如何在 Swift 4 中复制 hash_hmac('sha256', $key, $secret_key) 函数?

How to replicate hash_hmac('sha256', $key, $secret_key) function in Swift 4?

我尝试生成 hash_hmac('sha256', $key, $secret_key) php 等价于 Swift 4 的函数但没有成功,在使用像 CommonCrypto、CryptoSwift 这样的库之后。我需要这些函数用于 API 身份验证,使用 Alamofire 库,这是一个很棒的库。因为我使用 Swift 4 与其他 Swift 库的兼容性不是很好。即使使用具有 Swift 4 的最新版本 (0.7.1) 的 CryptoSwift,我仍然会遇到很多兼容性错误,例如 enter image description here

首先,直接使用 SHA512 可能更好,众所周知,SHA 很容易被 GPU 破解,因此稍微增加内存规模是个不错的主意。

其次,使用 CommonCrypto 生成 HMAC 实际上非常容易,这是我使用的实现:

static func hmac(_ secretKey: inout [UInt8], cipherText: inout [UInt8], algorithm: CommonCrypto.HMACAlgorithm = .sha512) -> [UInt8] {
        var mac = [UInt8](repeating: 0, count: 64)
        CCHmac(algorithm.value, &secretKey, secretKey.count, &cipherText, cipherText.count, &mac)
        return mac
    }

算法定义如下:

enum HMACAlgorithm {
        case sha512

        var value: UInt32 {
            switch(self) {
            case .sha512:
                return UInt32(kCCHmacAlgSHA512)
            }
        }
    }

本例中我的密文是cipherText+IV。当您不使用 AES-GCM 时,似乎建议/推荐使用 HMAC IV+Cipher,但我无法向您提供有关原因的技术细节。

将数据或 NSData 转换为字节数组:

var byteArray = data.withUnsafeBytes { [UInt8](UnsafeBufferPointer(start: [=12=], count: data.count) }

使用数组的原因是性能比Data大幅提升,我不知道核心团队在做什么,但Data甚至比NSMutableData性能更差。

Swift 3/4:

带 MD5、SHA1、SHA224、SHA256、SHA384、SHA512 的 HMAC (Swift 3)

These functions will hash either String or Data input with one of eight cryptographic hash algorithms.

name参数指定哈希函数名称为字符串 支持的函数有 MD5、SHA1、SHA224、SHA256、SHA384 和 SHA512

此示例需要通用加密
必须要有项目的桥接头:
#import <CommonCrypto/CommonCrypto.h>
将 Security.framework 添加到项目中。

这些函数采用散列名称、要散列的消息、密钥和 return 摘要:


hashName: name of a hash function as String  
message:  message as Data  
key:      key as Data  
returns:  digest as Data  
func hmac(hashName:String, message:Data, key:Data) -> Data? {
    let algos = ["SHA1":   (kCCHmacAlgSHA1,   CC_SHA1_DIGEST_LENGTH),
                 "MD5":    (kCCHmacAlgMD5,    CC_MD5_DIGEST_LENGTH),
                 "SHA224": (kCCHmacAlgSHA224, CC_SHA224_DIGEST_LENGTH),
                 "SHA256": (kCCHmacAlgSHA256, CC_SHA256_DIGEST_LENGTH),
                 "SHA384": (kCCHmacAlgSHA384, CC_SHA384_DIGEST_LENGTH),
                 "SHA512": (kCCHmacAlgSHA512, CC_SHA512_DIGEST_LENGTH)]
    guard let (hashAlgorithm, length) = algos[hashName]  else { return nil }
    var macData = Data(count: Int(length))

    macData.withUnsafeMutableBytes {macBytes in
        message.withUnsafeBytes {messageBytes in
            key.withUnsafeBytes {keyBytes in
                CCHmac(CCHmacAlgorithm(hashAlgorithm),
                       keyBytes,     key.count,
                       messageBytes, message.count,
                       macBytes)
            }
        }
    }
    return macData

}

hashName: name of a hash function as String
message:  message as String
key:      key as String
returns:  digest as Data
func hmac(hashName:String, message:String, key:String) -> Data? {
    let messageData = message.data(using:.utf8)!
    let keyData = key.data(using:.utf8)!
    return hmac(hashName:hashName, message:messageData, key:keyData)
}

hashName: name of a hash function as String  
message:  message as String  
key:      key as Data  
returns:  digest as Data  
func hmac(hashName:String, message:String, key:Data) -> Data? {
    let messageData = message.data(using:.utf8)!
    return hmac(hashName:hashName, message:messageData, key:key)
}

// 例子

let clearString = "clearData0123456"
let keyString   = "keyData8901234562"
let clearData   = clearString.data(using:.utf8)!
let keyData     = keyString.data(using:.utf8)!
print("clearString: \(clearString)")
print("keyString:   \(keyString)")
print("clearData: \(clearData as NSData)")
print("keyData:   \(keyData as NSData)")

let hmacData1 = hmac(hashName:"SHA1", message:clearData, key:keyData)
print("hmacData1: \(hmacData1! as NSData)")

let hmacData2 = hmac(hashName:"SHA1", message:clearString, key:keyString)
print("hmacData2: \(hmacData2! as NSData)")

let hmacData3 = hmac(hashName:"SHA1", message:clearString, key:keyData)
print("hmacData3: \(hmacData3! as NSData)")

输出:

clearString: clearData0123456
keyString:   keyData8901234562
clearData: <636c6561 72446174 61303132 33343536>
keyData:   <6b657944 61746138 39303132 33343536 32>

hmacData1: <bb358f41 79b68c08 8e93191a da7dabbc 138f2ae6>
hmacData2: <bb358f41 79b68c08 8e93191a da7dabbc 138f2ae6>
hmacData3: <bb358f41 79b68c08 8e93191a da7dabbc 138f2ae6>