java相当于php的hmac-SHA1 [英] java equivalent to php's hmac-SHA1

查看:759
本文介绍了java相当于php的hmac-SHA1的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在寻找一个等价于此php调用的java:

I'm looking for a java equivalent to this php call:

hash_hmac('sha1', "test", "secret")

我试过这个,使用 java.crypto.Mac ,但两者不同意:

I tried this, using java.crypto.Mac, but the two do not agree:

String mykey = "secret";
String test = "test";
try {
    Mac mac = Mac.getInstance("HmacSHA1");
    SecretKeySpec secret = new SecretKeySpec(mykey.getBytes(),"HmacSHA1");
    mac.init(secret);
    byte[] digest = mac.doFinal(test.getBytes());
    String enc = new String(digest);
    System.out.println(enc);  
} catch (Exception e) {
    System.out.println(e.getMessage());
}

具有key =secret和test =test的输出

The outputs with key = "secret" and test = "test" do not seem to match.

推荐答案

事实上,他们同意。

正如Hans Doggen已经提到的PHP输出消息摘要,除非您将原始输出参数设置为true。

如果要在Java中使用相同的符号,可以使用

In fact they do agree.
As Hans Doggen already noted PHP outputs the message digest using hexadecimal notation unless you set the raw output parameter to true.
If you want to use the same notation in Java you can use something like

for (byte b : digest) {
    System.out.format("%02x", b);
}
System.out.println();

相应地格式化输出。

这篇关于java相当于php的hmac-SHA1的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆