Sep 20, 2018

Swift4 - php hash_hmac to iOS hash

While working on APIs this could be one problem when the docs only written in php. :(

While looking the solution I found CryptoSwift which could help and solve my problem. Please check CryptoSwift on how to install.

Hear's same php to iOS conversion code.
PHP hash_hmac:
$hash = hash_hmac( 'SHA512', "YOUR_STRING_DATA_TO_HASH_HERE", 'YOUR_SECRET_KEY' // SHARED KEY ); print ("HMAC:" . $hash);

XCODE hmac
let yourData: Array = Array("YOUR_STRING_DATA_TO_HASH_HERE".utf8)
do{
   let myhmac = try HMAC(key: "YOUR_SECRET_KEY", variant: .sha512)

    // great your found your hash
   let iosHash = try myhmac.authenticate(password).toHexString()
   print ("HMAC:", iosHash)
}catch let err as NSError{
    
}


PHP hash:
$hash = hash( 'SHA512', "YOUR_STRING_DATA_TO_HASH_HERE" ); print ("HMAC:" . $hash);

XCODE Hash
print ("Hash:", "YOUR_STRING_DATA_TO_HASH_HERE".sha512())


NOTED: Be sure you import the CryptoSwift in your swift code.

Thanks for passing by.