将散列字节数组转换为String

Pet*_*sik 0 java string hash bytearray

如果我做的事情

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();
Run Code Online (Sandbox Code Playgroud)

如何将此哈希值转换为字符串,以便将其保存到数据库中?我尝试过,new String(hash, "UTF-8");但这样会产生格式错误的字符l??0\?w?c??Q?.

Zim*_*oot 5

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