在 iOS 中生成 SHA256

Generating SHA256 in iOS

我尝试使用 Arcane 库和以下数据在 iOS 中生成 SHA256:

字符串:Amount=50&BillerID=59&ChannelID=2&Context=34|check|test&ReturnURL=https://uat.myfatoora.com/ReceiptPOC.aspx&TxnRefNum=000000000020003&UserName=DCS

键:71DD0F73AFFBB47825FF9864DDE95F3B

结果是 409dc622b3bef5c9fc46e45c3210111fcb4536d3a55833316fe0dc8154b3ea34

我认为是正确的。但是,Windows 对应方正在使用以下代码生成 SHA256:

Windows Phone Source Code:

public static string HmacSha256(string secretKey, string value)
    {
        var msg = CryptographicBuffer.ConvertStringToBinary(value, BinaryStringEncoding.Utf8);
        byte[] convertedHash = new byte[secretKey.Length / 2];

        for (int i = 0; i < secretKey.Length / 2; i++)
        {
            convertedHash[i] = (byte)Int32.Parse(secretKey.Substring(i * 2, 2), System.Globalization.NumberStyles.HexNumber);
        }

        // Create HMAC.
        var objMacProv = MacAlgorithmProvider.OpenAlgorithm(MacAlgorithmNames.HmacSha256);
        CryptographicHash hash = objMacProv.CreateHash(convertedHash.AsBuffer());

        hash.Append(msg);
        return CryptographicBuffer.EncodeToHexString(hash.GetValueAndReset());

    }

结果是: 94a20ca39c8487c7763823ec9c918d9e38ae83cb741439f6d129bcdef9edba73 这和我得到的不一样。有人可以帮我解决这个问题,让我知道上面的代码在做什么以及如何在 iOS.

中复制它

编辑:

 iOS Source code

 let key = self.md5(string: "71DD0F73AFFBB47825FF9864DDE95F3B")

    let hash = HMAC.SHA256(str, key: key)

Windows代码获取字符串,将其解释为十六进制数,一次将两个字符转换为一个字节。

您的 Mac 代码最喜欢采用字符串 原样 。由于密钥以“71”开头,您的 windows 代码将其视为值为 0x71 = 129 的单个字节,您的 Mac 代码将其视为值为“7”= 55 和“1”的两个字节' = 49。

您需要做的就是像在 Windows 上一样转换 Mac 上的字节。您可能不得不做一些不可思议的事情,并查看 Mac 库的源代码以了解它如何进行实际的哈希计算。

这里的关键是你需要将你的秘密,它是一个十六进制字符串,转换成 NSData。换句话说,NSData 字节流会 "look" 喜欢这个秘密。

这应该可以满足您的要求:

    // Hex string to NSData conversion from here 
    NSString *secret = @"71DD0F73AFFBB47825FF9864DDE95F3B";
    NSData *dataIn = [@"Amount=50&BillerID=59&ChannelID=2&Context=34|check|test&ReturnURL=https://uat.myfatoora.com/ReceiptPOC.aspx&TxnRefNum=000000000020003&UserName=DCS" dataUsingEncoding:NSUTF8StringEncoding];
    NSMutableData *macOut = [NSMutableData dataWithLength:CC_SHA256_DIGEST_LENGTH];

    secret = [secret stringByReplacingOccurrencesOfString:@" " withString:@""];
    NSMutableData *secretData = [[NSMutableData alloc] init];
    unsigned char whole_byte;
    char byte_chars[3] = {'[=10=]','[=10=]','[=10=]'};
    int i;
    for (i=0; i < [secret length]/2; i++) {
        byte_chars[0] = [secret characterAtIndex:i*2];
        byte_chars[1] = [secret characterAtIndex:i*2+1];
        whole_byte = strtol(byte_chars, NULL, 16);
        [secretData appendBytes:&whole_byte length:1];
    }

    CCHmac(kCCHmacAlgSHA256, secretData.bytes, secretData.length, dataIn.bytes, dataIn.length, macOut.mutableBytes);

    NSMutableString *stringOut = [NSMutableString stringWithCapacity:macOut.length];
    const unsigned char *macOutBytes = macOut.bytes;

    for (NSInteger i=0; i<macOut.length; ++i) {
        [stringOut appendFormat:@"%02x", macOutBytes[i]];
    }

    NSLog(@"dataIn: %@", dataIn);
    NSLog(@"macOut: %@", macOut);
    NSLog(@"stringOut: %@", stringOut);

输出:

2016-09-27 20:18:54.181 JKS[27562:5321334] dataIn: <416d6f75 6e743d35 30264269 6c6c6572 49443d35 39264368 616e6e65 6c49443d 3226436f 6e746578 743d3334 7c636865 636b7c74 65737426 52657475 726e5552 4c3d6874 7470733a 2f2f7561 742e6d79 6661746f 6f72612e 636f6d2f 52656365 69707450 4f432e61 73707826 54786e52 65664e75 6d3d3030 30303030 30303030 32303030 33265573 65724e61 6d653d44 4353>

2016-09-27 20:18:54.181 JKS[27562:5321334] macOut: <94a20ca3 9c8487c7 763823ec 9c918d9e 38ae83cb 741439f6 d129bcde f9edba73>

2016-09-27 20:18:54.181 JKS[27562:5321334] stringOut: 94a20ca39c8487c7763823ec9c918d9e38ae83cb741439f6d129bcdef9edba73

Updated with Swift (code should be cleaned up)

// 
func generateHMAC(key: String, data: String) -> String {
    let keyData = key.dataFromHexadecimalString()! as NSData
    let dataIn = data.data(using: .utf8)! as NSData
    var result: [CUnsignedChar]
    result = Array(repeating: 0, count: Int(CC_SHA256_DIGEST_LENGTH))
    CCHmac(CCHmacAlgorithm(kCCHmacAlgSHA256), keyData.bytes, keyData.length, dataIn.bytes, dataIn.length, &result)

    let hash = NSMutableString()
    for val in result {
        hash.appendFormat("%02hhx", val)
    }

    return hash as String
}

您可以使用此扩展将十六进制字符串转换为 Data

// Modified slightly 
extension String {

    func dataFromHexadecimalString() -> Data? {
        var data = Data(capacity: characters.count / 2)

        let regex = try! NSRegularExpression(pattern: "[0-9a-f]{1,2}", options: .caseInsensitive)
        regex.enumerateMatches(in: self, options: [], range: NSMakeRange(0, characters.count)) { match, flags, stop in
            let byteString = (self as NSString).substring(with: match!.range)
            var num = UInt8(byteString, radix: 16)
            data.append(&num!, count: 1)
        }

        return data
    }
}

并使用做类似的事情:

    let secret = "71DD0F73AFFBB47825FF9864DDE95F3B"
    let value = "Amount=50&BillerID=59&ChannelID=2&Context=34|check|test&ReturnURL=https://uat.myfatoora.com/ReceiptPOC.aspx&TxnRefNum=000000000020003&UserName=DCS"

    print("\(generateHMAC(key: secret, data: value))")

你的输出应该是 94a20ca39c8487c7763823ec9c918d9e38ae83cb741439f6d129bcdef9edba73

您的桥接头中需要 #import <CommonCrypto/CommonCrypto.h>

#import <CommonCrypto/CommonHMAC.h>

+ (NSString *)hmacSHA256EncryptString{


    NSString * parameterSecret = @"input secret key";
    NSString *plainString = @"input encrypt content string";
    const char *secretKey  = [parameterSecret cStringUsingEncoding:NSUTF8StringEncoding];
    const char *plainData = [plainString cStringUsingEncoding:NSUTF8StringEncoding];
    unsigned char cHMAC[CC_SHA256_DIGEST_LENGTH];
    CCHmac(kCCHmacAlgSHA256, secretKey, strlen(secretKey), plainData, strlen(plainData), cHMAC);
    NSData *HMACData = [NSData dataWithBytes:cHMAC length:sizeof(cHMAC)];
    const unsigned char *bufferChar = (const unsigned char *)[HMACData bytes];
    NSMutableString *hmacString = [NSMutableString stringWithCapacity:HMACData.length * 2];
    for (int i = 0; i < HMACData.length; ++i){
        [hmacString appendFormat:@"%02x", bufferChar[i]];
    }
    return hmacString;
    
}