5

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...
        }
    }
MrDrewskii
  • 91
  • 1
  • 10
  • Compare http://stackoverflow.com/questions/25761344/how-to-crypt-string-to-sha1-with-swift or http://stackoverflow.com/questions/25424831/cant-covert-nsdata-to-nsstring-swift (and there are probably more ...) – To use CommonCrypto you need a bridging header, this is described here: http://stackoverflow.com/questions/24002369/how-to-call-objective-c-code-from-swift. – Martin R Mar 17 '15 at 06:11
  • but I need to do the hash with a key? how can i do that? – MrDrewskii Mar 17 '15 at 06:19
  • 1
    What about this: http://stackoverflow.com/questions/24099520/commonhmac-in-swift ? – Martin R Mar 17 '15 at 06:23

2 Answers2

4

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
Bhuvan Bhatt
  • 3,276
  • 2
  • 18
  • 23
sundance
  • 2,930
  • 1
  • 20
  • 25
0

Checkout this repo: https://github.com/0xa6a/HMAC

It also contains a demo proj for reference.

wzso
  • 3,482
  • 5
  • 27
  • 48