java equivalent to php's hmac-SHA1 java equivalent to php's hmac-SHA1 java java

java equivalent to php's hmac-SHA1


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

to format the output accordingly.


You can try this in 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();}


This is my implementation :

        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;