Create a gist now

Instantly share code, notes, and snippets.

What would you like to do?
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