Java has a convinient class PBEKeySpec that lets you generate a secret key from a password using values of iteration count, key length and salt for decryption purposes. See the example below.
private static Key getPasswordBasedKey(String cipher, int keySize, char[] password) throws NoSuchAlgorithmException, InvalidKeySpecException {
byte[] salt = new byte[100];
SecureRandom random = new SecureRandom();
random.nextBytes(salt);
PBEKeySpec pbeKeySpec = new PBEKeySpec(password, salt, 1000, keySize);
SecretKey pbeKey = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA256").generateSecret(pbeKeySpec);
return new SecretKeySpec(pbeKey.getEncoded(), cipher);
}
But what if salt is not a part of specific case of encryption? Then in order to get correct output I'll have to decrypt without salt as well.
But in this case constructor of PBEKeySpec(char[] password, byte[] salt, int iterationCount, int keyLength)
will throw an exception (NullPointerException
if salt is null, IllegalArgumentException
if it's an empty array).
So my question is: is there any way available in Java to generate secret key from a password taking account of iterationCount and keyLength but skipping salt?
Why I need it:
- Data was encrypted this way (no salt) on the other end. I can't change it.
- So now i need a tool in Java that will let me decrypt it with no requirement to have a salt (but still with use of iteration count and key length).
- I can't find such tool.