2

I have am trying to use PBKDF2 to store passwords. I am then using the code with the password hashes it generated on a different machine.

I am using this method to encrypt my passwords:

public String pwdEncodePBKDF2(String unencryptedPassword,String salt) { try { if(salt.isEmpty()) { salt = generateSalt(SystemSecurity.SALTLENGTH); } String algorithm = "PBKDF2WithHmacSHA1"; int derivedKeyLength = 160; int iterations = 1000; KeySpec spec = new PBEKeySpec(unencryptedPassword.toCharArray(), salt.getBytes(), iterations, derivedKeyLength); SecretKeyFactory f = SecretKeyFactory.getInstance(algorithm); StringBuffer hexString = new StringBuffer(); byte[] mdbytes = f.generateSecret(spec).getEncoded(); for (int i=0;i<mdbytes.length;i++) { hexString.append(Integer.toHexString(0xFF & mdbytes[i])); } String hashedPassword = hexString.toString(); return hashedPassword + salt; } catch(Exception e) { e.printStackTrace(); throw new RuntimeException("Error computing hash: "+e.getMessage()); } } 

It works fine, but when I run it on a different machine (i.e. install my project on a different machine, with a database that has an encrypted of a default password from the machine I run on initially) I see that with the same salt and password it give me a different encryption. As far as I understand the SecretKeyFactory methods depend only on the inputs I give them, or do they depend on the machine I am running on as well?

If so, how can I save a default password for first installation with this security mechanism without running any extra code during installation?

Thank You!

1 Answer 1

1

I think the problem may be in different default String encodings.

Check that your strings use same encoding.

you can try to check bytes using

salt.getBytes() 
  • it return bytes in default encoding, may be machines has different encodings.

You can just replace salt.getBytes(), with somethink like salt.getBytes("UTF-8"); may be it will help.

Sign up to request clarification or add additional context in comments.

4 Comments

Which strings? I do not understand.
@user1114464 String unencryptedPassword,String salt
The salt seems to use String.getBytes(). Salts should be random bytes, so I don't understand the use of a string, unless it was encoded to be stored/transported in a String...
owlstead- You can see in the beginning of the code that I am generating a random string for a salt. Then I use getBytes because byte[] is the argument type for the PBEKeySpec. kornero - I will try that and write the result tomorrow. thank you.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.