Skip to content

Instantly share code, notes, and snippets.

@madcato
Created May 20, 2021 10:01
Show Gist options
  • Save madcato/b6c1f49983604f7c97bb5d592b0bced1 to your computer and use it in GitHub Desktop.
Save madcato/b6c1f49983604f7c97bb5d592b0bced1 to your computer and use it in GitHub Desktop.
import Foundation
import var CommonCrypto.CC_MD5_DIGEST_LENGTH
import func CommonCrypto.CC_MD5
import typealias CommonCrypto.CC_LONG
extension String {
func md5() -> String {
let length = Int(CC_MD5_DIGEST_LENGTH)
let messageData = data(using: .utf8)!
var digestData = Data(count: length)
_ = digestData.withUnsafeMutableBytes { digestBytes -> UInt8 in
messageData.withUnsafeBytes { messageBytes -> UInt8 in
if let messageBytesBaseAddress = messageBytes.baseAddress,
let digestBytesBlindMemory =
digestBytes.bindMemory(to: UInt8.self).baseAddress {
let messageLength = CC_LONG(messageData.count)
CC_MD5(messageBytesBaseAddress,
messageLength,
digestBytesBlindMemory)
}
return 0
}
}
let md5Hex = digestData.map { String(format: "%02hhx", $0) }.joined()
return md5Hex
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment