ios - 在 Swift 5 中获取字符串 md5

标签 ios swift md5 swift5

在 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/

相关文章:

ios - React Native - Apple Mach-O 链接器错误

ios - SIGTRAP(TRAP_BRKPT) CollectionView cellForItemAt IndexPath 中崩溃

ios - swift didSelectRowAtIndexPath 可以多次调用

java - 如何使用 Java 解码/解密 MD5 加密

md5 - 是否有一种优雅的方法可以使用从服务器获取的 md5 文件在 ansible 中使用 md5 检查文件完整性?

ios - 修复 UIView 元素以避免更改 "scrollViewDidScroll"函数中的尺寸

ios - 在插入 CoreData 之前检查文本字段是否为空

java - 从给定的数字字符串生成 16 位唯一的十六进制值

iphone - 核心数据迁移 : How to delete the Core Data stack?

ios - 使用 swift NSObjects 和 JSON 的 EXC_BAD_INSTRUCTION