osx – Swift中的CommonHMAC

前端之家收集整理的这篇文章主要介绍了osx – Swift中的CommonHMAC前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我试图在Swift中创建一个字符串的HMAC SHA-1散列,但是无法弄清楚如何与API进行交互,因为它似乎不会导入CommonCrypto框架。我尝试过各种不同形式的“Import CommonCrypto”,并创建了一个桥接头文件,但没有任何区别。

奇怪的是,如果我创建一个Objective-C类,我可以与API交互没有任何问题,所以这似乎是独特的Swift。

另外如果有人可以告诉我在swift中相当于uint8_t的消息[CC_SHA1_DIGEST_LENGTH]我会非常感谢

你可以在Swift做到这一点。只需确保添加#import< CommonCrypto / CommonHMAC.h>到桥接Objective-C桥接头。
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)
    }

}
原文链接:https://www.f2er.com/swift/320685.html

猜你在找的Swift相关文章