In Swift 2, I used the following code to extend string variables and to be able to make sha1, sha256, and md5.
After moving to swift 3, the code is not working any more!
For completion, the shortest and most flexible solution in Swift 4 is:
extension Data {
var hexString: String {
return map { String(format: "%02hhx", $0) }.joined()
}
var md5: Data {
var digest = [Byte](repeating: 0, count: Int(CC_MD5_DIGEST_LENGTH))
self.withUnsafeBytes({
_ = CC_MD5($0, CC_LONG(self.count), &digest)
})
return Data(bytes: digest)
}
var sha1: Data {
var digest = [UInt8](repeating: 0, count: Int(CC_SHA1_DIGEST_LENGTH))
self.withUnsafeBytes({
_ = CC_SHA1($0, CC_LONG(self.count), &digest)
})
return Data(bytes: digest)
}
var sha256: Data {
var digest = [UInt8](repeating: 0, count: Int(CC_SHA256_DIGEST_LENGTH))
self.withUnsafeBytes({
_ = CC_SHA256($0, CC_LONG(self.count), &digest)
})
return Data(bytes: digest)
}
}
extension String {
var md5: Data {
return self.data(using: .utf8)!.md5
}
var sha1: Data {
return self.data(using: .utf8)!.sha1
}
var sha256: Data {
return self.data(using: .utf8)!.sha256
}
}