Nabeel Khan
Nabeel Khan

Reputation: 3983

Minimal way to get HMAC SHA512 in swift 3.1

I'm coding an app using xcode and swift 3.1

I need to create hmac sha512 hash for my api call to the server.

I konw there are various frameworks like CryptoSwift that provide us with such feature.

However I am interested to know if it's possible in native xcode / swift 3.1 without the use of any libraries or frameworks.

If not then why not?

Also, if I do need to use the library, what's the minimal method to get hmac sha512 based library code only?

Thanks.

Upvotes: 2

Views: 481

Answers (1)

sundance
sundance

Reputation: 3020

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>

You can look up here how to add the bridging header.

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

Upvotes: 3

Related Questions