2

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.

Nabeel Khan
  • 3,715
  • 2
  • 24
  • 37
  • 4
    Sure it's possible. It's just math. Look up the algorithm and write it. :) – Tom Harrington Jun 07 '17 at 00:36
  • Or pull it out of CryptoSwift, which includes SHA-512 in Swift without a framework underneath it. https://github.com/krzyzanowskim/CryptoSwift/blob/master/Sources/CryptoSwift/SHA2.swift – Rob Napier Feb 12 '18 at 23:52

1 Answers1

3

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
sundance
  • 2,930
  • 1
  • 20
  • 25