如何从字节数组中获取String,生成PBKDF2密码

时间:2018-03-31 15:43:04

标签: java security pbkdf2

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

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

1 个答案:

答案 0 :(得分:2)

如果要将byte[]之类的二进制数据转换为String,通常会将其编码为Hex或Base64格式。 Base64小于十六进制,因此我建议你使用这个。

对于Base64,您可以使用自Java 8以来的java.util.Base64

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

对于Hex AFAIR Java不包含必要的代码。你可以用例如来自Hex encodeApache common codec

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