-
-
Save nitrag/ac062b8f6ebc957071938acf06ca67ca to your computer and use it in GitHub Desktop.
HMAC algorithm for iOS
This file contains 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
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) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
updated for swift 3