如何将JavaScript HMAC代码转换为CryptoSwift实现?

时间:2017-12-23 11:03:39

标签: javascript ios swift sha256 cryptoswift

我想使用CryptoSwift库将此JavaScript HMAC代码转换为Swift。

var crypto = require("crypto");
var currentDate = Moment.utc().format("YYYYMMDDHH");
var hmac = crypto.createHmac("sha256", "secretTokenKey123");
hmac.update(currentDate);
var code = hmac.digest("hex").toUpperCase();

最好的方法是什么?

这是我尝试过的,但没有返回正确的代码:

    let formatter = DateFormatter()
    formatter.dateFormat = "yyyyMMddHH"
    let dateString = formatter.string(from: Date())
    let baseString = secretToken + dateString
    print(baseString.sha256().uppercased())

我也试过这个,但它返回相同的错误代码

    var digest = SHA2(variant: .sha256)
    var bytes: Array<UInt8>?
    do {
        _ = try digest.update(withBytes: secretToken.bytes)
        _ = try digest.update(withBytes: dateString.bytes)
        bytes = try digest.finish()
    } catch {}
    if let result = bytes?.toHexString().uppercased() {
        print(result)
    }

我也尝试直接使用CryptoSwift的HMCA。但我不知道我需要验证什么消息:

HMAC(key: secretToken.bytes, variant: .sha256).authenticate(???)

2 个答案:

答案 0 :(得分:2)

我自己刚刚发现了解决方案:

HMAC(key: secretToken.bytes, variant: .sha256).authenticate(dateString.bytes).toHexString().uppercased()

答案 1 :(得分:0)

普通加密中的HAMC SHA256

func hmacSHA256(message:Data, key:Data) -> Data {
    var macData = Data(count: Int(CC_SHA256_DIGEST_LENGTH))

    macData.withUnsafeMutableBytes {macBytes in
        message.withUnsafeBytes {messageBytes in
            key.withUnsafeBytes {keyBytes in
                CCHmac(CCHmacAlgorithm(kCCHmacAlgSHA256),
                       keyBytes,     key.count,
                       messageBytes, message.count,
                       macBytes)
            }
        }
    }
    return macData
}

let clearData = "clearData0123456".data(using:.utf8)!
let keyData   = "keyData8901234562".data(using:.utf8)!
let hmacData  = hmacSHA256(message:clearData, key:keyData)
print("hmacData: \(String(describing: hmacData as NSData))")

hmacData:fcc487ce7dc1115a69a37dc3710610a87ad2fc9c85e2e0a52f0e7ee1dc9407c1

注意:
在桥接标题中加入#import <CommonCrypto/CommonCrypto.h>Security.framework添加到项目