Skip to content

Instantly share code, notes, and snippets.

@nitrag nitrag/hmac.swift

forked from davetrux/hmac.swift
Created Nov 8, 2016
What would you like to do?
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])
return String(hash)

This comment has been minimized.

Copy link
Owner 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
You can’t perform that action at this time.