Last active
August 29, 2015 14:05
-
-
Save Henriquedn/669f54a23f52307b07a2 to your computer and use it in GitHub Desktop.
Java hmacDigest to match provider php digest
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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