HMAC Algorithm in Swift

In your Xcode project, make a bridging header and include this header file:

#import <CommonCrypto/CommonHMAC.h>

Then, create a Swift file. We will create the hashing function as an extension method to String.

import Foundation

extension String {

    func digestHMac256(key: String) -> String! {

        let str = self.cStringUsingEncoding(NSUTF8StringEncoding)
        let strLen = self.lengthOfBytesUsingEncoding(NSUTF8StringEncoding)

        let digestLen = Int(CC_SHA256_DIGEST_LENGTH)
        let result = UnsafeMutablePointer.alloc(digestLen)

        let keyStr = key.cStringUsingEncoding(NSUTF8StringEncoding)
        let keyLen = key.lengthOfBytesUsingEncoding(NSUTF8StringEncoding)

        let algorithm = CCHmacAlgorithm(kCCHmacAlgSHA256)

        CCHmac(algorithm, keyStr!, keyLen, str!, strLen, result)

        let data = NSData(bytesNoCopy: result, length: digestLen)

        let hash = data.base64EncodedStringWithOptions(.allZeros)

        return hash
    }
}

The function takes in the string to use as the key. In HMAC, this key is shared between the client and server.

Use the function like this, where result ends up being the Base64 encoded string:

    let data = "Message"
    
    let result = data.digestHMac256("secret")

GitHub Gist

Other references:

CommonHMAC in Swift

Examples of creating base64 hashes using HMAC SHA256 in different languages

Posted on:

Comments are closed.