ios - Swift 中 UTF16LE(无 BOM 和 0 字节结尾)的 MD5

标签 ios swift md5

我遇到了与此线程中完全相同的问题:

MD5 of an UTF16LE (without BOM and 0-Byte End) in C#

但是,我正在尝试在基于 Swift 4 的 iOS 应用程序中实现这一点。我尝试了

中讨论的所有选项

How to convert string to MD5 hash using ios swift

还有 https://github.com/krzyzanowskim/CryptoSwift

但我无法生成正确的 MD5 哈希值。我生成了一个输入字符串的字节数组并删除了字符串末尾的 0 字节,并使用了上面线程中提到的函数。如果有人可以请指出我正确的方向。 基本上 utf8 字符串“1234567z-äbc”应该变成“9e224a41eeefa284df7bb0f26c2913e2”

这就是我到目前为止所尝试的:

        let str = "1234567z" + "-" + "äbc"
        let data = str.data(using: .utf16LittleEndian)!

        let bytesArray = data.map { $0 }
        let bytesArrayNoZero = bytesArray.filter{ $0 != 0}

        let str2 = String(bytes: bytesArrayNoZero, encoding: String.Encoding.utf16LittleEndian)

        print (fritz_01.MD5(str2!))



 func MD5(string: String) -> Data {
    let messageData = string.data(using:.utf8)!
    var digestData = Data(count: Int(CC_MD5_DIGEST_LENGTH))

    _ = digestData.withUnsafeMutableBytes {digestBytes in
        messageData.withUnsafeBytes {messageBytes in
            CC_MD5(messageBytes, CC_LONG(messageData.count), digestBytes)
        }
    }

    return digestData
}

最佳答案

这个

let str = "1234567z" + "-" + "äbc"
let data = str.data(using: .utf16LittleEndian)!

已经给出了你想要计算的 UTF16LE 数据 MD5 hash,无需过滤0字节等操作。

相反,修改 How to convert string to MD5 hash using ios swift 中的函数以获取 Data 参数 而不是 String:

func MD5(messageData: Data) -> Data {
    var digestData = Data(count: Int(CC_MD5_DIGEST_LENGTH))
    _ = digestData.withUnsafeMutableBytes {digestBytes in
        messageData.withUnsafeBytes {messageBytes in
            CC_MD5(messageBytes, CC_LONG(messageData.count), digestBytes)
        }
    }
    return digestData
}

以便您可以使用已转换的数据调用它:

let str = "1234567z" + "-" + "äbc"
let data = str.data(using: .utf16LittleEndian)!

let md5Data = MD5(messageData: data)
let md5Hex =  md5Data.map { String(format: "%02hhx", $0) }.joined()

print("md5Hex: \(md5Hex)")
// 9e224a41eeefa284df7bb0f26c2913e2

关于ios - Swift 中 UTF16LE(无 BOM 和 0 字节结尾)的 MD5,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49214061/

相关文章:

ios - 应用被拒绝,但应用内购买正在审核中

iOS React Native 应用程序不会从 CodePush 服务器更新

swift - 向网络服务器发送参数

ios - 如何使用Codable解码字典的JSON字典(具有不同的键)?

swift - 无法识别 if 语句条件中使用的变量

MySQL 哈希值作为列名

ios - Vfr Reader从右到左阅读

ios - 使用 SLRequest(无对话框)在 iOS 6 中将视频上传到 Facebook 的示例

sql - 如何处理 MySQL 函数 md5 的输入?

database - 使用 URI 的 md5 散列作为数据库主键的优缺点