java的hmacsha1怎么改成php的,java相当于php的hmac-SHA1

事实上他们同意。

正如Hans Doggen已经指出的那样,PHP输出使用hex符号的消息摘要,除非您将原始输出参数设置为true。

如果你想在Java中使用相同的符号,你可以使用类似的东西

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

相应地格式化输出。

你可以在Java中试试这个:

private static String computeSignature(String baseString, String keyString) throws GeneralSecurityException, UnsupportedEncodingException { SecretKey secretKey = null; byte[] keyBytes = keyString.getBytes(); secretKey = new SecretKeySpec(keyBytes, "HmacSHA1"); Mac mac = Mac.getInstance("HmacSHA1"); mac.init(secretKey); byte[] text = baseString.getBytes(); return new String(Base64.encodeBase64(mac.doFinal(text))).trim(); }

这是我的实现:

String hmac = ""; Mac mac = Mac.getInstance("HmacSHA1"); SecretKeySpec secret = new SecretKeySpec(llave.getBytes(), "HmacSHA1"); mac.init(secret); byte[] digest = mac.doFinal(cadena.getBytes()); BigInteger hash = new BigInteger(1, digest); hmac = hash.toString(16); if (hmac.length() % 2 != 0) { hmac = "0" + hmac; } return hmac;

在我看来,PHP使用hex符号表示Java产生的字节(1a = 26) – 但我没有检查整个expression式。

如果您通过此页面上的方法运行字节数组会发生什么情况?

没有testing过,但试试这个:

BigInteger hash = new BigInteger(1, digest); String enc = hash.toString(16); if ((enc.length() % 2) != 0) { enc = "0" + enc; }

这是从我的方法,使Java的MD5和SHA1匹配PHP的快照。

我的HmacMD5的执行 – 只是改变algorithmHmacSHA1:

SecretKeySpec keySpec = new SecretKeySpec("secretkey".getBytes(), "HmacMD5"); Mac mac = Mac.getInstance("HmacMD5"); mac.init(keySpec); byte[] hashBytes = mac.doFinal("text2crypt".getBytes()); return Hex.encodeHexString(hashBytes);

这样我可以得到完全相同的string,因为我在PHP中使用hash_hmac

String result; try { String data = "mydata"; String key = "myKey"; // Get an hmac_sha1 key from the raw key bytes byte[] keyBytes = key.getBytes(); SecretKeySpec signingKey = new SecretKeySpec(keyBytes, "HmacSHA1"); // Get an hmac_sha1 Mac instance and initialize with the signing key Mac mac = Mac.getInstance("HmacSHA1"); mac.init(signingKey); // Compute the hmac on input data bytes byte[] rawHmac = mac.doFinal(data.getBytes()); // Convert raw bytes to Hex byte[] hexBytes = new Hex().encode(rawHmac); // Covert array of Hex bytes to a String result = new String(hexBytes, "ISO-8859-1"); out.println("MAC : " + result); } catch (Exception e) { }

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值