Last active
January 24, 2022 15:33
MD5 with CommonCrypto in Swift 3.0
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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]) | |
} | |
} |
There is a warning: Result of call to 'withUnsafeBytes' is unused
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.
Update for Swift 5?
The last one from April 5th, works with Swift 5 also
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Good!