Skip to content

Instantly share code, notes, and snippets.

@nitrag
Forked from davetrux/hmac.swift
Created November 8, 2016 19:06
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save nitrag/ac062b8f6ebc957071938acf06ca67ca to your computer and use it in GitHub Desktop.
Save nitrag/ac062b8f6ebc957071938acf06ca67ca to your computer and use it in GitHub Desktop.
HMAC algorithm for iOS
import Foundation
//You have to create a bridging header in your project containing:
// #import <CommonCrypto/CommonHMAC.h>
extension String {
func digestHMac256(_ key: String) -> String! {
let str = self.cString(using: String.Encoding.utf8)
let strLen = self.lengthOfBytes(using: String.Encoding.utf8)
let digestLen = Int(CC_SHA256_DIGEST_LENGTH)
let result = UnsafeMutablePointer<CUnsignedChar>.allocate(capacity: digestLen)
let keyStr = key.cString(using: String.Encoding.utf8)
let keyLen = key.lengthOfBytes(using: String.Encoding.utf8)
let algorithm = CCHmacAlgorithm(kCCHmacAlgSHA256)
CCHmac(algorithm, keyStr!, keyLen, str!, strLen, result)
var hash = NSMutableString()
for i in 0..<digestLen {
hash.appendFormat("%02x", result[i])
}
result.deinitialize()
return String(hash)
}
}
@nitrag
Copy link
Author

nitrag commented Nov 8, 2016

updated for swift 3

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