3

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?

Charles
  • 50,943
  • 13
  • 104
  • 142
philgiese
  • 623
  • 1
  • 7
  • 17

3 Answers3

4

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

buffer.append(String.format("%02x", 0xFF & digest[i]));
Ignacio Vazquez-Abrams
  • 776,304
  • 153
  • 1,341
  • 1,358
0
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();
Alex Orlov
  • 18,077
  • 7
  • 55
  • 44
0

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();
whatnick
  • 5,400
  • 3
  • 19
  • 35