Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to do HMAC-SHA1 in swift

Tags:

swift

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:

  1. Is CommonCrypto the correct way to do this?
  2. If so, how do I add the framework?
  3. If CommonCrypto isn't the best way to do this, what is?

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...
        }
    }
like image 560
MrDrewskii Avatar asked Sep 28 '22 12:09

MrDrewskii


1 Answers

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
like image 171
sundance Avatar answered Oct 07 '22 18:10

sundance