Using HMAC in PHP or C#/VB.net

PHP

Code

<?php
echo "Output: ", hash_hmac('sha256', 'Hello, World!', 'secret');
?>

Although I’ve only focused on SHA256, PHP supports a number of algorithms, for the full list use the following code, then simply replace ‘sha256′ with the name of the algorithm you need, but please note that .Net framework doesn’t support as many algorithms as PHP does.

<?php
print_r(hash_algos());
?>

Output

Output: fcfaffa7fef86515c7beb6b62d779fa4ccf092f2e61c164376054271252821ff

C#

.Net doesn’t support as many algorithms as PHP, here is the full list of the supported algorithms as of .Net 4.0.

  • HMACMD5
  • HMACRIPEMD160
  • HMACSHA1
  • HMACSHA256
  • HMACSHA384
  • HMACSHA512

Code

using System;
using System.Text;
using System.Security.Cryptography;

Encoding e = Encoding.UTF8;

// Initialize the keyed hash object.
HMACSHA256 hmac = new HMACSHA256(e.GetBytes("secret"));
byte[] b = hmac.ComputeHash(e.GetBytes("Hello, World!"));

StringBuilder s = new StringBuilder();
for (int i = 0; i < b.Length; i++)
{
	s.Append(b[i].ToString("x2"));
}
Console.WriteLine("Output: {0}", s.ToString());

If you want a slightly shorter version you can use the following, however you will need a newer version of .Net.

Note: You need C# 3.0/.Net 3.5+ for this to work.
using System;
using System.Linq;
using System.Text;
using System.Security.Cryptography;

...

Encoding e = Encoding.UTF8;

// Initialize the keyed hash object.
HMACSHA256 hmac = new HMACSHA256(e.GetBytes("secret"));
byte[] b = hmac.ComputeHash(e.GetBytes("Hello, World!"));

string s = b.Aggregate("", (current, b1) => current + b1.ToString("x2"));

Console.WriteLine("Output: {0}", s);

Output

Output: fcfaffa7fef86515c7beb6b62d779fa4ccf092f2e61c164376054271252821ff

VB.net

As all the .Net languages use the same framework, there is no difference in the type of algorithm you can use, it's just a question of which language you are using to code.

Code

Imports System.Security.Cryptography
Imports System.Text

...

Dim e As Encoding = Encoding.UTF8

' Initialize the keyed hash object.
Dim hmac As New HMACSHA256(e.GetBytes("secret"))
Dim b As Byte() = hmac.ComputeHash(e.GetBytes("Hello, World!"))

Dim s As New StringBuilder()
For i As Integer = 0 To b.Length - 1
	s.Append(b(i).ToString("x2"))
Next
Console.WriteLine("Output: {0}", s.ToString())

As you can see, all the outputs are exactly the same. This code is useful if your working on a client that uses .Net and a Web Service that uses PHP.

This entry was posted in C#, Cryptography, PHP, Programming, VB.net. Bookmark the permalink.

Comments are closed.