HMAC SHA256 in Swift 4

后端 未结 3 2014
不思量自难忘°
不思量自难忘° 2020-12-17 03:03

I have a string and a key, which i want to generate an HMAC SHA256 from it. Although i\'m using 2 libs

IDZSwiftCommonCrypto and CryptoSwift

and this answer

3条回答
  •  轮回少年
    2020-12-17 03:44

    I've been using this:

    import Foundation
    
    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.cString(using: String.Encoding.utf8)
            let strLen = Int(self.lengthOfBytes(using: String.Encoding.utf8))
            let digestLen = algorithm.digestLength
            let result = UnsafeMutablePointer.allocate(capacity: digestLen)
            let keyStr = key.cString(using: String.Encoding.utf8)
            let keyLen = Int(key.lengthOfBytes(using: String.Encoding.utf8))
    
            CCHmac(algorithm.HMACAlgorithm, keyStr!, keyLen, str!, strLen, result)
    
            let digest = stringFromResult(result: result, length: digestLen)
    
            result.deallocate(capacity: digestLen)
    
            return digest
        }
    
        private func stringFromResult(result: UnsafeMutablePointer, length: Int) -> String {
            let hash = NSMutableString()
            for i in 0..

    You'll need to add #import to your Objective-C bridging header.

    Source: @thevalyreangroup on this github thread

提交回复
热议问题