Reputation: 83
I am currently working on a project (in swift 3/4) where I need to hash a HTTP request that is formatted as so:
{"request": {"method": "getMyPeople",
"params": {"api_key": 00de5089d590e413807343166da22a45,
"user_id": 8 }, "id": "1"}}
I am trying to hash in SHA-256 with a secret key, something that looks like this:
6b107c7ebebf056e1c45924d0546d35e
What I need:
What I have:
Solutions I have tried: My most recent attempt is Zaph's post here (https://stackoverflow.com/a/39249920/8093921).
Where my issue occurs: My issue seems to occurring when I try to convert the form of
hashSHA256: <aabc766b 6b357564 e41f4f91 2d494bcc bfa16924 b574abbd ba9e3e9d a0c8920a>
as seen in Zaph's post, they leave it in this form where I need it in form of a string in hex.
If anyone need any more clarification please let me know. Thank you in advance for the help!
Upvotes: 5
Views: 10946
Reputation: 3040
I admit that it can be confusing to get everything together but the final solution is quite simple:
extension String {
func hmac(key: String) -> String {
var digest = [UInt8](repeating: 0, count: Int(CC_SHA256_DIGEST_LENGTH))
CCHmac(CCHmacAlgorithm(kCCHmacAlgSHA256), key, key.count, self, self.count, &digest)
let data = Data(bytes: digest)
return data.map { String(format: "%02hhx", $0) }.joined()
}
}
Example:
let result = "test".hmac(key: "test")
Result:
88cd2108b5347d973cf39cdf9053d7dd42704876d8c9a9bd8e2d168259d3ddf7
Upvotes: 17