SHA256 快速 [英] SHA256 in swift
问题描述
我想在我的项目中使用 sha256,但是在将 objC 代码重写为 swift 代码时遇到了一些麻烦.请帮帮我.我用了这个答案:如何在 iOS 中计算 SHA-2(最好是 SHA 256 或 SHA 512)哈希?
I want to use sha256 in my project, but I had some troubles rewriting objC code to swift code. Help me please. I used this answer: How can I compute a SHA-2 (ideally SHA 256 or SHA 512) hash in iOS?
这是我的代码
var hash : [CUnsignedChar]
CC_SHA256(data.bytes, data.length, hash)
var res : NSData = NSData.dataWithBytes(hash, length: CC_SHA256_DIGEST_LENGTH)
它给了我错误的一切,因为例如 swift 无法将 Int
转换为 CC_LONG
.
it gives me error everything because swift cannot convert Int
to CC_LONG
, for example.
推荐答案
你必须在 Int
和 CC_LONG
之间显式转换,因为 Swift 没有进行隐式转换,如 (Objective-)C.
You have to convert explicitly between Int
and CC_LONG
, because Swift does not
do implicit conversions, as in (Objective-)C.
您还必须将 hash
定义为所需大小的数组.
You also have to define hash
as an array of the required size.
func sha256(data : NSData) -> NSData {
var hash = [UInt8](count: Int(CC_SHA256_DIGEST_LENGTH), repeatedValue: 0)
CC_SHA256(data.bytes, CC_LONG(data.length), &hash)
let res = NSData(bytes: hash, length: Int(CC_SHA256_DIGEST_LENGTH))
return res
}
或者,您可以使用 NSMutableData
来分配所需的缓冲区:
Alternatively, you can use NSMutableData
to allocate the needed buffer:
func sha256(data : NSData) -> NSData {
let res = NSMutableData(length: Int(CC_SHA256_DIGEST_LENGTH))
CC_SHA256(data.bytes, CC_LONG(data.length), UnsafeMutablePointer(res.mutableBytes))
return res
}
Swift 3 和 4 的更新:
func sha256(data : Data) -> Data {
var hash = [UInt8](repeating: 0, count: Int(CC_SHA256_DIGEST_LENGTH))
data.withUnsafeBytes {
_ = CC_SHA256($0, CC_LONG(data.count), &hash)
}
return Data(bytes: hash)
}
Swift 5 更新:
func sha256(data : Data) -> Data {
var hash = [UInt8](repeating: 0, count: Int(CC_SHA256_DIGEST_LENGTH))
data.withUnsafeBytes {
_ = CC_SHA256($0.baseAddress, CC_LONG(data.count), &hash)
}
return Data(hash)
}
这篇关于SHA256 快速的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!