Search code examples
c#javahmacsha1language-translation

C# HMAC to Java


I'm making the equivalent java code for the code below. But I can make something that returns the same result for encodedString. What Java class can I use for achieve the same result?

//Set the Hash method to SHA1
HMAC hash;
switch (validation)
{
    case MachineKeyValidation.MD5:
        hash = new HMACMD5();
        break;
    case MachineKeyValidation.SHA1:
    default:
        hash = new HMACSHA1();
        break;
}
//Get the hash validation key as an array of bytes
hash.Key = HexToByte(validationKey);
//Encode the password based on the hash key and
//converts the encrypted value into a string
encodedString = Convert.ToBase64String(hash.ComputeHash(Encoding.Unicode.GetBytes(password)));

Thanks in advance! :)


Solution

  • I found a solution for the translation code. There was two main problem. When a request a HMACSHA1 I'm not talking about a SHA1 algorithm, but a HmacSHA1. And there is a difference between the encoding from Java and C#. I was using the correct key, and the correct algorithm, but the encoding was differente.

    SecretKeySpec signingKey = new SecretKeySpec(key, "HmacSHA1");
    Mac mac = Mac.getInstance("HmacSHA1");
    mac.init(signingKey);
    // The big problem is difference between C# and Java encoding
    byte[] rawHmac = mac.doFinal(data.getBytes("UTF-16LE"));
    result = new String(Base64.encode(rawHmac));