代码之家  ›  专栏  ›  技术社区  ›  Konstantinos Natsios

Swift 4中的HMAC SHA256

  •  0
  • Konstantinos Natsios  · 技术社区  · 6 年前

    IDZSwiftCommonCrypto CryptoSwift

    this answer

    对我来说什么都不管用。我的真相来源于这两个网站

    https://myeasywww.appspot.com/utility/free/online/Crypt_Decrypt-MD5-AES-HMAC-SHA-DES-RABBIT/en?command=UTILITY&ID=2

    https://www.freeformatter.com/hmac-generator.html#ad-output

    你知道什么能在这里工作吗?一些代码示例

    对于IDZSwiftCommonCrypto

    func getHMacSHA256(forMessage message: String, key: String) -> String? {
        let hMacVal = HMAC(algorithm: HMAC.Algorithm.sha256, key: key).update(string: message)?.final()
        if let encryptedData = hMacVal {
            let decData = NSData(bytes: encryptedData, length: Int(encryptedData.count))
            let base64String = decData.base64EncodedString(options: .lineLength64Characters)
            print("base64String: \(base64String)")
            return base64String
        } else {
            return nil
        }
    }
    

    对于CryptoSwift

        let password: Array<UInt8> = Array(payload.utf8)
        let salt: Array<UInt8> = Array("somekey".utf8)
    
        let signedBody = try? HKDF(password: password, salt: salt, variant: .sha256).calculate()
    

    2 回复  |  直到 6 年前
        1
  •  13
  •   Christina    6 年前

    我一直在用这个:

    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<CUnsignedChar>.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<CUnsignedChar>, length: Int) -> String {
            let hash = NSMutableString()
            for i in 0..<length {
                hash.appendFormat("%02x", result[i])
            }
            return String(hash).lowercased()
        }
    }
    

    你需要加上 #import <CommonCrypto/CommonHMAC.h> 到你的Objective-C桥接头。

    @thevalyreangroup on this github thread

        2
  •  12
  •   Eric    4 年前

    如果您的目标是iOS 13.0+或macOS 10.15+,请使用苹果的加密套件

    import CryptoKit
    
    let secretString = "my-secret"
    let key = SymmetricKey(data: secretString.data(using: .utf8)!)
    
    let string = "An apple a day keeps anyone away, if you throw it hard enough"
    
    let signature = HMAC<SHA256>.authenticationCode(for: string.data(using: .utf8)!, using: key)
    print(Data(signature).map { String(format: "%02hhx", $0) }.joined()) // 1c161b971ab68e7acdb0b45cca7ae92d574613b77fca4bc7d5c4effab89dab67
    
        3
  •  7
  •   funct7    5 年前

    你用CryptoSwift做错事了。

    对于未来的读者,以下是如何做到这一点:

    let result = try! HMAC(key: key, variant: .sha256).authenticate(message.bytes)
    
        4
  •  3
  •   Community CDub    5 年前

    Swift 4.2解决方案 HMAC公司

    不久前,我也遇到了同样的问题,所以我编写了一个简单的框架,用于所有平台上的Swift- 马科斯

    它叫 容易的 https://github.com/lukszar/EasyCrypt

    这个框架允许您使用HMAC算法用密钥加密消息。 用法很简单,如下所示:

    let crypto = EasyCrypt(secret: "mySecretKey", algorithm: .sha256)
    let result = crypto.hash("This is very secret text to encrypt")
    let otherResult = crypto.hash("This is another secret text to encrypt")
    
    print("result: ", result)
    print("otherResult: ", otherResult)