Search code examples
c#xamarinxamarin.formssha1portable-class-library

SHA1 keyed Hash with HMAC in Xamarin Forms PCL [C# equivalent to hash_hmac in PHP]


I'm trying to generate a keyed hash value using the HMAC method for a data message input and a secret key. What is the equivalent for the following PHP code in C#?

PHP

#!/usr/bin/php
<?php
$data = "WhatIsYourNumber";
$secretKey = "AliceAndBob";
echo hash_hmac('sha1', $data, $secretKey);
?>

Result:

e96af95f120df7b564b3dfecc0e74a870755ad9d

I would like to use it in a Xamarin Forms Portable Class Library (PCL).


Solution

  • First I found a solution with using System.Security.Cryptography; but I forget it for that solution :

    As said @Giorgi, install PCLCrypto NuGet package into your PCL project and Client projects.

    Use this code :

    using System.Text;
    using PCLCrypto;
    
    public static string hash_hmacSha1(string data, string key) {
        byte[] keyBytes = Encoding.UTF8.GetBytes(key);
        byte[] dataBytes = Encoding.UTF8.GetBytes(data);
        var algorithm = WinRTCrypto.MacAlgorithmProvider.OpenAlgorithm(MacAlgorithm.HmacSha1);
        CryptographicHash hasher = algorithm.CreateHash(keyBytes);
        hasher.Append(dataBytes);
        byte[] mac = hasher.GetValueAndReset();
    
        StringBuilder sBuilder = new StringBuilder();
        for (int i = 0; i < mac.Length; i++) {
            sBuilder.Append(mac[i].ToString("X2"));
        }
        return sBuilder.ToString().ToLower();
    }
    

    .

    string data = "WhatIsYourNumber";
    string secretKey = "AliceAndBob";
    System.Diagnostics.Debug.WriteLine("{0}", Utils.hash_hmacSha1(data, secretKey));
    

    Result:

    e96af95f120df7b564b3dfecc0e74a870755ad9d
    

    Sources : https://github.com/AArnott/PCLCrypto/wiki/Crypto-Recipes