Note that there are some explanatory texts on larger screens.

plurals
  1. POHMAC-SHA1: How to do it properly in Java?
    primarykey
    data
    text
    <p>I'm hashing some values using HMAC-SHA1, using the following code in Java:</p> <pre><code>public static String hmacSha1(String value, String key) { try { // 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(value.getBytes()); // Convert raw bytes to Hex byte[] hexBytes = new Hex().encode(rawHmac); // Covert array of Hex bytes to a String return new String(hexBytes, "UTF-8"); } catch (Exception e) { throw new RuntimeException(e); } } </code></pre> <p><code>Hex()</code> belongs to <code>org.apache.commons.codec</code></p> <p>In PHP there's a similar function <code>hash_hmac(algorithm, data, key)</code> that I use to compare the values returned by my Java implementation.</p> <p>So the first try is:</p> <pre><code>hash_hmac("sha1", "helloworld", "mykey") // PHP </code></pre> <p>that returns: <code>74ae5a4a3d9996d5918defc2c3d475471bbf59ac</code></p> <p>My Java function returns <code>74ae5a4a3d9996d5918defc2c3d475471bbf59ac</code> as well.</p> <p>Ok, it seems working. Then I try to use a more complex key:</p> <pre><code>hash_hmac("sha1", "helloworld", "PRIE7$oG2uS-Yf17kEnUEpi5hvW/#AFo") // PHP </code></pre> <p>that returns: <code>e98bcc5c5be6f11dc582ae55f520d1ec4ae29f7a</code></p> <p>While this time my Java impl returns: <code>c19fccf57c613f1868dd22d586f9571cf6412cd0</code></p> <p>The hash returned by my PHP code is not equal to the value returned by my Java function, and I can't find out why.</p> <p>Any tips?</p>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload