jokecamp / jokecamp.com

personal blog and website
https://www.jokecamp.com
84 stars 40 forks source link

HMAC SHA256 | issue in Java example #13

Closed Atifmahmood12 closed 6 years ago

Atifmahmood12 commented 6 years ago

https://github.com/jokecamp/jokecamp.com/commit/2d9f0734ae437b6d2d0603bc13c9f94435e1df89

Curernt example:

import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import org.apache.commons.codec.binary.Base64;

public class ApiSecurityExample {
  public static void main(String[] args) {
    try {
     String secret = "secret";
     String message = "Message";

     Mac sha256_HMAC = Mac.getInstance("HmacSHA256");
     SecretKeySpec secret_key = new SecretKeySpec(secret.getBytes(), "HmacSHA256");
     sha256_HMAC.init(secret_key);

     String hash = Base64.encodeBase64String(sha256_HMAC.doFinal(message.getBytes()));
     System.out.println(hash);
    }
    catch (Exception e){
     System.out.println("Error");
    }
   }
}

Correction in Example:

import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import org.apache.commons.codec.binary.Base64;

public class ApiSecurityExample {
  public static void main(String[] args) {
    try {
     String secret = "secret";
     String message = "Message";

     Mac sha256_HMAC = Mac.getInstance("HmacSHA256");
     SecretKeySpec secret_key = new SecretKeySpec(**Base64.decode**(secret.getBytes()), "HmacSHA256");
     sha256_HMAC.init(secret_key);

     String hash = Base64.encodeBase64String(sha256_HMAC.doFinal(message.getBytes()));
     System.out.println(hash);
    }
    catch (Exception e){
     System.out.println("Error");
    }
   }
}

Note: Please correct it in the documentation.

jokecamp commented 6 years ago

Looks like Base64.decode is the diff in the line new SecretKeySpec(**Base64.decode**(secret.getBytes()), "HmacSHA256");.

Atifmahmood12 commented 6 years ago

Yes. That is the difference. secrete key decoding is also necessary here.

jokecamp commented 6 years ago

There is no need to decode the secret in these simple examples. We never expose or pass the secret so we don't need it in base64. I'm going to leave as is to keep it the same as all the other examples.

Your own implementation may vary but for these examples it is not needed.

jokecamp commented 6 years ago

Thanks for the feedback though. It is appreciated.

Atifmahmood12 commented 6 years ago

OK. You welcome.