iOS13.0中的Insecure.MD5得到错误结果

rjee0c15  于 2022-12-20  发布在  iOS
关注(0)|答案(2)|浏览(152)

当我使用Insecure.MD5.hash(数据:data)来获取一个数据的md5结果,我发现在iOS 13.0中结果是不正确的,这是我的代码:

if let data = "helloworld".data(using: .utf8) {
    let digest = Insecure.MD5.hash(data: data)
    for i in digest {
        print(i)
    }
    let result = digest.map { String(format: "%02hhx", $0) }.joined()
    print("StringMD5Result--\(result)")
}

结果为fc5e038d38a57032085441e7fe7010b00000000,但正确的结果应为fc5e038d38a57032085441e7fe7010b0。
那么,这是苹果在iOS 13.0中的bug吗?

wztqucjr

wztqucjr1#

很可能不会,因为我无法复制你的结果。对我来说,这是应该的(我应用了一些风格上的改进):

import Foundation
import CryptoKit

func md5(string: String) -> String {
    let digest = Insecure.MD5.hash(data: Data(string.utf8))
    return digest.map {
        String(format: "%02hhx", $0)
    }.joined()
}

print(md5(string: "helloworld")) // returns fc5e038d38a57032085441e7fe7010b0
kdfy810k

kdfy810k2#

我在iOS13.0上遇到了和你一样的问题,我也认为这是苹果的bug。

我的解决方案

MD5散列函数产生的位数是固定的,它产生一个128位的散列值,由于我们用十六进制数来表示,而一个十六进制数占用4位,所以最终的MD5值用32个十六进制数来表示。
因此我们可以使用prefix(_ maxLength: Int) -> Substring函数来截取字符串。

替换:

let result = digest.map { String(format: "%02hhx", $0) }.joined()

let result = String(digest.map { String(format: "%02hhx", $0) }.joined().prefix(32))

相关问题