Friday, July 15, 2011

HmacSHA1 in Java and C#

Java:

byte[] password = "password".getBytes();
SecretKeySpec keySpec = new SecretKeySpec(password,"HmacSHA1");
Mac hmacsha1 = Mac.getInstance("HmacSHA1");
hmacsha1.init(keySpec);
byte[] hash = hmacsha1.doFinal("test".getBytes());
String hashBase64 = new String(Base64.encodeBase64(hash));
System.out.println(hashBase64);

C#:

System.Text.ASCIIEncoding encoding = new System.Text.ASCIIEncoding();
byte[] password = encoding.GetBytes("password");

HMACSHA1 hmacsha1 = new HMACSHA1(password);
byte[] hash = hmacsha1.ComputeHash(encoding.GetBytes("test"));

String hashBase64 = Convert.ToBase64String(hash);
Console.WriteLine(hashBase64);

1 comment:

  1. where did you get the Base64 class (in the java code)?

    ReplyDelete