如何从生成 PBKDF2 密码的字节数组中获取字符串

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

我使用来自 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();
}

问题是当我这样做时:

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

我得到一个非常奇怪的字符串,类似于 ���:,但我想要一个可以保存在数据库中的普通字符串。我的错误是什么?

如果您想将 byte[] 之类的二进制数据转换为字符串,您通常会将其编码为 Hex 或 Base64 格式。 Base64比hex更小,所以我推荐你使用这个。

对于 Base64,您可以使用 java.util.Base64 因为 Java 8:

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

For Hex AFAIR Java 不包含必要的代码。你可以使用例如Hex encode from Apache common codec :

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