使用Swift4创建SHA256哈希值

4

我已经搜索了一些资料,但是只找到了使用Objective-C创建SHA256哈希的示例。是否有一种仅使用Swift4实现的方法呢?


4
可能是Swift中的SHA256重复问题 - Andy Ibanez
1个回答

7
您可以像这样使用:
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>

当我将该函数添加到我的代码中时,它会给我多个错误。 - Matthew N
请检查我的更新答案。你需要在桥接头文件中导入CommonCrypto - Vini App

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接