Swift 中的 SHA512 哈希字符串
Hash string with SHA512 in Swift
任何人都知道如何在 swift 中重现 PHP 散列方法 hash('SHA512', $value, true) ?我尝试将 CommonCrypto C 库与此代码一起使用:
extension String {
func digest(length:Int32, gen:(data: UnsafePointer<Void>, len: CC_LONG, md: UnsafeMutablePointer<UInt8>) -> UnsafeMutablePointer<UInt8>) -> String {
var cStr = [UInt8](self.utf8)
var result = [UInt8](count:Int(length), repeatedValue:0)
gen(data: &cStr, len: CC_LONG(cStr.count), md: &result)
let output = NSMutableString(capacity:Int(length))
for r in result {
output.appendFormat("%02x", r)
}
return String(output)
}
}
并像这样使用它:
var digest = salted.digest(CC_SHA512_DIGEST_LENGTH, gen: {(data, len, md) in CC_SHA512(data,len,md)})
但是我没有得到正确的输出
编辑:
我有一些 PHP 代码:
echo base64_encode(hash('sha512', '8yOrBmkd', true)); // output: rlltLWeWaQCrfNTYMa0CcIs0mfLoHGAynrd+d8H65+rGAzHS/BSWsumwSmcxF9aAG9TIzXx+HOjArPyLL3herg==
我希望我的 swift 代码输出相同的内容。 Base64编码没问题:
let utf8str = input.dataUsingEncoding(NSUTF8StringEncoding)!.base64EncodedStringWithOptions(NSDataBase64EncodingOptions(rawValue: 0))
let base64Encoded = utf8str!.base64EncodedStringWithOptions(NSDataBase64EncodingOptions(rawValue: 0))
print("Encoded: \(base64Encoded)")
但散列部分 return 输出与此 PHP 代码相同的值:
echo base64_encode(hash('sha512', '8yOrBmkd', false)); // output: YWU1OTZkMmQ2Nzk2NjkwMGFiN2NkNGQ4MzFhZDAyNzA4YjM0OTlmMmU4MWM2MDMyOWViNzdlNzdjMWZhZTdlYWM2MDMzMWQyZmMxNDk2YjJlOWIwNGE2NzMxMTdkNjgwMWJkNGM4Y2Q3YzdlMWNlOGMwYWNmYzhiMmY3ODVlYWU=
Swift 底部有 3 个实现。
代码不需要那么复杂或扩展:
func sha512Hex(string string: String) -> String {
var digest = [UInt8](count: Int(CC_SHA512_DIGEST_LENGTH), repeatedValue: 0)
if let data = string.dataUsingEncoding(NSUTF8StringEncoding) {
CC_SHA512(data.bytes, CC_LONG(data.length), &digest)
}
var digestHex = ""
for index in 0..<Int(CC_SHA512_DIGEST_LENGTH) {
digestHex += String(format: "%02x", digest[index])
}
return digestHex
}
//测试:
let hexDigest = sha512Hex(string:"8yOrBmkd")
print("hexDigest:\n\(hexDigest)")
输出:
hexDigest:
ae596d2d67966900ab7cd4d831ad02708b3499f2e81c60329eb77e77c1fae7eac60331d2fc1496b2e9b04a673117d6801bd4c8cd7c7e1ce8c0acfc8b2f785eae
只是返回字节数组:
func sha512(string string: String) -> [UInt8] {
var digest = [UInt8](count: Int(CC_SHA512_DIGEST_LENGTH), repeatedValue: 0)
let data = string.dataUsingEncoding(NSUTF8StringEncoding)!
CC_SHA512(data.bytes, CC_LONG(data.length), &digest)
return digest
}
//测试:
let digestRaw = sha512(string:"8yOrBmkd")
print("decimal array:\n\(digestRaw)")
print("hexadecimal:\n\(NSData(bytes:digestRaw, length:digestRaw.count).description)")
输出:
decimal array:
[174, 89, 109, 45, 103, 150, 105, 0, 171, 124, 212, 216, 49, 173, 2, 112, 139, 52, 153, 242, 232, 28, 96, 50, 158, 183, 126, 119, 193, 250, 231, 234, 198, 3, 49, 210, 252, 20, 150, 178, 233, 176, 74, 103, 49, 23, 214, 128, 27, 212, 200, 205, 124, 126, 28, 232, 192, 172, 252, 139, 47, 120, 94, 174]
hexadecimal:
ae596d2d67966900ab7cd4d831ad02708b3499f2e81c60329eb77e77c1fae7eac60331d2fc1496b2e9b04a673117d6801bd4c8cd7c7e1ce8c0acfc8b2f785eae
Base64 输出:
func sha512Base64(string string: String) -> String {
let digest = NSMutableData(length: Int(CC_SHA512_DIGEST_LENGTH))!
if let data = string.dataUsingEncoding(NSUTF8StringEncoding) {
CC_SHA512(data.bytes, CC_LONG(data.length), UnsafeMutablePointer<UInt8>(digest.mutableBytes))
}
return digest.base64EncodedStringWithOptions(NSDataBase64EncodingOptions([]))
}
//测试:
let digestBase64 = sha512Base64(string:"8yOrBmkd")
print("Base64:\n\(digestBase64)")
输出:
Base64:
rlltLWeWaQCrfNTYMa0CcIs0mfLoHGAynrd+d8H65+rGAzHS/BSWsumwSmcxF9aAG9TIzXx+HOjArPyLL3herg==
Swift 3
func hashSHA512(data:Data) -> String? {
var hashData = Data(count: Int(CC_SHA512_DIGEST_LENGTH))
_ = hashData.withUnsafeMutableBytes {digestBytes in
data.withUnsafeBytes {messageBytes in
CC_SHA512(messageBytes, CC_LONG(data.count), digestBytes)
}
}
// For hexadecimal output:
return hashData.map { String(format: "%02hhx", [=16=]) }.joined()
// For Base64 output use this instead of the above:
// return data.base64EncodedString()
}
已弃用文档部分的示例:
带 MD5、SHA1、SHA224、SHA256、SHA384、SHA512 的 HMAC (Swift 3+)
These functions will hash either String or Data input with one of eight cryptographic hash algorithms.
name 参数指定哈希函数名称为字符串
支持的函数有 MD5、SHA1、SHA224、SHA256、SHA384 和 SHA512
此示例需要通用加密
必须有项目的桥接头:
#import <CommonCrypto/CommonCrypto.h>
将 Security.framework 添加到项目中。
这些函数采用散列名称、要散列的消息、密钥和 return 摘要:
hashName: name of a hash function as String
message: message as Data
key: key as Data
returns: digest as Data
func hmac(hashName:String, message:Data, key:Data) -> Data? {
let algos = ["SHA1": (kCCHmacAlgSHA1, CC_SHA1_DIGEST_LENGTH),
"MD5": (kCCHmacAlgMD5, CC_MD5_DIGEST_LENGTH),
"SHA224": (kCCHmacAlgSHA224, CC_SHA224_DIGEST_LENGTH),
"SHA256": (kCCHmacAlgSHA256, CC_SHA256_DIGEST_LENGTH),
"SHA384": (kCCHmacAlgSHA384, CC_SHA384_DIGEST_LENGTH),
"SHA512": (kCCHmacAlgSHA512, CC_SHA512_DIGEST_LENGTH)]
guard let (hashAlgorithm, length) = algos[hashName] else { return nil }
var macData = Data(count: Int(length))
macData.withUnsafeMutableBytes {macBytes in
message.withUnsafeBytes {messageBytes in
key.withUnsafeBytes {keyBytes in
CCHmac(CCHmacAlgorithm(hashAlgorithm),
keyBytes, key.count,
messageBytes, message.count,
macBytes)
}
}
}
return macData
}
hashName: name of a hash function as String
message: message as String
key: key as String
returns: digest as Data
func hmac(hashName:String, message:String, key:String) -> Data? {
let messageData = message.data(using:.utf8)!
let keyData = key.data(using:.utf8)!
return hmac(hashName:hashName, message:messageData, key:keyData)
}
hashName: name of a hash function as String
message: message as String
key: key as Data
returns: digest as Data
func hmac(hashName:String, message:String, key:Data) -> Data? {
let messageData = message.data(using:.utf8)!
return hmac(hashName:hashName, message:messageData, key:key)
}
// 例子
let clearString = "clearData0123456"
let keyString = "keyData8901234562"
let clearData = clearString.data(using:.utf8)!
let keyData = keyString.data(using:.utf8)!
print("clearString: \(clearString)")
print("keyString: \(keyString)")
print("clearData: \(clearData as NSData)")
print("keyData: \(keyData as NSData)")
let hmacData1 = hmac(hashName:"SHA1", message:clearData, key:keyData)
print("hmacData1: \(hmacData1! as NSData)")
let hmacData2 = hmac(hashName:"SHA1", message:clearString, key:keyString)
print("hmacData2: \(hmacData2! as NSData)")
let hmacData3 = hmac(hashName:"SHA1", message:clearString, key:keyData)
print("hmacData3: \(hmacData3! as NSData)")
输出:
clearString: clearData0123456
keyString: keyData8901234562
clearData: <636c6561 72446174 61303132 33343536>
keyData: <6b657944 61746138 39303132 33343536 32>
hmacData1: <bb358f41 79b68c08 8e93191a da7dabbc 138f2ae6>
hmacData2: <bb358f41 79b68c08 8e93191a da7dabbc 138f2ae6>
hmacData3: <bb358f41 79b68c08 8e93191a da7dabbc 138f2ae6>
MD2、MD4、MD5、SHA1、SHA224、SHA256、SHA384、SHA512 (Swift 3+)
These functions will hash either String or Data input with one of eight cryptographic hash algorithms.
name 参数将哈希函数名称指定为字符串
支持的函数有 MD2、MD4、MD5、SHA1、SHA224、SHA256、SHA384 和 SHA512
一种
此示例需要 Common Crypto
必须有项目的桥接头:
#import <CommonCrypto/CommonCrypto.h>
将 Security.framework 添加到项目中。
这个函数接受一个散列名称和要散列的字符串,return一个数据:
name: A name of a hash function as a String
string: The String to be hashed
returns: the hashed result as Data
func hash(name:String, string:String) -> Data? {
let data = string.data(using:.utf8)!
return hash(name:name, data:data)
}
示例:
let clearString = "clearData0123456"
let clearData = clearString.data(using:.utf8)!
print("clearString: \(clearString)")
print("clearData: \(clearData as NSData)")
let hashSHA256 = hash(name:"SHA256", string:clearString)
print("hashSHA256: \(hashSHA256! as NSData)")
let hashMD5 = hash(name:"MD5", data:clearData)
print("hashMD5: \(hashMD5! as NSData)")
输出:
clearString: clearData0123456
clearData: <636c6561 72446174 61303132 33343536>
hashSHA256: <aabc766b 6b357564 e41f4f91 2d494bcc bfa16924 b574abbd ba9e3e9d a0c8920a>
hashMD5: <4df665f7 b94aea69 695b0e7b baf9e9d6>
更新为 swift 4
func sha512Hex( string: String) -> String {
var digest = [UInt8](repeating: 0, count: Int(CC_SHA512_DIGEST_LENGTH))
if let data = string.data(using: String.Encoding.utf8) {
let value = data as NSData
CC_SHA512(value.bytes, CC_LONG(data.count), &digest)
}
var digestHex = ""
for index in 0..<Int(CC_SHA512_DIGEST_LENGTH) {
digestHex += String(format: "%02x", digest[index])
}
return digestHex
}
func sha512(string: String) -> [UInt8] {
var digest = [UInt8](repeating: 0, count: Int(CC_SHA512_DIGEST_LENGTH))
let data = string.data(using: String.Encoding.utf8 , allowLossyConversion: true)
let value = data! as NSData
CC_SHA512(value.bytes, CC_LONG(value.length), &digest)
return digest
}
func sha512Base64(string: String) -> String {
let digest = NSMutableData(length: Int(CC_SHA512_DIGEST_LENGTH))!
if let data = string.data(using: String.Encoding.utf8) {
let value = data as NSData
let uint8Pointer = UnsafeMutablePointer<UInt8>.allocate(capacity: digest.length)
CC_SHA512(value.bytes, CC_LONG(data.count), uint8Pointer)
}
return digest.base64EncodedString(options: NSData.Base64EncodingOptions([]))
}
测试
let vad = sha512Hex(string: "8yOrBmkd")
print(vad)
let digestRaw = sha512(string:"8yOrBmkd")
print("decimal array:\n\(digestRaw)")
print("hexadecimal:\n\(NSData(bytes:digestRaw, length:digestRaw.count).description)")
let digestBase64 = sha512Base64(string:"8yOrBmkd")
print("Base64:\n\(digestBase64)")
在 iOS13 中添加了 CryptoKit
,我们现在有原生 Swift API:
import Foundation
import CryptoKit
// CryptoKit.Digest utils
extension Digest {
var bytes: [UInt8] { Array(makeIterator()) }
var data: Data { Data(bytes) }
var hexStr: String {
bytes.map { String(format: "%02X", [=10=]) }.joined()
}
}
func example() {
guard let data = "hello world".data(using: .utf8) else { return }
let digest = SHA512.hash(data: data)
print(digest.data) // 64 bytes
print(digest.hexStr) // 309ECC489C12D6EB4CC40F50C902F2B4D0ED77EE511A7C7A9BCD3CA86D4CD86F989DD35BC5FF499670DA34255B45B0CFD830E81F605DCF7DC5542E93AE9CD76F
}
任何人都知道如何在 swift 中重现 PHP 散列方法 hash('SHA512', $value, true) ?我尝试将 CommonCrypto C 库与此代码一起使用:
extension String {
func digest(length:Int32, gen:(data: UnsafePointer<Void>, len: CC_LONG, md: UnsafeMutablePointer<UInt8>) -> UnsafeMutablePointer<UInt8>) -> String {
var cStr = [UInt8](self.utf8)
var result = [UInt8](count:Int(length), repeatedValue:0)
gen(data: &cStr, len: CC_LONG(cStr.count), md: &result)
let output = NSMutableString(capacity:Int(length))
for r in result {
output.appendFormat("%02x", r)
}
return String(output)
}
}
并像这样使用它:
var digest = salted.digest(CC_SHA512_DIGEST_LENGTH, gen: {(data, len, md) in CC_SHA512(data,len,md)})
但是我没有得到正确的输出
编辑:
我有一些 PHP 代码:
echo base64_encode(hash('sha512', '8yOrBmkd', true)); // output: rlltLWeWaQCrfNTYMa0CcIs0mfLoHGAynrd+d8H65+rGAzHS/BSWsumwSmcxF9aAG9TIzXx+HOjArPyLL3herg==
我希望我的 swift 代码输出相同的内容。 Base64编码没问题:
let utf8str = input.dataUsingEncoding(NSUTF8StringEncoding)!.base64EncodedStringWithOptions(NSDataBase64EncodingOptions(rawValue: 0))
let base64Encoded = utf8str!.base64EncodedStringWithOptions(NSDataBase64EncodingOptions(rawValue: 0))
print("Encoded: \(base64Encoded)")
但散列部分 return 输出与此 PHP 代码相同的值:
echo base64_encode(hash('sha512', '8yOrBmkd', false)); // output: YWU1OTZkMmQ2Nzk2NjkwMGFiN2NkNGQ4MzFhZDAyNzA4YjM0OTlmMmU4MWM2MDMyOWViNzdlNzdjMWZhZTdlYWM2MDMzMWQyZmMxNDk2YjJlOWIwNGE2NzMxMTdkNjgwMWJkNGM4Y2Q3YzdlMWNlOGMwYWNmYzhiMmY3ODVlYWU=
Swift 底部有 3 个实现。
代码不需要那么复杂或扩展:
func sha512Hex(string string: String) -> String {
var digest = [UInt8](count: Int(CC_SHA512_DIGEST_LENGTH), repeatedValue: 0)
if let data = string.dataUsingEncoding(NSUTF8StringEncoding) {
CC_SHA512(data.bytes, CC_LONG(data.length), &digest)
}
var digestHex = ""
for index in 0..<Int(CC_SHA512_DIGEST_LENGTH) {
digestHex += String(format: "%02x", digest[index])
}
return digestHex
}
//测试:
let hexDigest = sha512Hex(string:"8yOrBmkd")
print("hexDigest:\n\(hexDigest)")
输出:
hexDigest: ae596d2d67966900ab7cd4d831ad02708b3499f2e81c60329eb77e77c1fae7eac60331d2fc1496b2e9b04a673117d6801bd4c8cd7c7e1ce8c0acfc8b2f785eae
只是返回字节数组:
func sha512(string string: String) -> [UInt8] {
var digest = [UInt8](count: Int(CC_SHA512_DIGEST_LENGTH), repeatedValue: 0)
let data = string.dataUsingEncoding(NSUTF8StringEncoding)!
CC_SHA512(data.bytes, CC_LONG(data.length), &digest)
return digest
}
//测试:
let digestRaw = sha512(string:"8yOrBmkd")
print("decimal array:\n\(digestRaw)")
print("hexadecimal:\n\(NSData(bytes:digestRaw, length:digestRaw.count).description)")
输出:
decimal array: [174, 89, 109, 45, 103, 150, 105, 0, 171, 124, 212, 216, 49, 173, 2, 112, 139, 52, 153, 242, 232, 28, 96, 50, 158, 183, 126, 119, 193, 250, 231, 234, 198, 3, 49, 210, 252, 20, 150, 178, 233, 176, 74, 103, 49, 23, 214, 128, 27, 212, 200, 205, 124, 126, 28, 232, 192, 172, 252, 139, 47, 120, 94, 174]
hexadecimal:
ae596d2d67966900ab7cd4d831ad02708b3499f2e81c60329eb77e77c1fae7eac60331d2fc1496b2e9b04a673117d6801bd4c8cd7c7e1ce8c0acfc8b2f785eae
Base64 输出:
func sha512Base64(string string: String) -> String {
let digest = NSMutableData(length: Int(CC_SHA512_DIGEST_LENGTH))!
if let data = string.dataUsingEncoding(NSUTF8StringEncoding) {
CC_SHA512(data.bytes, CC_LONG(data.length), UnsafeMutablePointer<UInt8>(digest.mutableBytes))
}
return digest.base64EncodedStringWithOptions(NSDataBase64EncodingOptions([]))
}
//测试:
let digestBase64 = sha512Base64(string:"8yOrBmkd")
print("Base64:\n\(digestBase64)")
输出:
Base64:
rlltLWeWaQCrfNTYMa0CcIs0mfLoHGAynrd+d8H65+rGAzHS/BSWsumwSmcxF9aAG9TIzXx+HOjArPyLL3herg==
Swift 3
func hashSHA512(data:Data) -> String? {
var hashData = Data(count: Int(CC_SHA512_DIGEST_LENGTH))
_ = hashData.withUnsafeMutableBytes {digestBytes in
data.withUnsafeBytes {messageBytes in
CC_SHA512(messageBytes, CC_LONG(data.count), digestBytes)
}
}
// For hexadecimal output:
return hashData.map { String(format: "%02hhx", [=16=]) }.joined()
// For Base64 output use this instead of the above:
// return data.base64EncodedString()
}
已弃用文档部分的示例:
带 MD5、SHA1、SHA224、SHA256、SHA384、SHA512 的 HMAC (Swift 3+)
These functions will hash either String or Data input with one of eight cryptographic hash algorithms.
name 参数指定哈希函数名称为字符串 支持的函数有 MD5、SHA1、SHA224、SHA256、SHA384 和 SHA512
此示例需要通用加密
必须有项目的桥接头:
#import <CommonCrypto/CommonCrypto.h>
将 Security.framework 添加到项目中。
这些函数采用散列名称、要散列的消息、密钥和 return 摘要:
hashName: name of a hash function as String message: message as Data key: key as Data returns: digest as Data
func hmac(hashName:String, message:Data, key:Data) -> Data? {
let algos = ["SHA1": (kCCHmacAlgSHA1, CC_SHA1_DIGEST_LENGTH),
"MD5": (kCCHmacAlgMD5, CC_MD5_DIGEST_LENGTH),
"SHA224": (kCCHmacAlgSHA224, CC_SHA224_DIGEST_LENGTH),
"SHA256": (kCCHmacAlgSHA256, CC_SHA256_DIGEST_LENGTH),
"SHA384": (kCCHmacAlgSHA384, CC_SHA384_DIGEST_LENGTH),
"SHA512": (kCCHmacAlgSHA512, CC_SHA512_DIGEST_LENGTH)]
guard let (hashAlgorithm, length) = algos[hashName] else { return nil }
var macData = Data(count: Int(length))
macData.withUnsafeMutableBytes {macBytes in
message.withUnsafeBytes {messageBytes in
key.withUnsafeBytes {keyBytes in
CCHmac(CCHmacAlgorithm(hashAlgorithm),
keyBytes, key.count,
messageBytes, message.count,
macBytes)
}
}
}
return macData
}
hashName: name of a hash function as String message: message as String key: key as String returns: digest as Data
func hmac(hashName:String, message:String, key:String) -> Data? {
let messageData = message.data(using:.utf8)!
let keyData = key.data(using:.utf8)!
return hmac(hashName:hashName, message:messageData, key:keyData)
}
hashName: name of a hash function as String message: message as String key: key as Data returns: digest as Data
func hmac(hashName:String, message:String, key:Data) -> Data? {
let messageData = message.data(using:.utf8)!
return hmac(hashName:hashName, message:messageData, key:key)
}
// 例子
let clearString = "clearData0123456"
let keyString = "keyData8901234562"
let clearData = clearString.data(using:.utf8)!
let keyData = keyString.data(using:.utf8)!
print("clearString: \(clearString)")
print("keyString: \(keyString)")
print("clearData: \(clearData as NSData)")
print("keyData: \(keyData as NSData)")
let hmacData1 = hmac(hashName:"SHA1", message:clearData, key:keyData)
print("hmacData1: \(hmacData1! as NSData)")
let hmacData2 = hmac(hashName:"SHA1", message:clearString, key:keyString)
print("hmacData2: \(hmacData2! as NSData)")
let hmacData3 = hmac(hashName:"SHA1", message:clearString, key:keyData)
print("hmacData3: \(hmacData3! as NSData)")
输出:
clearString: clearData0123456
keyString: keyData8901234562
clearData: <636c6561 72446174 61303132 33343536>
keyData: <6b657944 61746138 39303132 33343536 32>
hmacData1: <bb358f41 79b68c08 8e93191a da7dabbc 138f2ae6>
hmacData2: <bb358f41 79b68c08 8e93191a da7dabbc 138f2ae6>
hmacData3: <bb358f41 79b68c08 8e93191a da7dabbc 138f2ae6>
MD2、MD4、MD5、SHA1、SHA224、SHA256、SHA384、SHA512 (Swift 3+)
These functions will hash either String or Data input with one of eight cryptographic hash algorithms.
name 参数将哈希函数名称指定为字符串
支持的函数有 MD2、MD4、MD5、SHA1、SHA224、SHA256、SHA384 和 SHA512
一种
此示例需要 Common Crypto
必须有项目的桥接头:
#import <CommonCrypto/CommonCrypto.h>
将 Security.framework 添加到项目中。
这个函数接受一个散列名称和要散列的字符串,return一个数据:
name: A name of a hash function as a String string: The String to be hashed returns: the hashed result as Data
func hash(name:String, string:String) -> Data? {
let data = string.data(using:.utf8)!
return hash(name:name, data:data)
}
示例:
let clearString = "clearData0123456"
let clearData = clearString.data(using:.utf8)!
print("clearString: \(clearString)")
print("clearData: \(clearData as NSData)")
let hashSHA256 = hash(name:"SHA256", string:clearString)
print("hashSHA256: \(hashSHA256! as NSData)")
let hashMD5 = hash(name:"MD5", data:clearData)
print("hashMD5: \(hashMD5! as NSData)")
输出:
clearString: clearData0123456
clearData: <636c6561 72446174 61303132 33343536>
hashSHA256: <aabc766b 6b357564 e41f4f91 2d494bcc bfa16924 b574abbd ba9e3e9d a0c8920a>
hashMD5: <4df665f7 b94aea69 695b0e7b baf9e9d6>
更新为 swift 4
func sha512Hex( string: String) -> String {
var digest = [UInt8](repeating: 0, count: Int(CC_SHA512_DIGEST_LENGTH))
if let data = string.data(using: String.Encoding.utf8) {
let value = data as NSData
CC_SHA512(value.bytes, CC_LONG(data.count), &digest)
}
var digestHex = ""
for index in 0..<Int(CC_SHA512_DIGEST_LENGTH) {
digestHex += String(format: "%02x", digest[index])
}
return digestHex
}
func sha512(string: String) -> [UInt8] {
var digest = [UInt8](repeating: 0, count: Int(CC_SHA512_DIGEST_LENGTH))
let data = string.data(using: String.Encoding.utf8 , allowLossyConversion: true)
let value = data! as NSData
CC_SHA512(value.bytes, CC_LONG(value.length), &digest)
return digest
}
func sha512Base64(string: String) -> String {
let digest = NSMutableData(length: Int(CC_SHA512_DIGEST_LENGTH))!
if let data = string.data(using: String.Encoding.utf8) {
let value = data as NSData
let uint8Pointer = UnsafeMutablePointer<UInt8>.allocate(capacity: digest.length)
CC_SHA512(value.bytes, CC_LONG(data.count), uint8Pointer)
}
return digest.base64EncodedString(options: NSData.Base64EncodingOptions([]))
}
测试
let vad = sha512Hex(string: "8yOrBmkd")
print(vad)
let digestRaw = sha512(string:"8yOrBmkd")
print("decimal array:\n\(digestRaw)")
print("hexadecimal:\n\(NSData(bytes:digestRaw, length:digestRaw.count).description)")
let digestBase64 = sha512Base64(string:"8yOrBmkd")
print("Base64:\n\(digestBase64)")
在 iOS13 中添加了 CryptoKit
,我们现在有原生 Swift API:
import Foundation
import CryptoKit
// CryptoKit.Digest utils
extension Digest {
var bytes: [UInt8] { Array(makeIterator()) }
var data: Data { Data(bytes) }
var hexStr: String {
bytes.map { String(format: "%02X", [=10=]) }.joined()
}
}
func example() {
guard let data = "hello world".data(using: .utf8) else { return }
let digest = SHA512.hash(data: data)
print(digest.data) // 64 bytes
print(digest.hexStr) // 309ECC489C12D6EB4CC40F50C902F2B4D0ED77EE511A7C7A9BCD3CA86D4CD86F989DD35BC5FF499670DA34255B45B0CFD830E81F605DCF7DC5542E93AE9CD76F
}