Last active
November 8, 2016 19:06
-
-
Save davetrux/0db65e368765681953ce to your computer and use it in GitHub Desktop.
HMAC algorithm for iOS
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Based on: http://stackoverflow.com/questions/24099520/commonhmac-in-swift
and http://www.jokecamp.com/blog/examples-of-creating-base64-hashes-using-hmac-sha256-in-different-languages/