如果我做类似的事情

int keyLength = 160; // because SHA1 generates 160-bit hashes
int iterations = 20 * 1000; //standard is 2000 but let's be more secure here

KeySpec spec = new PBEKeySpec(password.toCharArray(), generateSalt(), iterations, keyLength);
SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA1");
byte[] hash = keyFactory.generateSecret(spec).getEncoded();


我如何将此哈希转换为String以便可以将其保存到DB中?我尝试了new String(hash, "UTF-8");,但是给出了格式错误的字符,如l��0\�w�c��Q�

最佳答案

您需要将字节数组编码为Base64 string,然后在从数据库中读取字节数组时将其解码回字节数组。请注意,编码后的字符串将比原始字节数组大33%左右。

关于java - 将哈希字节数组转换为String,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/16245631/

10-12 06:05