Last active
November 18, 2021 08:50
-
-
Save MaximeFrancoeur/bcb7fc2db08c704f322a to your computer and use it in GitHub Desktop.
Generating HMAC MD5/SHA1/SHA256 etc in Java
This file contains 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
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; | |
} | |
} |
soo helpful! thanks!
thank you so much dude :)
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
THANK YOU SO MUCH! :)