【发布时间】:2017-10-16 23:34:04
【问题描述】:
我环顾四周,但只能找到使用 Objective-C 创建 SHA256 哈希的示例。有没有办法只用 Swift4 来做到这一点?
【问题讨论】:
-
SHA256 in swift的可能重复
我环顾四周,但只能找到使用 Objective-C 创建 SHA256 哈希的示例。有没有办法只用 Swift4 来做到这一点?
【问题讨论】:
你可以这样使用:
func ccSha256(data: Data) -> Data {
var digest = Data(count: Int(CC_SHA256_DIGEST_LENGTH))
_ = digest.withUnsafeMutableBytes { (digestBytes) in
data.withUnsafeBytes { (stringBytes) in
CC_SHA256(stringBytes, CC_LONG(data.count), digestBytes)
}
}
return digest
}
你可以这样调用:
let str = "givesomestringtoencode"
let data = ccSha256(data: str.data(using: .utf8)!)
print("sha256 String: \(data.map { String(format: "%02hhx", $0) }.joined())")
在桥接头文件中添加以下内容:
#import <CommonCrypto/CommonHMAC.h>
【讨论】:
CommonCrypto。