gpt4 book ai didi

java - 在数据库中存储盐 - 字符还是二进制?

转载 作者:太空宇宙 更新时间:2023-11-03 12:17:23 24 4
gpt4 key购买 nike

我已经设置了一个相当基本的密码散列和加盐系统,用于在我的数据库中保存密码。它工作正常,但我不太确定盐是如何储存的。

目前我在 byte[] 数组中创建它,然后将其转换为字符串,然后将其存储在数据库中。

我唯一担心的是每个 salt 都以 [B@ 开头,例如:[B@b24f11[B@1e71a51>/p>

可以这样存储吗,还是我也应该将它保留为 byte[] 数组并将其作为二进制数据存储在数据库中?或者干点别的?

public class PasswordHasher {

// calculates a hash, given a password and a salt
public static String getHash(String pass, String salt) {
String hashedPassword = null;
try{
MessageDigest md = MessageDigest.getInstance("SHA-1");
md.update(salt.getBytes()); //update digest to include salt
byte[] hashedBytes = md.digest(pass.getBytes());

// convert byte array to hex
StringBuilder sb = new StringBuilder();
for (int i=0;i<hashedBytes.length;i++) {
sb.append(Integer.toHexString((int) hashedBytes[i] & 0xFF));
}
hashedPassword = sb.toString();

}catch(NoSuchAlgorithmException e){
e.printStackTrace();
}
return hashedPassword;
}

// calculates a hash, then returns both hash and salt to store in DB
public static String[] registerHashAndSalt(String pass){
String salt = getSalt();
String hashedPassword = getHash(pass, salt);

String[] hashAndSalt = {hashedPassword, salt};
return hashAndSalt;
}

// creates a random salt
private static String getSalt(){
SecureRandom sr = new SecureRandom();
byte[] salt = new byte[16];
sr.nextBytes(salt);
return salt.toString();
}
}

最佳答案

您没有将字节转换为字符串。您在 byte[] 上调用 toString(),它返回数组类型 ([B),后跟 @ 符号和数组的hashCode。

使用 base 64 或十六进制编码将字节转换为可打印的字符串。

关于java - 在数据库中存储盐 - 字符还是二进制?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21500781/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com