本文介绍了Swift 4 中的 HMAC SHA256的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个字符串和一个密钥,我想从中生成一个 HMAC SHA256.虽然我使用 2 个库

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

IDZSwiftCommonCryptoCryptoSwift

这个答案

没有什么对我真正有用.我的事实来源是这两个网站

Nothing really worked for me. My source of truth are those 2 websites

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#广告输出

他们总是为我的情况生成正确的哈希键.知道什么可以在这里工作吗?一些代码示例

Which they always generate the correct hash key for my case.Any idea in what can work here? Some code samples

对于 IDZSwiftCommonCrypto

For 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

And for 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()

但没有什么比真相的来源更有效.有什么想法吗?

But nothing really works like the sources of truth.Any idea?

推荐答案

我一直在用这个:

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 桥接头.

You'll need to add #import <CommonCrypto/CommonHMAC.h> to your Objective-C bridging header.

来源:@thevalyreangroup 在这个 github 线程上

这篇关于Swift 4 中的 HMAC SHA256的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

06-07 03:35