2017-10-16 112 views
1

我已经做了一些四处寻找,但我只能找到使用Objective-C创建SHA256哈希值的例子。有没有办法只用Swift4来做到这一点?使用swift4创建SHA256哈希值

+3

[SHA256在可能的复制swift](https://stackoverflow.com/questions/25388747/sha256-in-swift) –

回答

1

你可以使用这样的:

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> 
+0

当我添加功能到我的代码,它给了我多ple错误 –

+0

多重错误意味着它给予了什么? –

+0

这是Xcode的截图:https://imgur.com/a/7QPwg –