'How to translate Python HMAC code to Swift
I've been struggling to convert the code from Python to Swift and can't get the same signature value. I've been trying different combinations in Swift but my requests are failing as the signature is incorrect. I've tried looking at other HMAC posts in swift but haven't had much luck.
Python code:
hashed = hmac.new(base64.urlsafe_b64decode(
(secretMessage_string).encode('utf-8'),
),
msg=message_string.encode('utf-8'),
digestmod=hashlib.sha256,
)
signature = base64.urlsafe_b64encode(hashed.digest()).decode()
Swift code:
let keyString = "specialKey"
let messageString = "This is a basic message"
let key = SymmetricKey(data: Data(keyString.utf8))
let signature = HMAC<SHA256>.authenticationCode(for: Data(messageString.utf8), using: key)
Solution 1:[1]
Try this:
import CryptoKit
let keyString = "specialKey"
let keyData = Data(base64Encoded: keyString)!
let messageString = "This is a basic message"
let key = SymmetricKey(data: keyData)
let signatureObj = HMAC<SHA256>.authenticationCode(for: Data(messageString.utf8), using: key)
let signatureHex = Data(signatureObj).map { String(format: "%02hhx", $0) }.joined()
let signature = Data(signatureHex.utf8).base64EncodedString()
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Cyrille |