我要做的是将输入的密码转换为 jPasswordField 为 SHA-256 哈希。如果我将密码保存为字符串,但我正在使用的字段正在返回 char[],我四处游荡并找到了如何做到这一点,所以我最终只是猜测该怎么做......起初我得到了即使密码相同,结果也会不同,但现在我相信我更接近了,因为它是一个常数;但它仍然不是它的输出
echo -n 'abc' | sha256sum
是
ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad
而我的动作的输出(对于相同的输入)是
86900f25bd2ee285bc6c22800cfb8f2c3411e45c9f53b3ba5a8017af9d6b6b05
我的动作是这样的:
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
NoSuchAlgorithmException noSuchAlgorithmException = null;
MessageDigest messageDigest = null;
try {
messageDigest = MessageDigest.getInstance("SHA-256");
} catch (NoSuchAlgorithmException ex) {
noSuchAlgorithmException = ex;
}
if (noSuchAlgorithmException != null) {
System.out.println(noSuchAlgorithmException.toString());
}
else {
UnsupportedEncodingException unsupportedEncodingException = null;
byte[] hash = null;
char[] password = jPasswordField1.getPassword();
StringBuffer stringBuffer = new StringBuffer();
for (char c : password) {
if (c > 0 && c < 16) {
stringBuffer.append("0");
}
stringBuffer.append(Integer.toHexString(c & 0xff));
}
String passwordString = stringBuffer.toString();
try {
hash = messageDigest.digest(passwordString.getBytes("UTF-8"));
} catch (UnsupportedEncodingException ex) {
unsupportedEncodingException = ex;
}
if (unsupportedEncodingException != null) {
System.out.println(unsupportedEncodingException.toString());
}
else {
stringBuffer = new StringBuffer();
for (byte b : hash) {
stringBuffer.append(String.format("%02x", b));
}
String passwordHashed = stringBuffer.toString();
System.out.println(passwordHashed);
}
}
有任何想法吗?