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]
注
は、IOSのためのプロジェクト
にSecurity.framework
を追加します。
一般的な暗号はimでなければなりませんブリッジされたヘッダーに
#import <CommonCrypto/CommonCrypto.h>
を追加します。 OSX用
はちょうど
#import <CommonCrypto/CommonCrypto.h>
http://stackoverflow.com/questions/24099520/commonhmac-in-swift、http://stackoverflow.com/questions/26970807/implementing-hmac-and-をインポートsha1-encryption-in-swift、http://stackoverflow.com/questions/35620960/generating-hmac-sha256-from-byte-array-in-swift –