1

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 2

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
3
  • 1
    Side note: Data(string.utf8) would avoid the unwrap (or coesciling)
    – Larme
    Commented Aug 8, 2022 at 12:26
  • Even better! Thanks for the note! Commented Aug 8, 2022 at 12:29
  • Thanks, I try to use your code, but I found my results are inconsistent with yours, Are you running the code under the iOS13.0 system? Under other systems it is normal.
    – Yosmative
    Commented Aug 9, 2022 at 3:21
0

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))
1
  • not working (iOS 17) Commented Sep 21, 2023 at 11:56

Not the answer you're looking for? Browse other questions tagged or ask your own question.