Generated JSON Web signature under Java expresses invalid signature

Based on the nimbus-jose-jwt Java library, I tried to create the following JNT Web Token (JWT) and signed it using JSON Web Signature (JWS) using the string "secret", hashed SHA256.

But after generating the serialized string and checking it against jwt.io , I always get an "Invalid Signature" error.

When I try to decode server side using a Python decoder, I also get a signature error. What could be wrong?

byte[] bytes = new byte[32];
String message = "secret";
MessageDigest md = MessageDigest.getInstance("SHA-256");
bytes = md.digest(message.getBytes("UTF-8"));

JWSSigner signer = new MACSigner(bytes);

// Prepare JWT with claims set
JWTClaimsSet claimsSet = new JWTClaimsSet();
claimsSet.setSubject("alice");

SignedJWT signedJWT = new SignedJWT(new JWSHeader(JWSAlgorithm.HS256), claimsSet);

// Apply the HMAC
signedJWT.sign(signer);

// To serialize to compact form, produces something like
String s = signedJWT.serialize();

      

+3


source to share


1 answer


It looks like you are using the SHA-256 digest "secret" as the key to generate the MAC and a plain old "secret" for verification. Replace:

byte[] bytes = new byte[32];
String message = "secret";
MessageDigest md = MessageDigest.getInstance("SHA-256");
bytes = md.digest(message.getBytes("UTF-8"));

JWSSigner signer = new MACSigner(bytes);

      



from:

JWSSigner signer = new MACSigner("secret");

      

0


source







All Articles