hmac within Swift

I am pretty new to swift and have been struggling to find a solution to hashing a string into a string.


I need to take a string and hash it to sha512 and return as a string to pass via HTTP Header to a GET URL request.


I have seen some posts around using CommonCrypto, which has a lot of comments suggesting to not use this in Swift, but I've not found much else.


I am taking an API Secret key, hashing the URL and returning a string.


Would seem odd that Swift doesn't have Framework or classes for this.


Thanks in advance,


Bombhead

Accepted Reply

I have seen some posts around using CommonCrypto, which has a lot of comments suggesting to not use this in Swift, but I've not found much else.

CommonCrypto is definitely the right API for this. The problem is that it’s tricky to call from Swift, partly because it’s a low-level C API and partly for weird tooling issues (it doesn’t have a module map). If you’re doing simple stuff — creating an app that needs to calculate an HMAC, for example — my recommendation is that you wrap the necessary CommonCrypto function in a tiny Objective-C wrapper and call that from Swift. This post has a concrete example of how to do this.

Share and Enjoy

Quinn “The Eskimo!”
Apple Developer Relations, Developer Technical Support, Core OS/Hardware

let myEmail = "eskimo" + "1" + "@apple.com"

Replies

Have you looked at this:


https://developer.apple.com/library/content/documentation/Security/Conceptual/CertKeyTrustProgGuide/KeyGen.html


The date on the document is 2017, and there are Swift code examples, so I assume it's current.

I have seen some posts around using CommonCrypto, which has a lot of comments suggesting to not use this in Swift, but I've not found much else.

CommonCrypto is definitely the right API for this. The problem is that it’s tricky to call from Swift, partly because it’s a low-level C API and partly for weird tooling issues (it doesn’t have a module map). If you’re doing simple stuff — creating an app that needs to calculate an HMAC, for example — my recommendation is that you wrap the necessary CommonCrypto function in a tiny Objective-C wrapper and call that from Swift. This post has a concrete example of how to do this.

Share and Enjoy

Quinn “The Eskimo!”
Apple Developer Relations, Developer Technical Support, Core OS/Hardware

let myEmail = "eskimo" + "1" + "@apple.com"