java相当于php的hmac-SHA1

我在找一个相当于这个php调用的java:

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

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

 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”的输出似乎不匹配。

事实上他们同意。
正如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) { }