java equivalent to php's hmac-SHA1

前端 未结 7 880
花落未央
花落未央 2020-11-28 20:33

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

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

I tried this, using java.crypto.Mac, but the

7条回答
  •  北海茫月
    2020-11-28 21:30

    This way I could get the exact same string as I was getting with hash_hmac in php

    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) {
    
    }
    

提交回复
热议问题