Last active
March 22, 2022 14:51
-
-
Save stansidel/2079eb7d25e97b4d0694f83999fc5c61 to your computer and use it in GitHub Desktop.
Getting MD5 and SHA256 of NSData and String in Swift
This file contains hidden or 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
extension NSData { | |
private func getHash( | |
algorithm: (UnsafePointer<Void>, CC_LONG, UnsafeMutablePointer<UInt8>) -> UnsafeMutablePointer<UInt8>, | |
digestLength: Int32 | |
) -> String { | |
let digestLen = Int(digestLength) | |
let fileLen = CUnsignedInt(self.length) | |
let buffer = UnsafeMutablePointer<CUnsignedChar>.alloc(digestLen) | |
algorithm(self.bytes, fileLen, buffer) | |
let hash = NSMutableString() | |
for i in 0..<digestLen { | |
hash.appendFormat("%02x", buffer[i]) | |
} | |
buffer.destroy() | |
return String(format: hash as String) | |
} | |
func MD5() -> String { | |
return getHash(CC_MD5, digestLength: CC_MD5_DIGEST_LENGTH) | |
} | |
func SHA256() -> String { | |
return getHash(CC_SHA256, digestLength: CC_SHA256_DIGEST_LENGTH) | |
} | |
} |
This file contains hidden or 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
extension String { | |
private func getHash( | |
algorithm: (UnsafePointer<Void>, CC_LONG, UnsafeMutablePointer<UInt8>) -> UnsafeMutablePointer<UInt8>, | |
digestLength: Int32 | |
) -> String { | |
let str = self.cStringUsingEncoding(NSUTF8StringEncoding) | |
let strLen = CUnsignedInt(self.lengthOfBytesUsingEncoding(NSUTF8StringEncoding)) | |
let digestLen = Int(digestLength) | |
let result = UnsafeMutablePointer<CUnsignedChar>.alloc(digestLen) | |
algorithm(str!, strLen, result) | |
let hash = NSMutableString() | |
for i in 0..<digestLen { | |
hash.appendFormat("%02x", result[i]) | |
} | |
result.destroy() | |
return String(format: hash as String) | |
} | |
func MD5() -> String { | |
return getHash(CC_MD5, digestLength: CC_MD5_DIGEST_LENGTH) | |
} | |
func SHA256() -> String { | |
return getHash(CC_SHA256, digestLength: CC_SHA256_DIGEST_LENGTH) | |
} | |
} |
This file contains hidden or 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 <CommonCrypto/CommonCrypto.h> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
This has all been obsoleted by CryptoKit, and Apple has deprecated MD5 since it is insecure.