Swift – HMAC SHA256 in Swift 4

cryptographycryptoswifthmacswiftswift4

I have a string and a key, which i want to generate an HMAC SHA256 from it. Although i'm using 2 libs

IDZSwiftCommonCrypto and CryptoSwift

and this answer

Nothing really worked for me. My source of truth are those 2 websites

https://myeasywww.appspot.com/utility/free/online/Crypt_Decrypt-MD5-AES-HMAC-SHA-DES-RABBIT/en?command=UTILITY&ID=2

and

https://www.freeformatter.com/hmac-generator.html#ad-output

Which they always generate the correct hash key for my case.
Any idea in what can work here? Some code samples

For IDZSwiftCommonCrypto

func getHMacSHA256(forMessage message: String, key: String) -> String? {
    let hMacVal = HMAC(algorithm: HMAC.Algorithm.sha256, key: key).update(string: message)?.final()
    if let encryptedData = hMacVal {
        let decData = NSData(bytes: encryptedData, length: Int(encryptedData.count))
        let base64String = decData.base64EncodedString(options: .lineLength64Characters)
        print("base64String: \(base64String)")
        return base64String
    } else {
        return nil
    }
}

And for CryptoSwift

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

But nothing really works like the sources of truth.Any idea?

Best Answer

If you target iOS 13.0+ or macOS 10.15+, use Apple's 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