Last active
August 29, 2015 14:21
-
-
Save bre7/ab226b79b80bcef7a1de to your computer and use it in GitHub Desktop.
Swift String extension to get crypto hashes
This file contains 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
// 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