SHA256 哈希结果在 Android 和 iOS 之间对于大数不同

SHA256 Hash results different across Android & iOS for Big numbers

我正在尝试对 BigInteger/BigNum 进行哈希运算,但在 Android/iOS 中得到了不同的结果。我需要获得相同的哈希结果,以便两个应用程序都按照 SRP 协议工作。仔细检查它对正数工作正常但对负数不起作用(第一个半字节大于 7)。不确定哪个是正确的,哪个是要调整以匹配另一个。

Android:

    void hashBigInteger(String s) {
    try {
        BigInteger a = new BigInteger(s, 16);
        MessageDigest sha = MessageDigest.getInstance("SHA-256");
        byte[] b = a.toByteArray();
        sha.update(b, 0, b.length);
        byte[] digest = sha.digest();
        BigInteger d = new BigInteger(digest);
        Log.d("HASH", "H = " + d.toString(16));
    } catch (NoSuchAlgorithmException e) {
        throw new UnsupportedOperationException(e);
    }
}

iOS:

void hashBigNum(unsigned char *c) {
    BIGNUM *n = BN_new();
    BN_hex2bn(&n, c);
    unsigned char   buff[ SHA256_DIGEST_LENGTH ];
    int             len  = BN_num_bytes(n);
    unsigned char * bin    = (unsigned char *) malloc( len );
    BN_bn2bin(n, bin);
    hash( SRP_SHA256, bin, len, buff ); 
    fprintf(stderr, "H: ");
    for (int z = 0; z < SHA256_DIGEST_LENGTH; z++)
        fprintf(stderr, "%2x", buff[z]);
    fprintf(stderr, "\n");
    free(bin);
}

结果:

Source String = "6F"
Android Hash = 65c74c15a686187bb6bbf9958f494fc6b80068034a659a9ad44991b08c58f2d2
iOS     Hash = 65c74c15a686187bb6bbf9958f494fc6b80068034a659a9ad44991b08c58f2d2

Source String = "FF"
Android Hash = 06eb7d6a69ee19e5fbdf749018d3d2abfa04bcbd1365db312eb86dc7169389b8
iOS     Hash = a8100ae6aa1940d0b663bb31cd466142ebbdbd5187131b92d93818987832eb89

一种方法是将大数字转换为字符串并获取它们的哈希值。

问题出在 JAVA 代码中。 new BigInteger(s, 16).toByteArray() 前导零不安全。 请参阅 Convert a string representation of a hex dump to a byte array using Java?

上的 post 评论

在Android中FF的位表示是0000000011111111而在iOS中是11111111。前导零是原因,因为 SHA256 哈希不同。

只需使用链接 post 的一种方法将十六进制更改为字节转换器即可获得相同的字节数组(没有零)。例如

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);
    }
}

为了正确的 HEX 打印,也将 BigInteger d = new BigInteger(digest); 更改为

BigInteger d = new BigInteger(1,digest);