Skip to content

Instantly share code, notes, and snippets.

@diederikh
Last active November 8, 2016 12:16
Show Gist options
  • Save diederikh/77223d9f518e4ec03fceb4ed8b3788e5 to your computer and use it in GitHub Desktop.
Save diederikh/77223d9f518e4ec03fceb4ed8b3788e5 to your computer and use it in GitHub Desktop.
import Foundation
import CommonCryptoKit
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 stringData = self.cString(using: .utf8)
let keyData = key.cString(using: .utf8)
let result = hmacGenerate(from: stringData, withKey: keyData, using: algorithm)
return result.base64EncodedString(options:[])
}
private func hmacGenerate(from data: Data, withKey key: Data, using algorithm: CryptoAlgorithm) -> Data {
// Get data pointers
let dataBytesPointer = data.unsafeBytes
let keyBytesPointer = key.unsafeBytes
var result = Data(count: Int(algorithm.digestLength))
let resultBytesPointer = result.unsafeMutableBytes
CCHmac(algorithm.HMACAlgorithm, keyBytesPointer, key.count, dataBytesPointer, data.count, resultBytesPointer)
return result
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment