【问题标题】:SHA256 Hash algorithm produces different results in iOS using Common Crypto and OpenSSLSHA256 哈希算法在 iOS 中使用 Common Crypto 和 OpenSSL 产生不同的结果
【发布时间】:2016-12-15 06:52:30
【问题描述】:

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

【问题讨论】:

  • 在 openSSL 案例中,length 的价值是多少?
  • 与其他 Hash 结果相同(32 字节)。 iOS CC/Android/MacOS OpenSSL Cmd 行哈希结果:。而 OpenSSL 哈希结果:
  • 你确定吗? sizeof(bin) 在 32 位设备上应为 4,在 64 位设备上应为 8。你可能想要length = data.length;
  • 保罗,请原谅我的愚蠢,就是这样 :) 现在它产生了相同的结果

标签: android ios hash sha256 commoncrypto


【解决方案1】:
NSInteger length = sizeof(bin);

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

你想要的是

NSInteger length = data.length

因为这将为您提供要散列的字节数

【讨论】:

    猜你喜欢
    • 2023-02-23
    • 1970-01-01
    • 1970-01-01
    • 2015-03-29
    • 2016-04-11
    • 1970-01-01
    • 2011-12-12
    • 2018-06-14
    • 1970-01-01
    相关资源
    最近更新 更多