variable results using same inputs
Hello, when encrypting a password, I noticed my encryption function produces different outputs even with the same inputs.
Question: What causes them to be different every time?
This is the function I use to encrypt my passwords:
Code:
private String encryptPassword(String password) {
try{
byte[] passwordBytes = password.getBytes();
MessageDigest m = MessageDigest.getInstance("MD5");
m.reset();
for (int i=0; i<1000; i++){
m.update(passwordBytes);
m.digest();
}
return passwordBytes.toString();
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
}
return null;
}
Calling code:
Code:
System.out.println(password);
System.out.println(encryptPassword(password));
System.out.println(password);
System.out.println(encryptPassword(password));
System.out.println(password);
System.out.println(encryptPassword(password));
Output: (passwords masked, but they are the same)
******
[B@47cf34
******
[B@746d6d
******
[B@1bc26ee
Output from running the program a second time, no changes to the code or inputs:
******
[B@1bc26ee
******
[B@1a00355
******
[B@3af8a6
Re: variable results using same inputs
You are returning the toString() value of an array which does not reflect the contents of that array, rather properties of the array instance itself (which will be different for every call to the method). Try creating a new String with the given byte array. And note that m.digest returns something.