在 Swift 4 中我们可以使用
var md5: String? {
guard let data = self.data(using: .utf8) else { return nil }
let hash = data.withUnsafeBytes { (bytes: UnsafePointer<Data>) -> [UInt8] in
var hash: [UInt8] = [UInt8](repeating: 0, count: Int(CC_MD5_DIGEST_LENGTH))
CC_MD5(bytes, CC_LONG(data.count), &hash)
return hash
}
return hash.map { String(format: "%02x", $0) }.joined()
}
但在 Swift 5 中,withUnsafeBytes
使用 UnsafeRawBufferPointer
而不是 UnsafePointer
。如何修改md5函数?
最佳答案
Swift 5 版本:使用 UnsafeRawBufferPointer
作为闭包参数的类型,并使用 bytes.baseAddress
将地址传递给 Common Crypto 函数:
import Foundation
import CommonCrypto
extension String {
var md5: String {
let data = Data(self.utf8)
let hash = data.withUnsafeBytes { (bytes: UnsafeRawBufferPointer) -> [UInt8] in
var hash = [UInt8](repeating: 0, count: Int(CC_MD5_DIGEST_LENGTH))
CC_MD5(bytes.baseAddress, CC_LONG(data.count), &hash)
return hash
}
return hash.map { String(format: "%02x", $0) }.joined()
}
}
(注意字符串到UTF-8数据的转换不能失败,不需要返回optional。)
iOS 13 已弃用 CC_MD5。您可以改用 CC_SHA256。
关于ios - 在 Swift 5 中获取字符串 md5,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55356220/