Swift 3 making sha1, sha256 and md5 functions
You'd better use Swift Data
in Swift 3.
Data
And when working with Data
, you need to use withUnsafeBytes(_:)
or withUnsafeMutableBytes(_:)
, where you were using bytes
or mutableBytes
respectively.
withUnsafeBytes(_:)
withUnsafeMutableBytes(_:)
extension Data {
func hexString() -> String {
let string = self.map{Int($0).hexString()}.joined()
return string
}
func MD5() -> Data {
var result = Data(count: Int(CC_MD5_DIGEST_LENGTH))
_ = result.withUnsafeMutableBytes {resultPtr in
self.withUnsafeBytes {(bytes: UnsafePointer<UInt8>) in
CC_MD5(bytes, CC_LONG(count), resultPtr)
}
}
return result
}
/*
... nearly the same for `SHA1` and `SHA256`.
*/
}
extension String {
func hexString() -> String {
return self.data(using: .utf8)!.hexString()
}
func MD5() -> String {
return self.data(using: .utf8)!.MD5().hexString()
}
/*
... nearly the same for `SHA1` and `SHA256`.
*/
}
I prefer making computed properties than no-argument methods (for relatively light-tasks). You need to fix all parts using them, but you can write something like this:
extension Int {
var hexString: String {
return ...
}
}
extension Data {
var hexString: String {
let string = self.map{Int($0).hexString}.joined()
return string
}
var MD5: Data {
var result = Data(count: Int(CC_MD5_DIGEST_LENGTH))
_ = result.withUnsafeMutableBytes {resultPtr in
self.withUnsafeBytes {(bytes: UnsafePointer<UInt8>) in
CC_MD5(bytes, CC_LONG(count), resultPtr)
}
}
return result
}
/*
... nearly the same for `SHA1` and `SHA256`.
*/
}
extension String {
var hexString: String {
return self.data(using: .utf8)!.hexString
}
var MD5: String {
return self.data(using: .utf8)!.MD5.hexString
}
/*
... nearly the same for `SHA1` and `SHA256`.
*/
}
There may be a quicker fix for your code using NSData
, but I recommend you to move to Data
in Swift 3.