lundi 23 mars 2015

JWT Signature Validation



I want to verify the JSON payload for Sender using shared key. I went through some sites and came up with this simple code to just verify only signature.



import java.security.InvalidKeyException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.security.SignatureException;

import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;

import org.apache.commons.codec.binary.Base64;

public class JWTVerify {
private final Base64 decoder = new Base64();
String secret="anandan";
private final byte[] bsecret=secret.getBytes();
public static void main(String args[]) throws InvalidKeyException, NoSuchAlgorithmException, SignatureException
{
String token="eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJodHRwczovL2p3dC1pZHAuZXhhbXBsZS5jb20iLCJzdWIiOiJtYWlsdG86bWlrZUBleGFtcGxlLmNvbSIsIm5iZiI6MTQyNzEwNjIwNCwiZXhwIjoxNDI3MTA5ODA0LCJpYXQiOjE0MjcxMDYyMDQsImp0aSI6ImlkMTIzNDU2IiwidHlwIjoiaHR0cHM6Ly9leGFtcGxlLmNvbS9yZWdpc3RlciJ9.BlVNHzDHelLyFCFurP72U5uPVrL8ae8EEIIuVCfSZM8";
String[] pieces = token.split("\\.");
JWTVerify jwt=new JWTVerify();
jwt.verifySignature(pieces, "HmacSHA256");

}
public void verifySignature(String[] pieces, String algorithm) throws NoSuchAlgorithmException, InvalidKeyException, SignatureException {
Mac hmac = Mac.getInstance(algorithm);
hmac.init(new SecretKeySpec(bsecret, algorithm));
byte[] sig = hmac.doFinal(new StringBuilder(pieces[0]).append(".").append(pieces[1]).toString().getBytes());
System.out.println(sig+"\n"+decoder.decodeBase64(pieces[2]));
if (!MessageDigest.isEqual(sig, decoder.decodeBase64(pieces[2]))) {
throw new SignatureException("signature verification failed");
}
}
}


But i am always getting "Signature Validation Failed".


Exception in thread "main" java.security.SignatureException: signature verification failed


Guess I am missing something. I am not sure where to go from here. I have checked the payload using http://ift.tt/1ChfV0U. It is working properly there. So the key and the message is proper.





Aucun commentaire:

Enregistrer un commentaire