简体   繁体   中英

How to transform JavaScript HMAC code to CryptoSwift implementation?

I want to transform this JavaScript HMAC code to Swift using CryptoSwift library.

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

What is the best way to do that?

This is what I tried, but did not return the correct code:

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

I also tried this, but it returns the same wrong code

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

I also tried to use HMCA from CryptoSwift directly. But I do not know what message I need to authenticate:

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

我自己发现了解决方案:

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

HAMC SHA256 in Common Crypto

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

Note:
Include #import <CommonCrypto/CommonCrypto.h> in a bridging header.
Add Security.framework to the project

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM