1 回答

TA貢獻1851條經驗 獲得超5個贊
我想通了。SHA-256 的二進制結果必須格式化為十六進制數字字符串。
這是工作代碼:
String password = "secret123";
MessageDigest digest = MessageDigest.getInstance("SHA-256");
Charset scs = StandardCharsets.UTF_8;
byte[] encodedhash = digest.digest(password.getBytes(scs));
String hash = toHexString(encodedhash);
String bcrypt = BCrypt.hashpw(hash, BCrypt.gensalt());
使用十六進制字符串,如下所示:
private static char toHex(int nibble) {
final char[] hexDigit = {'0','1','2','3','4','5','6','7','8','9','a','b','c','d','e','f'};
return hexDigit[nibble & 0xF];
}
public static String toHexString(byte[] bytes) {
StringBuffer sb = new StringBuffer(bytes.length*2);
for(int i = 0; i < bytes.length; i++) {
sb.append(toHex(bytes[i] >> 4) );
sb.append(toHex(bytes[i]) );
}
return sb.toString();
}
添加回答
舉報