Reputation: 3983
I'm trying to implement HMAC SHA512
encryption to a data string before sending it to the server, as it's their requirement.
I have found many possible solutions for that online, however all of them require including some module or framework.
Isn't HMAC
and SHA512
not supported by swift 3.1 natively?
Sorry if it's a stupid question, I'm relatively new to swift.
If it's available, how can I simply encrypt some data using hmac sha512
?
Thanks.
Upvotes: 1
Views: 170
Reputation: 3020
CommonCrypto is the native way to do encryption on Apple devices. You do not need any module or framework, you just add a bridging header and import CommonCrypto:
#import <CommonCrypto/CommonCrypto.h>
You then can compute your HMAC with a simple extension (Swift 4):
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
If you use Swift on a non-Apple device you indeed need to use an external framework to do encryption.
Upvotes: 1