Ierative Java SHA-1 versus Python solution
I have a specific problem with hashing algorithms in Java. I have 2 clients, one is working in python and the other is working in Java (I know I could solve everything using only python, but now I almost need to use java).
Clients should compare pasted passwords in the same way (i.e.: if the PIN generates a hash on java clients , then the same hash should be generated by the python client.
I am reading here: Iterative hashing returns different values in Python and Java
And studied the official docs here: https://docs.oracle.com/javase/7/docs/api/java/security/MessageDigest.html
And it turned out that python allows seamless iterative coding, while java does not. I tried to solve the problem using the .clone () method as follows (java code):
// creation of SHA-1 instance:
MessageDigest message = MessageDigest.getInstance("SHA-1");
// construction of the string to hash:
String secretMessage = "0" + myPassWord + mySalt;
// updating the instance:
message.update(secretMessage.getBytes());
// cloning the instance:
MessageDigest messageClone = (MessageDigest) message.clone();
// digesting the clone: the result is of type byte[]:
byteResult = messageClone.digest();
// construction of the previousHash: this will be used in the
// next run of SHA-1 hashing. Python runs everything in lowercase.
// the hash is rendered as HEX characters String:
prevHash = (DatatypeConverter.printHexBinary(byteResult)).toLowerCase();
secretMessage = prevHash + "1" + myPassWord + mySalt;
message.update(secretMessage.getBytes());
// compute the final digest:
byteResult = message.digest();
// print it:
System.out.println(DatatypeConverter.printHexBinary(byteResult));
Now, running System.out.println on the first iteration (index "0"), the hashes match.
Unfortunately, something goes wrong on the next index, and I can't, for love's sake, understand what it is. I suspect it has something to do with how python converts strings and inserts it into the secretMessage variable.
For your information, here is the code in python:
digest2 = ""
for i in range (0, 2):
digest2 = sha1(digest2 + str(i) + password_to_hash + salt).hexdigest()
print digest2
source to share
The problem is that in a Java implementation, you feed MessageDigest
first the iteration line and then the second iteration line without flushing MessageDigest
, so in reality one hash is generated String
as:
"0" + pw + salt + sha-of-data-so-far + "1" + pw + salt
However, the python implementation starts a new hash for the second iteration and creates two hashes:
"0" + pw + salt
And then:
sha-of-iteration-1 + "1" + pw + salt
source to share