+44 (791) 5698 086

How to use CommonCrypto for HMAC in Swift 4

After numerous hours trying to understand how CommonCrypto works with xCode and how to use it to generate a hmac hash, I finally made it work! In this tutorial you will see how to:

  1. What is CommonCrypto library and why to use it
  2. How to include CommonCrypto (and CommonHMAC) in your xcode project
  3. How to Generate a hmac (sha256 and others) encryption successfully using CommonCrypto only, without using any third party packages.

In the end you can also download the linked sample project with running code as an example.

This code was tested on 7th may 2018 on xcode 9.3 using swift 4.

What is CommonCrypto Library & Why to use it

CommonCrypto is a builtin library for various cryptographic functions with in swift 4. It’s coded in objective C and thus it appears to be hard for new comers on how to use it. However if you are determined like me to avoid any third party addons or modules (including cocoapods and carthage ones) then you are at the right place.

CommonCrypto doesn’t require you to add any packages to your computer or even to download anything from the internet. It’s all already there inside your xcode and swift 4.

How to include CommonCrypto library in your xcode project

To begin using CommonCrypto library, we need to include it in our xcode project first. You can either include the complete CommonCrypto library or include only sub part of it like CommonHMAC if you want to use any specific part only.

There are two ways to include CommonCrypto library in your project:

  1. Using Bridging Header
  2. Using Module manager

Both methods can be used. However each of them is best suited in their own situations, however you can use any of the ones you wish.

Include CommonCrypto library using Bridging Header method

This method is ideal if you’re already using Objective C based code in your swift project. However that’s not the absolute requirement. You can add a bridging header even if you are not already using any objective c code in your project.

To add the briding header, follow these steps:

1. Create a new file and name it anything. However it’s customary to name it yourprojectname-Bridging-Header.h.

2. Add this code to the new file:

#import <CommonCrypto/CommonCrypto.h>

You can also use any part of CommonCrypto if you’re sure which one you will be needing. E.g. for HMAC only use:

#import <CommonCrypto/CommonHMAC.h>

The complete file would look something like this:

Commonhmac in swift xcode

Make sure that you add it before the #endif line (as shown in the image above.

3. Click on the projects main name in the assets list on the left in xcode (see image below). Then in the right pane, click Targets > Build settings and then in search bar type “bridging” and it will filter out the items related to it. From those items click in front of Objective-C Bridging Header and in the popup enter the file name with path (in our case it’s hmacTest/Test-Bridging-header.h). You might also need to enter the same for the Project too (above targets).

How to Generate HMAC using CommonCrypto or CommonHMAC

Now once we have setup the briding header for CommonCrypto or CommonHMAC (based on your requirement), lets see how can we use this to generate a HMAC hash.

For this, we will first have to add some code to our project. You can do it in already existing files or it’s better to create a new one. Name it HMAC.swift (or anything you like) and add this swift 4 code to it:

//
//
//  HMAC.swift
//  hmacTest
//
//  Created by khan on 07/05/2018.
//  Copyright © 2018 khan. All rights reserved.
//

import Foundation

/*
 Usage:
 1. Add an ObjC bridging header.
 2. Import <CommonCrypto/CommonCrypto.h> in the header.
 */


//    kCCHmacAlgSHA1,
//    kCCHmacAlgMD5,
//    kCCHmacAlgSHA256,
//    kCCHmacAlgSHA384,
//    kCCHmacAlgSHA512,
//    kCCHmacAlgSHA224
enum HmacAlgorithm {
    case sha1, md5, sha256, sha384, sha512, sha224
    var algorithm: CCHmacAlgorithm {
        var alg = 0
        switch self {
        case .sha1:
            alg = kCCHmacAlgSHA1
        case .md5:
            alg = kCCHmacAlgMD5
        case .sha256:
            alg = kCCHmacAlgSHA256
        case .sha384:
            alg = kCCHmacAlgSHA384
        case .sha512:
            alg = kCCHmacAlgSHA512
        case .sha224:
            alg = kCCHmacAlgSHA224
        }
        return CCHmacAlgorithm(alg)
    }
    var digestLength: Int {
        var len: Int32 = 0
        switch self {
        case .sha1:
            len = CC_SHA1_DIGEST_LENGTH
        case .md5:
            len = CC_MD5_DIGEST_LENGTH
        case .sha256:
            len = CC_SHA256_DIGEST_LENGTH
        case .sha384:
            len = CC_SHA384_DIGEST_LENGTH
        case .sha512:
            len = CC_SHA512_DIGEST_LENGTH
        case .sha224:
            len = CC_SHA224_DIGEST_LENGTH
        }
        return Int(len)
    }
}

extension String {
    func hmac(algorithm: HmacAlgorithm, key: String) -> String {
        var digest = [UInt8](repeating: 0, count: algorithm.digestLength)
        CCHmac(algorithm.algorithm, key, key.count, self, self.count, &digest)
        let data = Data(bytes: digest)
        return data.map { String(format: "%02hhx", $0) }.joined()
    }
}

And to use it, simply use this format anywhere in your code:

    let str = "This is our string."
    let key = "TheKeyForEncryption."
    let hmac_sha1 = str.hmac(algorithm: .sha1, key: key)
    print(hmac_sha1)
    let hmac_md5 = str.hmac(algorithm: .sha512, key: key)
    print(hmac_md5)

And so on. You can use the encryption type of your own too.

Download: You can download the working copy of this project from github here: https://github.com/nabtron/hmacTest

Please let me know if you have any queries or suggestions for this code. If you want me to fix some issue in your swift project or do this or any similar task for you, you can contact me too.

Leave a Reply

Your email address will not be published. Required fields are marked *

Who are we?

Nabtron team includes web, desktop software and mobile apps developers along with SEO professionals.

We are available 24 hours, 7 days a week. Contact us now for anything you need!

Join our mailing list

Lets become friend :) What's your name & email?