Search code examples
javasecuritypbkdf2

How to get String from byte array which is generated PBKDF2 password


I use solution from here:

public static byte[] getEncryptedPassword(String password, byte[] salt,  int iterations,  int derivedKeyLength) throws NoSuchAlgorithmException, InvalidKeySpecException {
    KeySpec spec = new PBEKeySpec(password.toCharArray(), salt, iterations, derivedKeyLength * 8);
    SecretKeyFactory f = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA256");
    return f.generateSecret(spec).getEncoded();
}

The problem is that when I do:

System.out.println(new String(getEncryptedPassword(p,s,i,l)));

I get a very strange string, something like ���:, but I want a normal string which I can save in DB. What is my mistake?


Solution

  • If you want to convert binary data like a byte[] to a String you usually encode it to Hex or Base64 format. Base64 is smaller than hex, therefore I would recommend you to use this one.

    For Base64 you can use java.util.Base64 since Java 8:

    String base64encoded = Base64.getEncoder().encodeToString(getEncryptedPassword(p,s,i,l)));

    For Hex AFAIR Java does not contain the necessary code. You can use e.g. the Hex encode from Apache common codec :

    String hexEncoded = Hex.encodeHexString(getEncryptedPassword(p,s,i,l)));