skip to Main Content

When I use Insecure.MD5.hash(data: data) to get a md5 result of a data, I found in iOS 13.0 the result is incorrected, this is my code:

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)")
}

The result is fc5e038d38a57032085441e7fe7010b000000000, but the correctResult should be fc5e038d38a57032085441e7fe7010b0.

So, is this Apple’s bug in iOS 13.0?

2

Answers


  1. Very likely not since I cannot reproduce your results. For me, this works as it should (I applied some stylistic improvements):

    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
    
    Login or Signup to reply.
  2. I have encounterd the same problem as you on iOS 13.0, i also think that’s Apple’s bug.

    My solution

    The number of bits generated by the MD5 hash function is fixed, it produced a 128-bit hash value.
    Due to we use hexadecimal number to represented it, and a hexadecimal number occupies 4 bits, so the final MD5 value is represented by 32 hexadecimal numbers.

    so we can use prefix(_ maxLength: Int) -> Substring function to intercept string.

    replace:

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

    to

    let result = String(digest.map { String(format: "%02hhx", $0) }.joined().prefix(32))
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search