Skip to content

Instantly share code, notes, and snippets.

@MaximeFrancoeur
Last active November 18, 2021 08:50
Show Gist options
  • Save MaximeFrancoeur/bcb7fc2db08c704f322a to your computer and use it in GitHub Desktop.
Save MaximeFrancoeur/bcb7fc2db08c704f322a to your computer and use it in GitHub Desktop.
Generating HMAC MD5/SHA1/SHA256 etc in Java
import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import java.io.UnsupportedEncodingException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
public class HMAC {
public static void main(String[] args) throws Exception {
System.out.println(hmacDigest("The quick brown fox jumps over the lazy dog", "key", "HmacSHA1"));
}
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("ASCII"));
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;
}
}
@miraclebg
Copy link

THANK YOU SO MUCH! :)

@kostantza
Copy link

soo helpful! thanks!

@isengkali
Copy link

thank you so much dude :)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment