3

I am writing a Java application that is required to locally authenticate a user with a password and then use the password to generate an AES-256 key for local file encryption/decryption.

I understand the principles behind everything and how important proper algorithm choice, rounds of hashing and crypto-random salt generation is. With this in mind, I use the PBKDF2WithHmacSHA256 algorithm supported in Java 8, a 16 byte salt value generated with Java's SecureRandom and 250 000 rounds of hashing. My question lies in the implementation, the following is a (simplified) version of how I generate the hash and users key. The code was shortened for the sake of this post and values were hard-coded for again, simplification of the post.

int iterations = 250000;
String password = "password";
String salt = "salt";

SecretKeyFactory factory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA256");
char[] passwordChars = password.toCharArray();
KeySpec spec = new PBEKeySpec(passwordChars, salt.getBytes(), iterations, 256);
SecretKey key = factory.generateSecret(spec);

byte[] passwordHash = key.getEncoded();

SecretKey secret = new SecretKeySpec(key.getEncoded(), "AES");

This code is based on the concatenation of a few different open source Java projects I have gone through that also leverage the PBKDF2 algorithm for either password hashing, AES key generation, or both.

My question here is, is this actually secure? I have a feeling that the use of the same SecretKey value "key" to generate the SecretKey "secret" and generate the hash is incorrect.If this is true, can anyone advise the correct method to leverage the PBKDF2WithHmacSHA512 algorithm to generate a password hash and derive a AES key?

dFrancisco
  • 2,691
  • 1
  • 13
  • 26
  • Possible duplicate of [How to login and encrypt data with the same password/key](https://security.stackexchange.com/questions/23409/how-to-login-and-encrypt-data-with-the-same-password-key) – AndrolGenhald Feb 05 '18 at 22:28
  • 1
    Basically, use PBKDF2 for the encryption key, then hash the encryption key for the password hash. – AndrolGenhald Feb 05 '18 at 22:29
  • Hash the encryption key using what? A further secure number of rounds of PBKDF2 with new salt? – dFrancisco Feb 05 '18 at 22:30
  • 1
    If the api allows you to easily add an additional PBKDF2 round to the current hash that'd probably be the best way to go, otherwise I think a single `SHA512` would be enough. See also [here](https://security.stackexchange.com/a/167426/151903). – AndrolGenhald Feb 05 '18 at 22:40
  • 1
    If you're not protecting a plain-text password, but rather an "impossible" to guess hash, you don't need a heavy-handed hashing, something quick will be fine. – dandavis Feb 05 '18 at 23:11
  • @AndrolGenhald (and dandavis) It makes sense, thank you for the feedback! – dFrancisco Feb 06 '18 at 02:05

0 Answers0