HMAC SHA256 in Swift 4

If you target iOS 13.0+ or macOS 10.15+, use Apple’s CryptoKit

import CryptoKit

let secretString = "my-secret"
let key = SymmetricKey(data: Data(secretString.utf8))

let string = "An apple a day keeps anyone away, if you throw it hard enough"

let signature = HMAC<SHA256>.authenticationCode(for: Data(string.utf8), using: key)
print(Data(signature).map { String(format: "%02hhx", $0) }.joined()) // 1c161b971ab68e7acdb0b45cca7ae92d574613b77fca4bc7d5c4effab89dab67

Leave a Comment