-
-
Save joelchen/9a93479d8ad0c68e4f6a to your computer and use it in GitHub Desktop.
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
// Make sure you add #import <CommonCrypto/CommonCrypto.h> to the Xcode bridging header | |
enum HMACAlgorithm { | |
case MD5, SHA1, SHA224, SHA256, SHA384, SHA512 | |
func toCCEnum() -> CCHmacAlgorithm { | |
var result: Int = 0 | |
switch self { | |
case .MD5: | |
result = kCCHmacAlgMD5 | |
case .SHA1: | |
result = kCCHmacAlgSHA1 | |
case .SHA224: | |
result = kCCHmacAlgSHA224 | |
case .SHA256: | |
result = kCCHmacAlgSHA256 | |
case .SHA384: | |
result = kCCHmacAlgSHA384 | |
case .SHA512: | |
result = kCCHmacAlgSHA512 | |
} | |
return CCHmacAlgorithm(result) | |
} | |
func digestLength() -> Int { | |
var result: CInt = 0 | |
switch self { | |
case .MD5: | |
result = CC_MD5_DIGEST_LENGTH | |
case .SHA1: | |
result = CC_SHA1_DIGEST_LENGTH | |
case .SHA224: | |
result = CC_SHA224_DIGEST_LENGTH | |
case .SHA256: | |
result = CC_SHA256_DIGEST_LENGTH | |
case .SHA384: | |
result = CC_SHA384_DIGEST_LENGTH | |
case .SHA512: | |
result = CC_SHA512_DIGEST_LENGTH | |
} | |
return Int(result) | |
} | |
} | |
extension String { | |
func digest(algorithm: HMACAlgorithm, key: String) -> String! { | |
let str = self.cStringUsingEncoding(NSUTF8StringEncoding) | |
let strLen = UInt(self.lengthOfBytesUsingEncoding(NSUTF8StringEncoding)) | |
let digestLen = algorithm.digestLength() | |
let result = UnsafeMutablePointer<CUnsignedChar>.alloc(digestLen) | |
let keyStr = key.cStringUsingEncoding(NSUTF8StringEncoding) | |
let keyLen = UInt(key.lengthOfBytesUsingEncoding(NSUTF8StringEncoding)) | |
CCHmac(algorithm.toCCEnum(), keyStr!, keyLen, str!, strLen, result) | |
let data = NSData(bytesNoCopy: result, length: digestLen) | |
result.destroy() | |
return data.base64EncodedStringWithOptions(nil) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Have you tried your code with http://docs.aws.amazon.com/AWSECommerceService/latest/DG/rest-signature.html? I actually stumbled on this gist searching for a way to do this hash in Swift.