Skip to content

Instantly share code, notes, and snippets.

@finder39
Last active March 20, 2018 13:37
  • Star 29 You must be signed in to star a gist
  • Fork 6 You must be signed in to fork a gist
Star You must be signed in to star a gist
Save finder39/f6d71f03661f7147547d to your computer and use it in GitHub Desktop.
Swift MD5
extension String {
func md5() -> String! {
let str = self.cStringUsingEncoding(NSUTF8StringEncoding)
let strLen = CUnsignedInt(self.lengthOfBytesUsingEncoding(NSUTF8StringEncoding))
let digestLen = Int(CC_MD5_DIGEST_LENGTH)
let result = UnsafeMutablePointer<CUnsignedChar>.alloc(digestLen)
CC_MD5(str!, strLen, result)
var hash = NSMutableString()
for i in 0..<digestLen {
hash.appendFormat("%02x", result[i])
}
result.destroy()
return String(format: hash)
}
}
#import <CommonCrypto/CommonCrypto.h> // required for MD5
@ciryon
Copy link

ciryon commented Jul 7, 2015

return String(format: hash as String)
on last call

@theniceboy
Copy link

Cool

@EviloBivl
Copy link

Hi, first i want to thank you for that snippet
and then i want to mention, that instruments and its leak check discovered a memory leak.
As described here http://stackoverflow.com/a/27671003 i added
result.dealloc(digestLen)
which resolved the problem in instruments for me
Just wanted to share my findings :)

best regards

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment