如何将 hash_hmac 函数从 PHP 准确地转换为 iOS Swift?

How to transform hash_hmac function from PHP to iOS Swift exactly?

你好,我需要将 hash_hmac php 方法实现到 swift 并尝试这个:

var hexString = ""
var result: [CUnsignedChar]
if let cKey = keyStr.cString(using: String.Encoding.utf8),
    let cData = messageStr.cString(using: String.Encoding.utf8)
{
    let algo  = CCHmacAlgorithm(kCCHmacAlgSHA256)
    result = Array(repeating: 0, count: Int(CC_SHA256_DIGEST_LENGTH))
    CCHmac(algo, cKey, cKey.count, cData, cData.count, &result)
} else {
    fatalError("ERROR...")
}

for byte in result {
    hexString += String(format:"%2hhx", UInt8(byte))
}

print(hexString)

但这不像PHP完全那样模拟。

我试过这段代码:

let secretData : Data = messageStr.data(using: .utf8)!
let signatureData : Data = keyStr.data(using: .utf8)!
let digest = UnsafeMutablePointer<UInt8>.allocate(capacity:Int(CC_SHA256_DIGEST_LENGTH))
var hmacContext = CCHmacContext()
CCHmacInit(&hmacContext, CCHmacAlgorithm(kCCHmacAlgSHA256), [UInt8](secretData), secretData.count)
CCHmacUpdate(&hmacContext, [UInt8](signatureData), [UInt8](signatureData).count)
CCHmacFinal(&hmacContext, digest)
let cryptData = Data(bytes: digest, count: Int(CC_SHA256_DIGEST_LENGTH))
macStr = cryptData.hexEncodedString()

但是不行...

编辑:

message: a3FQZHJ1Z0hnOFhpZ2xkWg==8v8Fs6LXKTJOha69tsvUew==
key: u6KuXJLIUwEUl7noY8J8H1ffDRwLC/5gjaWW1qTQ3hE=
swift output: 37987524d1a379d67b2bae0a1618296d48b7a1f058a3b5816bf8070cb2fdf2ec
php output: 30f39f78a24ae2e6037114708f97fae1f3fede8dabece012a12b6625f3329302

Swift代码有误:

CCHmacInit(&hmacContext, CCHmacAlgorithm(kCCHmacAlgSHA256), [UInt8](secretData), secretData.count)
CCHmacUpdate(&hmacContext, [UInt8](signatureData), [UInt8](signatureData).count)

CCHmacInit拿钥匙。
CCHmacUpdate 取数据。
问题代码有倒退。

Note:

在这种情况下,有一个更容易使用且更不容易出错的一次性 HMAC 函数:
CCHmac(CCHmacAlgorithm algorithm, const void *key, size_t keyLength, const void *data, size_t dataLength, void *macOut);

解决了这个问题:(Swift 3)

extension Data {

    func hexEncodedString() -> String {
        return map { String(format: "%02hhx", [=10=]) }.joined()
    }
}

func HMAC_CREATOR(MIX_STR mixStr:String,KEY_DATA_UINT8 keyDataUint8:Array<UInt8>) -> String {
        let signatureData : Data = mixStr.data(using: .utf8)!
        let digest = UnsafeMutablePointer<UInt8>.allocate(capacity:Int(CC_SHA256_DIGEST_LENGTH))
        var hmacContext = CCHmacContext()
        CCHmacInit(&hmacContext, CCHmacAlgorithm(kCCHmacAlgSHA256), (keyDataUint8), (keyDataUint8.count))
        CCHmacUpdate(&hmacContext, [UInt8](signatureData), [UInt8](signatureData).count)
        CCHmacFinal(&hmacContext, digest)
        let macData = Data(bytes: digest, count: Int(CC_SHA256_DIGEST_LENGTH))
        return  macData.hexEncodedString()
    }