What I’m trying to do is to convert a password typed into a jPasswordField into SHA-256 hash. I was wandering around and found how to do this if I’ve got password saved as a string but the field I’m using is returning char[] so I ended up just guessing what to do… at first I’ve got different results even if the password was the same but now I believe I’m closer as it’s a constant; but it’s still not it as the output of
echo -n 'abc' | sha256sum
is
ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad
while the output of my action (for the same input) is
86900f25bd2ee285bc6c22800cfb8f2c3411e45c9f53b3ba5a8017af9d6b6b05
My action looks like this:
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);
}
}
Any ideas?
You’ve pretty much nailed it. just took the hard/wrong way converting from
char[]toString->new String(password)is all you need. (hint, if you find yourself manually converting between bytes and chars, you’re probably doing it wrong).as a side note, exceptions are “thrown” for a reason. that makes it easy to skip the following code which shouldn’t be executed when the exception is thrown. by catching and turning the exceptions into “if” blocks, you make the code more complex than it needs to be.