Skip to content

Instantly share code, notes, and snippets.

@bre7
Last active August 29, 2015 14:21
Show Gist options
  • Save bre7/ab226b79b80bcef7a1de to your computer and use it in GitHub Desktop.
Save bre7/ab226b79b80bcef7a1de to your computer and use it in GitHub Desktop.
Swift String extension to get crypto hashes
// Based on:
// https://github.com/mnbayan/StringHash
// https://github.com/hypercrypt/NSString-Hashes
enum HashType {
case MD5
case SHA256
case SHA512
}
extension String {
func getCryptoHash(type: HashType) -> String {
let str = self.cStringUsingEncoding(NSUTF8StringEncoding)
let strLen = CC_LONG(self.lengthOfBytesUsingEncoding(NSUTF8StringEncoding))
let digestLen: Int
let result: UnsafeMutablePointer<CUnsignedChar>
switch type {
case .MD5:
digestLen = Int(CC_MD5_DIGEST_LENGTH)
result = UnsafeMutablePointer<CUnsignedChar>.alloc(digestLen)
CC_MD5(str!, strLen, result)
case .SHA256:
digestLen = Int(CC_SHA256_DIGEST_LENGTH)
result = UnsafeMutablePointer<CUnsignedChar>.alloc(digestLen)
CC_SHA256(str!, strLen, result)
case .SHA512:
digestLen = Int(CC_SHA512_DIGEST_LENGTH)
result = UnsafeMutablePointer<CUnsignedChar>.alloc(digestLen)
CC_SHA512(str!, strLen, result)
}
var hash = NSMutableString()
for i in 0..<digestLen {
hash.appendFormat("%02x", result[i])
}
result.destroy()
return String(format: hash as String)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment