Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
683 views
in Technique[技术] by (71.8m points)

cryptography - HMAC SHA256 in Swift 4

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...