Crizly
Crizly

Reputation: 1009

How to verify HMAC java

I've got the following code to compute Hmacs with a password:

public static void main(String[] args) throws NoSuchAlgorithmException, InvalidKeyException 
{
  String password = "password123";
  SecretKeySpec keySpec = new SecretKeySpec(password.getBytes(), "HmacSHA1");

  Mac mac = Mac.getInstance("HmacSHA1");
  mac.init(keySpec);

  byte[] result = mac.doFinal("This is a test string".getBytes());

  System.out.println(new Base64().encodeAsString(result));
}

But I can't figure out how to verify it with a password, I'm reading the Java documentation here but i can't seem to find a verify function or anything, the section on HMACs is quite short.

How do i verify the HMAC with the password?

Upvotes: 1

Views: 5096

Answers (1)

yami
yami

Reputation: 881

Just adding this as answer as mentioned by "Markus W Mahlberg" for better viewing purpose. You simply do the hashing again and check wether the results match. If either of the strings has the slightest difference, the hash will not match. If they match, you know that both input strings and both passwords matched, because the hash matches

https://en.wikipedia.org/wiki/Message_authentication_code https://upload.wikimedia.org/wikipedia/commons/thumb/0/08/MAC.svg/661px-MAC.svg.png

Upvotes: 5

Related Questions