【问题标题】:Creating SHA256 hash with swift4使用 swift4 创建 SHA256 哈希
【发布时间】:2017-10-16 23:34:04
【问题描述】:

我环顾四周,但只能找到使用 Objective-C 创建 SHA256 哈希的示例。有没有办法只用 Swift4 来做到这一点?

【问题讨论】:

标签: sha256 xcode9 swift4


【解决方案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>

【讨论】:

  • 当我将函数添加到我的代码中时,它给了我多个错误
  • 请查看我更新的答案。您的桥接头中有 import CommonCrypto
猜你喜欢
  • 2012-12-16
  • 1970-01-01
  • 2015-12-23
  • 2019-11-10
  • 2020-06-05
  • 2015-11-22
  • 1970-01-01
  • 2014-01-14
  • 1970-01-01
相关资源
最近更新 更多