Skip to content

Instantly share code, notes, and snippets.

@Henriquedn
Last active August 29, 2015 14:05
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Henriquedn/669f54a23f52307b07a2 to your computer and use it in GitHub Desktop.
Save Henriquedn/669f54a23f52307b07a2 to your computer and use it in GitHub Desktop.
Java hmacDigest to match provider php digest
public static String hmacDigest(String msg, String keyString, String algo) {
String digest = null;
try {
SecretKeySpec key = new SecretKeySpec((keyString).getBytes("UTF-8"), algo);
Mac mac = Mac.getInstance(algo);
mac.init(key);
byte[] bytes = mac.doFinal(msg.getBytes("UTF-8"));
StringBuffer hash = new StringBuffer();
for (int i = 0; i < bytes.length; i++) {
String hex = Integer.toHexString(0xFF & bytes[i]);
if (hex.length() == 1) {
hash.append('0');
}
hash.append(hex);
}
digest = hash.toString();
} catch (UnsupportedEncodingException e) {
} catch (InvalidKeyException e) {
} catch (NoSuchAlgorithmException e) {
}
return digest;
}
//Usage
String hashid = hmacDigest(datastring, hashkey, "HmacSHA1");
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment