title: why PHP's hash_hmac('sha256') gives different result than java sha256_HMAC
body: <p>in PHP I have the following function:</p>
  
  <pre><code>base64_encode(hash_hmac('sha256', $data, $secret, false));
  </code></pre>
  
  <p>I'm trying to create a function in Java that will give the same result for the same "data" and "secret" parameters. </p>
  
  <p>I tried to use this function:</p>
  
  <pre><code>public static String base64sha256(String data, String secret) {
      Mac sha256_HMAC = Mac.getInstance("HmacSHA256");
      SecretKeySpec secret_key = new SecretKeySpec(secret.getBytes(), "HmacSHA256");
      sha256_HMAC.init(secret_key);
      byte[] res = sha256_HMAC.doFinal(data.getBytes());
      return Base64.encodeToString(res, Base64.NO_WRAP);
  }
  </code></pre>
  
  <p>But I get different results for the same input</p>
  
  <hr>
  
  <p>Update: This function works. Enjoy.</p>
  
  <pre><code>public static String base64sha256(String data, String secret) {
      String hash = null;
      try {
          Mac sha256_HMAC = Mac.getInstance("HmacSHA256");
          SecretKeySpec secret_key = new SecretKeySpec(secret.getBytes("UTF-8"), "HmacSHA256");
          sha256_HMAC.init(secret_key);
          byte[] res = sha256_HMAC.doFinal(data.getBytes("UTF-8"));
          hash = getHex(res);
          hash = Base64.encodeToString(hash.getBytes("UTF-8"), Base64.NO_WRAP);
      } catch (Exception e){}
      return hash;
  }
  
  static final String HEXES = "0123456789abcdef";
  public static String getHex( byte [] raw ) {
      if ( raw == null ) {
          return null;
      }
      final StringBuilder hex = new StringBuilder( 2 * raw.length );
      for ( final byte b : raw ) {
          hex.append(HEXES.charAt((b &amp; 0xF0) &gt;&gt; 4))
                  .append(HEXES.charAt((b &amp; 0x0F)));
      }
      return hex.toString();
  }
  </code></pre>