开发者

C# HMAC to Java

开发者 https://www.devze.com 2023-02-11 09:48 出处:网络
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?

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.M开发者_JAVA技巧D5:
        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! :)


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));


See this question about computing hash functions in Java.

And look at the javadoc for java.security.MessageDigest.getInstance(String algorithm).

Edited to add:

Try running the following app to see what providers you have registered.


import java.security.Provider;
import java.security.Security;

public class SecurityTest {

    public static void main(String[] args) {

        Provider[] providers = Security.getProviders();
        for (Provider p : providers) {
            System.out.println(p.toString());
        }
    }
}

You should have at least a few Sun providers listed. If not, you may need to download some security libraries.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号