SHA256 Hash results different across Android & iOS for Big numbers

怎甘沉沦 提交于 2019-12-03 03:23:39
pedrofb

The problem is in the JAVA code. new BigInteger(s, 16).toByteArray() is not safe for leading zeros. See poster comment at Convert a string representation of a hex dump to a byte array using Java?

The bit representation of FF with Android is 00000000 11111111 whereas in iOS is 11111111. The leading zeros is the reason because the SHA256 hashing is different.

Just change the Hex to byte converter using one method of the linked post to get the same byte array (without zeros). For example

public static byte[] hexStringToByteArray(String s) {
    int len = s.length();
    byte[] data = new byte[len / 2];
    for (int i = 0; i < len; i += 2) {
        data[i / 2] = (byte) ((Character.digit(s.charAt(i), 16) << 4)
                             + Character.digit(s.charAt(i+1), 16));
    }
    return data;
}

void hashBigInteger(String s){
    try{
        MessageDigest sha = MessageDigest.getInstance("SHA-256");
        byte b[] = hexStringToByteArray(s);
        sha.update(b,0,b.length);
        byte digest[] = sha.digest();
        BigInteger d = new BigInteger(1,digest);

        System.out.println("H "+d.toString(16));
    }catch (NoSuchAlgorithmException e){
        throw new UnsupportedOperationException(e);
    }
}

To proper HEX printing, change also BigInteger d = new BigInteger(digest); with

BigInteger d = new BigInteger(1,digest); 

One way is to convert your big numbers to strings and get hash of them.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!