How to replicate hash_hmac('sha256', $key, $secret_key) function in Swift 4?

iedi3

I've tried generating the hash_hmac('sha256', $key, $secret_key) php function equivalent in Swift 4 without success, after using libraries like CommonCrypto, CryptoSwift. I need these function for API authentication, using Alamofire library, which is a great library. Since i use Swift 4 the compatibility with other Swift libraries is not so good. Even with CryptoSwift which has the latest version(0.7.1) for Swift 4 i still get a lot of compatibility errors likes enter image description here

zaph

Swift 3/4:

HMAC with MD5, SHA1, SHA224, SHA256, SHA384, SHA512 (Swift 3)

These functions will hash either String or Data input with one of eight cryptographic hash algorithms.

The name parameter specifies the hash function name as a String Supported functions are MD5, SHA1, SHA224, SHA256, SHA384 and SHA512

This example requires Common Crypto
It is necessary to have a bridging header to the project:
#import <CommonCrypto/CommonCrypto.h>
Add the Security.framework to the project.

These functions takes a hash name, message to be hashed, a key and return a digest:


hashName: name of a hash function as String  
message:  message as Data  
key:      key as Data  
returns:  digest as Data  
func hmac(hashName:String, message:Data, key:Data) -> Data? {
    let algos = ["SHA1":   (kCCHmacAlgSHA1,   CC_SHA1_DIGEST_LENGTH),
                 "MD5":    (kCCHmacAlgMD5,    CC_MD5_DIGEST_LENGTH),
                 "SHA224": (kCCHmacAlgSHA224, CC_SHA224_DIGEST_LENGTH),
                 "SHA256": (kCCHmacAlgSHA256, CC_SHA256_DIGEST_LENGTH),
                 "SHA384": (kCCHmacAlgSHA384, CC_SHA384_DIGEST_LENGTH),
                 "SHA512": (kCCHmacAlgSHA512, CC_SHA512_DIGEST_LENGTH)]
    guard let (hashAlgorithm, length) = algos[hashName]  else { return nil }
    var macData = Data(count: Int(length))

    macData.withUnsafeMutableBytes {macBytes in
        message.withUnsafeBytes {messageBytes in
            key.withUnsafeBytes {keyBytes in
                CCHmac(CCHmacAlgorithm(hashAlgorithm),
                       keyBytes,     key.count,
                       messageBytes, message.count,
                       macBytes)
            }
        }
    }
    return macData

}

hashName: name of a hash function as String
message:  message as String
key:      key as String
returns:  digest as Data
func hmac(hashName:String, message:String, key:String) -> Data? {
    let messageData = message.data(using:.utf8)!
    let keyData = key.data(using:.utf8)!
    return hmac(hashName:hashName, message:messageData, key:keyData)
}

hashName: name of a hash function as String  
message:  message as String  
key:      key as Data  
returns:  digest as Data  
func hmac(hashName:String, message:String, key:Data) -> Data? {
    let messageData = message.data(using:.utf8)!
    return hmac(hashName:hashName, message:messageData, key:key)
}

// Examples

let clearString = "clearData0123456"
let keyString   = "keyData8901234562"
let clearData   = clearString.data(using:.utf8)!
let keyData     = keyString.data(using:.utf8)!
print("clearString: \(clearString)")
print("keyString:   \(keyString)")
print("clearData: \(clearData as NSData)")
print("keyData:   \(keyData as NSData)")

let hmacData1 = hmac(hashName:"SHA1", message:clearData, key:keyData)
print("hmacData1: \(hmacData1! as NSData)")

let hmacData2 = hmac(hashName:"SHA1", message:clearString, key:keyString)
print("hmacData2: \(hmacData2! as NSData)")

let hmacData3 = hmac(hashName:"SHA1", message:clearString, key:keyData)
print("hmacData3: \(hmacData3! as NSData)")

Output:

clearString: clearData0123456
keyString:   keyData8901234562
clearData: <636c6561 72446174 61303132 33343536>
keyData:   <6b657944 61746138 39303132 33343536 32>

hmacData1: <bb358f41 79b68c08 8e93191a da7dabbc 138f2ae6>
hmacData2: <bb358f41 79b68c08 8e93191a da7dabbc 138f2ae6>
hmacData3: <bb358f41 79b68c08 8e93191a da7dabbc 138f2ae6>

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related

what is secret_key parameter in hash_hmac function

How to encrypt data with sha256 with hash_hmac in Rails like in this php function

How do I specify the key for computing a SHA256 hash?

How do you supply a specific binary key to the PHP hash_hmac() function?

HMAC SHA256 in Swift 4

Generate HMAC SHA256 hash using key in C++

creating a HMAC SHA256 key in python

sha256 hash from public key

Hmac with SHa256 Or SHa256 with key appended in the input string? Which is more secure?

Hash a string in Java emulating the php function hash_hmac using ripemd160 with a key

How to hide SECRET_KEY?

typescript crypto-js how to hash data using sha256 algorithm and key

How to encrypt using AES with sha256 hash as key crypto++

Creating SHA256 hash with swift4

How to HMAC SHA256 sign a string with a double array key or an hex string key using google apps script?

How to use hash_hmac() with "SHA256withRSA" on PHP?

How to keep a SECRET_KEY secret in Django?

Equivalent from PHP hash_hmac("sha384", $data, $key) in .NET

How can I replicate a javascript sha256 hash in Java and get the same Hex output?

How to replicate sha256 hash example from CyberSource REST API documentation?

How is Devise's secret_key used?

How to hash output of sha256 with sha256 in rust

can I use sha1,sha256 lib generated string as a hash key

HMAC + SHA256 jwt secret length

How to work hash_hmac function in codeigniter or laravel?

How to generate hash_hmac sha1 php?

Generate a hashed message with SHA256 hmac in php (key & msg are fake)

How do I properly convert this SHA256 encryption function in PHP based off this Swift code?

Trying to create a sha256 key and hash in Elixir (converting from python code)