Question

For an application prototype I'm creating a simple user login. The Password of the user will then be hashed using sha224 and transferred to the back-end. The Problem I am facing right now is the following. The password that was stored in the DB (also hashed using sha224) seems to look a little different then the hash I am sending. I use the following code to create the hashes.

Given Password == test

Python

from hashlib import sha224
sha224("test").hexdigest()

android

MessageDigest sha224 = MessageDigest.getInstance("SHA-224");
sha224.update(key.getBytes());

byte[] digest = sha224.digest();
StringBuffer buffer = new StringBuffer();

for(int i = 0; i < digest.length; i++) {
 buffer.append(String.valueOf(Integer.toHexString(0xFF & digest[i])));
}

return buffer.toString();

What now will be produced looks like this and I will post the two hashes directly underneath each other. (The first one is python and the second android)

90a3ed9e32b2aaf4c61c410eb925426119e1a9dc53d4286ade99a809 90a3ed9e32b2aaf4c61c41eb925426119e1a9dc53d4286ade99a89

They are almost the same but the python hash has two 0s more. Do you guys have any idea why?

Was it helpful?

Solution

You're not formatting the hex values on the Android properly; leading 0s are being dropped.

buffer.append(String.format("%02x", 0xFF & digest[i]));

OTHER TIPS

final MessageDigest mDigest = MessageDigest.getInstance("SHA-224");
byte[] messageDigest = mDigest.digest(toEncrypt.getBytes());
final BigInteger number = new BigInteger(1, messageDigest);
final String sha = number.toString(16);
final int diff = 32 - sha.length();
final StringBuilder finalSHA = new StringBuilder(32);
for (int i=0;i<diff;i++) {
 finalSHA.append("0");
}
finalSHA.append(sha);
return finalSHA.toString();

You are converting the hex to string in pairs of 2 at a time. The first zero that is dropped is at 23rd i.e. an odd position. This is a leading zero. You need to zero pad the converted hex digits where necessary. Alternative implementation without BigInteger:

MessageDigest sha224 = MessageDigest.getInstance("SHA-224");
sha224.update(key.getBytes());

byte[] digest = sha224.digest();
StringBuffer buffer = new StringBuffer();

for(int i = 0; i < digest.length; i++) {
  String hex_string = Integer.toHexString(0xFF & digest[i]);
  if(hex_string.length()==1) hex_string = "0"+hex_string;
  buffer.append(hex_string);
}

return buffer.toString();
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top