Swift 4中的HMAC SHA256

时间:2018-10-12 17:59:42

标签: swift cryptography swift4 hmac cryptoswift

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

IDZSwiftCommonCryptoCryptoSwift

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

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

对于CryptoSwift

filter

但是没有什么能像真理的源头一样运作。知道吗?

4 个答案:

答案 0 :(得分:13)

如果您面向 iOS 13.0+ 或 macOS 10.15+,请使用 Apple 的 CryptoKit

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

答案 1 :(得分:2)

我一直在使用它:

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 :(得分:1)

用于 HMAC 加密的Swift 4.2解决方案

不久前我遇到了同样的问题,所以我编写了一个简单的框架,可在所有平台上的Swift中使用- iOS macOS tvOS

它叫做 EasyCrypt ,您可以在这里找到它: https://github.com/lukszar/EasyCrypt

此框架使您可以使用HMAC算法使用密钥对消息进行加密。 用法很简单,如下所示:

<select size="10" name="ListBox" id="ListBox" onclick="ListBox_Click()" style="width:98%;display:block;margin-bottom:10px">
        <option value="10" UseCount="0" Score="170" FirearmType="2">TRAINING</option>
        <option value="9" UseCount="0" Score="0" Type="1">TRAINING ONE</option>
        <option value="12" UseCount="0" Score="0" Type="1">TRAINING TWO</option>
        <option value="5" UseCount="5" Score="0" FirearmType="2">TRAINING THREE</option>
        <option value="1" UseCount="31" Score="225" Type="1">TRAINING FOUR</option>     
        <option value="1" UseCount="0" Score="50" Type="1">TEST</option>

您可以使用Carthage快速安装。在项目内部,您可以找到带演示的Playground,并附有说明。

答案 3 :(得分:0)

您使用CryptoSwift做错了。

对于将来的读者,这是操作方法:

let result = try! HMAC(key: key, variant: .sha256).authenticate(message.bytes)