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)")
哈希:[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]
注意事项:
将Security.framework 添加到项目中
对于 iOS:
Common Crypto必须导入,添加
#import <CommonCrypto/CommonCrypto.h>
到桥接头。
对于 OSX 只需导入
#import <CommonCrypto/CommonCrypto.h>