SHA256 哈希算法使用 Common Crypto 和 OpenSSL 在 iOS 中产生不同的结果

SHA256 Hash algorithm produces different results in iOS using Common Crypto and OpenSSL

Apple的Common Crypto和OpenSSL的Hash函数有区别吗?我正在尝试使用以下两种方法生成相同字符串的 SHA256,但都产生不同的结果。我在做什么不同的事吗?我的印象是 SHA256 算法在各个平台上都很常见,并且在 iOS、Android、Windows 等

中产生相同的结果

注意:当我在 Android 中使用 MessageDigest.getInstance("SHA-256") 尝试同样的事情时,我得到了与 CommonCrypto Hash 结果相同的结果,但 OpenSSL 结果不同。

// Apple Common Crypto - SHA256
- (NSData *)sha256:(NSData *)data {
    unsigned char hashResult[CC_SHA256_DIGEST_LENGTH];
    if ( CC_SHA256([data bytes], (unsigned int)[data length], hashResult) ) {
        NSData *sha256 = [NSData dataWithBytes:hashResult length:CC_SHA256_DIGEST_LENGTH];
        return sha256;
    }   
}

// SRP OpenSSL - SHA256
- (NSData *)sha256_2:(NSData *)data {
    unsigned char hashResult[SHA256_DIGEST_LENGTH];
    unsigned char *bin = (unsigned char *) [data bytes];
    NSInteger length = sizeof(bin);
    [_srpAuth hashWrapper:SRP_SHA256 input:bin size:length output:hashResult];
    NSData *sha256 = [NSData dataWithBytes:hashResult length:SHA256_DIGEST_LENGTH];
    return sha256;
}
NSInteger length = sizeof(bin);

将为您提供 unsigned char 指针的大小 - 在 32 位设备上为 4 个字节,在 64 位设备上为 8 个字节。

你要的是

NSInteger length = data.length

因为这会给你要散列的字节数