Skip to content

Instantly share code, notes, and snippets.

@foxicode
Created February 22, 2020 09:41
Show Gist options
  • Save foxicode/b77c74b0f2a60a0f351c5187cb8c3dd3 to your computer and use it in GitHub Desktop.
Save foxicode/b77c74b0f2a60a0f351c5187cb8c3dd3 to your computer and use it in GitHub Desktop.
Swift String extension to calculate MD5
import Foundation
extension String {
var md5: String? {
let length = Int(CC_MD5_DIGEST_LENGTH)
guard let data = self.data(using: String.Encoding.utf8) else { return nil }
let hash = data.withUnsafeBytes { (bytes: UnsafeRawBufferPointer) -> [UInt8] in
var hash: [UInt8] = [UInt8](repeating: 0, count: Int(CC_MD5_DIGEST_LENGTH))
CC_MD5(bytes.baseAddress, CC_LONG(data.count), &hash)
return hash
}
return (0..<length).map { String(format: "%02x", hash[$0]) }.joined()
}
}
@Andy0570
Copy link

'CC_MD5' was deprecated in iOS 13.0: This function is cryptographically broken and should not be used in security contexts. Clients should migrate to SHA256 (or stronger).

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