小编典典

Swift中的CommonHMAC

swift

我正在尝试在Swift中创建字符串的HMAC
SHA-1哈希,但是由于它似乎没有导入CommonCrypto框架,因此无法弄清楚如何与API进行交互。我尝试了各种不同形式的“ import
CommonCrypto”并创建了一个桥接头文件,但没有一个起作用。

奇怪的是,如果我创建一个Objective-C类,那么我就可以与API交互而不会出现任何问题,因此这似乎是Swift特有的。

另外,如果有人可以告诉我uint8_t digest[CC_SHA1_DIGEST_LENGTH]Swift中的等效内容,我将不胜感激


阅读 333

收藏
2020-07-07

共1个答案

小编典典

您可以在Swift中完成。只要确保您添加#import <CommonCrypto/CommonHMAC.h>到桥接Objective-C桥接头即可。

更新: 对于Swift 4,请在此处使用Swift Package
Manager查看更好的解决方案:https :
//github.com/jernejstrasner/SwiftCrypto

enum CryptoAlgorithm {
    case MD5, SHA1, SHA224, SHA256, SHA384, SHA512

    var HMACAlgorithm: CCHmacAlgorithm {
        var result: Int = 0
        switch self {
        case .MD5:      result = kCCHmacAlgMD5
        case .SHA1:     result = kCCHmacAlgSHA1
        case .SHA224:   result = kCCHmacAlgSHA224
        case .SHA256:   result = kCCHmacAlgSHA256
        case .SHA384:   result = kCCHmacAlgSHA384
        case .SHA512:   result = kCCHmacAlgSHA512
        }
        return CCHmacAlgorithm(result)
    }

    var digestLength: Int {
        var result: Int32 = 0
        switch self {
        case .MD5:      result = CC_MD5_DIGEST_LENGTH
        case .SHA1:     result = CC_SHA1_DIGEST_LENGTH
        case .SHA224:   result = CC_SHA224_DIGEST_LENGTH
        case .SHA256:   result = CC_SHA256_DIGEST_LENGTH
        case .SHA384:   result = CC_SHA384_DIGEST_LENGTH
        case .SHA512:   result = CC_SHA512_DIGEST_LENGTH
        }
        return Int(result)
    }
}

extension String {

    func hmac(algorithm: CryptoAlgorithm, key: String) -> String {
        let str = self.cStringUsingEncoding(NSUTF8StringEncoding)
        let strLen = Int(self.lengthOfBytesUsingEncoding(NSUTF8StringEncoding))
        let digestLen = algorithm.digestLength
        let result = UnsafeMutablePointer<CUnsignedChar>.alloc(digestLen)
        let keyStr = key.cStringUsingEncoding(NSUTF8StringEncoding)
        let keyLen = Int(key.lengthOfBytesUsingEncoding(NSUTF8StringEncoding))

        CCHmac(algorithm.HMACAlgorithm, keyStr!, keyLen, str!, strLen, result)

        let digest = stringFromResult(result, length: digestLen)

        result.dealloc(digestLen)

        return digest
    }

    private func stringFromResult(result: UnsafeMutablePointer<CUnsignedChar>, length: Int) -> String {
        var hash = NSMutableString()
        for i in 0..<length {
            hash.appendFormat("%02x", result[i])
        }
        return String(hash)
    }

}
2020-07-07