Created
February 22, 2020 09:41
-
-
Save foxicode/b77c74b0f2a60a0f351c5187cb8c3dd3 to your computer and use it in GitHub Desktop.
Swift String extension to calculate MD5
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
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() | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
'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).