Skip to content

Instantly share code, notes, and snippets.

@vinhjaxt
Forked from border/Signature.java
Created July 23, 2017 00:24
Show Gist options
  • Save vinhjaxt/af8dcf83d622687f57721e19c1cccad2 to your computer and use it in GitHub Desktop.
Save vinhjaxt/af8dcf83d622687f57721e19c1cccad2 to your computer and use it in GitHub Desktop.
Signature for php and java
The answer is in the documentation for the PHP function hash_hmac.
When set to TRUE, outputs raw binary data. FALSE outputs lowercase hexits.
Pass "true" as the final argument. Hashes are binary. When turning them into strings, they are often encoded in hexadecimal. But in this case you are going to base-64 encode it, so you want the raw binary form.
from: http://stackoverflow.com/questions/11002603/base64-encode-different-between-java-and-php
static String generateSignature () {
String encoded = "";
String type = "HmacSHA1";
try {
byte[] key = ("KEY").getBytes("UTF-8");
byte[] Sequence = ("hello").getBytes("UTF-8");
Mac HMAC = Mac.getInstance(type);
SecretKeySpec secretKey = new SecretKeySpec(key, type);
HMAC.init(secretKey);
byte[] Hash = HMAC.doFinal(Sequence);
encoded = Base64.getEncoder().encodeToString(Hash);
} catch (Exception e) {
e.printStackTrace();
}
System.out.println(encoded);
return encoded;
}
$key = "KEY";
$sequence = "hello";
$encrypted = hash_hmac('sha1', $sequence, $key, true);
echo base64_encode($encrypted).PHP_EOL;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment