I basically am trying to take a String and do what would look like this in php:
$signature= base64_encode(hash_hmac('sha1', $data, $secretKey, true));
However, do it in Swift... I see a lot of posts about other people trying to do things with CommonCrypto, but that module doesn't seem to install.
So 3 questions really:
My current code looks like this:
var authString:String = "PUT\nTEST=BLAH\nTEST2=BLAHBLAHBLAH"
let hmacResult:String = authString.sha1()
...
extension String {
func sha1() -> String {
//Do Something...
}
}
You should definitely use CommonCrypto because it is already available on every device, well tested and fast. You just need to add a bridging header containing
#import <CommonCrypto/CommonCrypto.h>
As already stated, you can look up here how to add the bridging header.
To calculate the HMAC you just need this extension:
extension String {
func hmac(key: String) -> String {
var digest = [UInt8](repeating: 0, count: Int(CC_SHA1_DIGEST_LENGTH))
CCHmac(CCHmacAlgorithm(kCCHmacAlgSHA1), key, key.count, self, self.count, &digest)
let data = Data(bytes: digest, count: Int(CC_SHA1_DIGEST_LENGTH))
return data.map { String(format: "%02hhx", $0) }.joined()
}
}
Example:
let result = "test".hmac(key: "test")
Result:
0c94515c15e5095b8a87a50ba0df3bf38ed05fe6
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With