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! I tried to convert it but run into continuous errors.
Any idea how can I solve this?
extension NSData {
func hexString() -> String {
var string = String()
for i in UnsafeBufferPointer<UInt8>(start: UnsafeMutablePointer<UInt8>(bytes), count: length) {
string += Int(i).hexString()
}
return string
}
func MD5() -> NSData {
let result = NSMutableData(length: Int(CC_MD5_DIGEST_LENGTH))!
CC_MD5(bytes, CC_LONG(length), UnsafeMutablePointer<UInt8>(result.mutableBytes))
return NSData(data: result)
}
func SHA1() -> NSData {
let result = NSMutableData(length: Int(CC_SHA1_DIGEST_LENGTH))!
CC_SHA1(bytes, CC_LONG(length), UnsafeMutablePointer<UInt8>(result.mutableBytes))
return NSData(data: result)
}
func SHA256() -> NSData {
let result = NSMutableData(length: Int(CC_SHA256_DIGEST_LENGTH))
CC_SHA256(bytes, CC_LONG(length), UnsafeMutablePointer(result!.mutableBytes))
return NSData(data: result!)
}
}
extension String {
func hexString() -> String {
return (self as NSString).dataUsingEncoding(NSUTF8StringEncoding)!.hexString()
}
func MD5() -> String {
return (self as NSString).dataUsingEncoding(NSUTF8StringEncoding)!.MD5().hexString()
}
func SHA1() -> String {
return (self as NSString).dataUsingEncoding(NSUTF8StringEncoding)!.SHA1().hexString()
}
func SHA256() -> String {
return (self as NSString).dataUsingEncoding(NSUTF8StringEncoding)!.SHA256().hexString()
}
}
You'd better use Swift
Data
in Swift 3.Data
And when working with
Data
, you need to usewithUnsafeBytes(_:)
orwithUnsafeMutableBytes(_:)
, where you were usingbytes
ormutableBytes
respectively.withUnsafeBytes(_:)
withUnsafeMutableBytes(_:)
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:
There may be a quicker fix for your code using
NSData
, but I recommend you to move toData
in Swift 3.For completion, the shortest and most flexible solution in Swift 4 is:
I find most of the answer ok, but if we should have a true universal solution I think we need to step it up a level.
CC_LONG
is just anUInt32
and will not support really large data structures.This is my solution in Swift 3:
First we create a foundation that work with
Data
:For convenience we do an extension for Data:
And last an extension for String:
If needed, convert the result from
Data
to hex string or something else depending on your use case.This solution can be used for Sha512, MD5 etc. to get true universal solutions with Apple's CommonCrypto that are easy to extend to many different use cases.