Skip to content

Instantly share code, notes, and snippets.

@davetrux
Last active November 8, 2016 19:06
Show Gist options
  • Save davetrux/0db65e368765681953ce to your computer and use it in GitHub Desktop.
Save davetrux/0db65e368765681953ce to your computer and use it in GitHub Desktop.
HMAC algorithm for iOS
import Foundation
//You have to create a bridging header in your project containing:
// #import <CommonCrypto/CommonHMAC.h>
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<CUnsignedChar>.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
}
}