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(???)
I just discovered the solution myself: