func hmacSha256(string:String, key:String) -> [UInt8] {
var mac = [UInt8](count: Int(CC_SHA256_DIGEST_LENGTH), repeatedValue: 0)
if let dataBytes = string.dataUsingEncoding(NSUTF8StringEncoding) {
if let keyBytes = key.dataUsingEncoding(NSUTF8StringEncoding) {
CCHmac(CCHmacAlgorithm(kCCHmacAlgSHA256),
keyBytes.bytes, keyBytes.length,
dataBytes.bytes, dataBytes.length,
&mac);
}
}
return mac;
}
let hash = hmacSha256("InputString", key:"keyString")
print("hash: \(hash)")
hash: [41, 226, 70, 65, 222, 197, 202, 78, 138, 62, 40, 93, 225, 228, 181, 178, 108, 158, 238, 25, 74, 199, 116, 106, 96, 142, 216, 239, 41, 18, 245, 156]
Notes:
Add Security.framework
to the project
For iOS:
Common Crypto must be imported, add
#import <CommonCrypto/CommonCrypto.h>
to the bridging header.
For OSX just import
#import <CommonCrypto/CommonCrypto.h>