Skip to content

Instantly share code, notes, and snippets.

@jernejstrasner
Last active May 4, 2020 14:54
Show Gist options
  • Star 7 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save jernejstrasner/1d5fa5e2fabda2e729d1 to your computer and use it in GitHub Desktop.
Save jernejstrasner/1d5fa5e2fabda2e729d1 to your computer and use it in GitHub Desktop.
HMAC digest in Swift
// Make sure you add #import <CommonCrypto/CommonCrypto.h> to the Xcode bridging header!
enum CryptoAlgorithm {
case MD5, SHA1, SHA224, SHA256, SHA384, SHA512
var HMACAlgorithm: 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)
}
var digestLength: Int {
var result: Int32 = 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 hmac(algorithm: CryptoAlgorithm, key: String) -> String {
let str = self.cStringUsingEncoding(NSUTF8StringEncoding)
let strLen = Int(self.lengthOfBytesUsingEncoding(NSUTF8StringEncoding))
let digestLen = algorithm.digestLength
let result = UnsafeMutablePointer<CUnsignedChar>.alloc(digestLen)
let keyStr = key.cStringUsingEncoding(NSUTF8StringEncoding)
let keyLen = Int(key.lengthOfBytesUsingEncoding(NSUTF8StringEncoding))
CCHmac(algorithm.HMACAlgorithm, keyStr!, keyLen, str!, strLen, result)
let digest = stringFromResult(result, length: digestLen)
result.dealloc(digestLen)
return digest
}
private func stringFromResult(result: UnsafeMutablePointer<CUnsignedChar>, length: Int) -> String {
var hash = NSMutableString()
for i in 0..<length {
hash.appendFormat("%02x", result[i])
}
return String(hash)
}
}
@sebastiankpunkt
Copy link

Did you already get the digest function working in Beta 6? I get weird exceptions when building. :/

@MihaelIsaev
Copy link

There's an error in Xcode6GM: 'UnsafePointer <CUnsignedChar.Type' doesn't have a member named 'alloc' at 51 line

Can you resolve it?^^

@weyhan
Copy link

weyhan commented Oct 10, 2014

On Xcode 6.1, the following modification is necessary:

51 let result = UnsafeMutablePointer(calloc(1, UInt(digestLen)))
...
58 for i in 0..<digestLen {

@joelchen
Copy link

On Xcode 6.1.1, line 51 should be UnsafeMutablePointer.alloc(digestLen) instead.

Here is a Base64 implementation: https://gist.github.com/joelchen/9a93479d8ad0c68e4f6a

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