Skip to content

Instantly share code, notes, and snippets.

@jstn
Last active January 24, 2022 15:33
Show Gist options
  • Save jstn/787da74ab4be9d4cf3cb to your computer and use it in GitHub Desktop.
Save jstn/787da74ab4be9d4cf3cb to your computer and use it in GitHub Desktop.
MD5 with CommonCrypto in Swift 3.0
// requires a bridging header with this:
// #import <CommonCrypto/CommonCrypto.h>
func MD5(_ string: String) -> String? {
let length = Int(CC_MD5_DIGEST_LENGTH)
var digest = [UInt8](repeating: 0, count: length)
if let d = string.data(using: String.Encoding.utf8) {
d.withUnsafeBytes { (body: UnsafePointer<UInt8>) in
CC_MD5(body, CC_LONG(d.count), &digest)
}
}
return (0..<length).reduce("") {
$0 + String(format: "%02x", digest[$1])
}
}
Copy link

ghost commented Sep 12, 2017

Good!

@Ricardo1980
Copy link

There is a warning: Result of call to 'withUnsafeBytes' is unused

@eneko
Copy link

eneko commented Apr 4, 2019

Maybe a simpler version, without the warning:

func md5(string: String) -> String {
    let length = Int(CC_MD5_DIGEST_LENGTH)
    var digest = [UInt8](repeating: 0, count: length)
    var data = string.utf8
    CC_MD5(&data, CC_LONG(data.count), &digest)
    return digest.map { String(format: "%02x", $0) }.joined()
}

Use "%02X" for uppercase.

@AdiAyyakad
Copy link

Update for Swift 5?

@blastar
Copy link

blastar commented Jun 12, 2019

The last one from April 5th, works with Swift 5 also

@AdiAyyakad
Copy link

Screen Shot 2019-06-12 at 11 10 18 AM

I'm seeing this

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment