Hello I am using below code to encrypt a string. I found MD5 make working in -127 - +128 values.
I am getting value in minus for.
public static void main(String[] args) throws Exception {
String message = "smile";
encrypt("Jack the Bear");
}
public static void encrypt(String password) throws Exception {
byte byteData[] =null;
MessageDigest md = null;
try {
md = MessageDigest.getInstance("MD5");
md.update(password.getBytes("US-ASCII"));
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (NoSuchAlgorithmException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
byteData = md.digest();
System.out.println(Arrays.toString(byteData));
}
My Output : [101, 23, 66, 106, 91, -51, 6, 119, -13, 23, -101, 108, -122, 27, 20, -124]
Real output : [101, 23, 66, 106, 91, 205, 6, 119, 243, 23, 155, 108, 134, 27, 20, 132]
This is because the byte
type in Java (like almost all other types) is signed, which means it has a range of -128..127
.
If you want to convert this range to an unsigned range (0..255
), do this:
byte b = -2;
int i = b & 0xff;
Print your result byteData
like this:
for (byte b : byteData)
System.out.print((b & 0xff) + " ");
If you want to print the result in hexadecimal format:
for (byte b : byteData)
System.out.printf("%02x ", b);