Java功能
private static byte[] getHmac(String login, String password, byte[] key) throws NoSuchAlgorithmException, InvalidKeyException {
// byte[] Login = login.getBytes(StandardCharsets.US_ASCII);//OK
byte[] pwdBytes = (login + password).getBytes(StandardCharsets.US_ASCII);//OK
//MD5
MessageDigest md = MessageDigest.getInstance("md5");
md.update(pwdBytes);
byte[] pwdbytes_md5 = md.digest();//OK
//HMAC
Mac mac = Mac.getInstance("HmacMD5");
SecretKey sk = new SecretKeySpec(key, mac.getAlgorithm());
mac.init(sk);
mac.update(pwdbytes_md5);
return mac.doFinal();
}
C#功能
public byte[] GetHash(string login, string password, byte[] key)
{
byte[] pwdBytes = Encoding.ASCII.GetBytes(login + password);
MD5 md = MD5.Create();
byte[] pwdbytes_md5 = md.ComputeHash(pwdBytes);
Hash = new HMACMD5(pwdbytes_md5).ComputeHash(key);
return Hash;
}
输入:
login = happy
密码= 89631139
key = [0x04,0x00,0x00,0x50,0x00,0x00,0x00,0x00,0x6b,0x2e,0x8e,0x6b,0x3c,0xb7,0x02,0x06]
输出(调试中的var值)c#
key = 0x04,0x00,0x00,0x50,0x00,0x00,0x00,0x00,0x6b,0x2e,0x8e,0x6b,0x3c,0xb7,0x02,0x06 = ok
md5 = 0x5a,0x6a,0x0b,0xef,0xff,0x83,0x2f,0x61,0x5e,0x16,0xc7,0x3d,0x5a,0x6e,0xde,0x65 = ok
登录= 0x68,0x61,0x70,0x70,0x79 = ok
pwdBytes = 0x68,0x61,0x70,0x70,0x79,0x38,0x39,0x36,0x33,0x31,0x31,0x33,0x39 = ok
Hash = 0x6a,0xcd,0xad,0x49,0x8d,0x54,0xfe,0xf1,0xca,0x4e,0x74,0xd8,0x52,0x46,0x09,0x6a = ok
这些是变量的预期输出以及函数的返回, 但是在用java编写的函数中,所有输出都是,除了函数的返回,在这种情况下是散列,C#的正确,但我不能以任何方式在java中返回相同的值。
java中的始终返回此值> A3 DE F0 6C 9D 53 87 4A 18 23 FD 2C F6 E4 15 0D
但是,返回函数所需的值必须是C#
有没有人知道在java中实现c#功能的正确方法,我已经搜索过网站的所有内容并且没有解决方案,谢谢。
答案 0 :(得分:0)
错误在C#代码中。密钥和数据被切换。如果你在Java中做同样的事情,你会得到与C#相同的结果:
private static byte[] getHmac(final String data, final byte[] key)
throws NoSuchAlgorithmException, InvalidKeyException {
// byte[] Login = login.getBytes(StandardCharsets.US_ASCII);//OK
final byte[] pwdBytes = data.getBytes(StandardCharsets.US_ASCII);// OK
// MD5
final MessageDigest md = MessageDigest.getInstance("md5");
md.update(pwdBytes);
final byte[] pwdbytes_md5 = md.digest();// OK
// HMAC
final Mac mac = Mac.getInstance("HmacMD5");
final SecretKey sk = new SecretKeySpec(pwdbytes_md5, mac.getAlgorithm());
mac.init(sk);
mac.update(key);
return mac.doFinal();
}