Skip to content

Instantly share code, notes, and snippets.

@artem-smotrakov
Created August 15, 2021 14:22
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 artem-smotrakov/aaff397fa5194f975fa5b038a94361c1 to your computer and use it in GitHub Desktop.
Save artem-smotrakov/aaff397fa5194f975fa5b038a94361c1 to your computer and use it in GitHub Desktop.
Using constant-time algorithm for validating a MAC
public boolean validate(HttpRequest request, SecretKey key) throws Exception {
byte[] message = getMessageFrom(request);
byte[] signature = getSignatureFrom(request);
Mac mac = Mac.getInstance("HmacSHA256");
mac.init(new SecretKeySpec(key.getEncoded(), "HmacSHA256"));
byte[] actual = mac.doFinal(message);
return MessageDigest.isEqual(signature, actual);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment