开发者

Difference between android sha224 and python sha224

开发者 https://www.devze.com 2023-01-24 23:10 出处:网络
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 foll

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 passwor开发者_C百科d 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?


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

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


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();
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号