Mohan Raja
Mohan Raja

Reputation: 129

JWT(JSON Web Token) generated in node.js not validated in java

I am generating JWT using Node.js with require('jsonwebtoken') using public key which is generated by puttygen tool in windows. Then i will pass that token to other application in headers. The Other application is not developed in Node.js. Using java I need to validate the token with public key. But none of the sites i found a valid sample to verify using public/private key.

Can any one please provide me steps how i can load public/private key in java and verify jwt token. Please provide me examples if any you have. Thanks in advance.

Sample public key (public.pem) :-

---- BEGIN SSH2 PUBLIC KEY ----
Comment: "rsa-key-20160721"
AAAAB3NzaC1yc2EAAAABJQAAAQEAhk1i7Jwz2M6zakReDgg0NkVPn1kK1R8qAp2p
Ayh0eUPCb2XICDDVRnpUIK7/4k4dlLeeSi10TwwXe85zZ0gXcNMIOpnEKIWcnqJM
ctbYwyrl2tAb/tKjvBCvHMA9ZnfNADkN6reBZq8u7kYJ3bF9PxvS3QM+vgJ8/8ZS
qkRWcsmRZdq+wthwGt43J3NSKFfhMVP08/V/hTASq06vvFYApHsEH6zLxNNQ63Tt
Bzedh+C5efyqYqEVqnA7S9bXimyY2ViqpqFTx1lM9dV+12dSOxd7CQzX8eo00Phi
EAnY2hfoTooUeCO3/L6YavRl+CXgjhvA9mg4QO554qI1YCUvBw==
---- END SSH2 PUBLIC KEY ----

Node JS code:-

var privateKey = fs.readFileSync("public.pem");
var userData = {username:'John'};
var token = jwt.sign(userData, privateKey);

Java Code:-

Needed java code which can verify above token using above public key.

Upvotes: 1

Views: 1184

Answers (1)

pedrofb
pedrofb

Reputation: 39241

Cryptographic operations are independent of programming language. You can perfectly generate a JWT in nodeJS and verify in Java.

JWT is digitally signed with the private key and signature is verified with public key. In case of HMAC symmetric keys, the key to sign and verify is the same.

Use a JWT library for Java like https://github.com/jwtk/jjwt

 Jwts.parser().setSigningKey(key).parseClaimsJws(compactJws);

In the page you can see the supported algorithms.

Putty uses its own key format. Java does not supports it. You need to export the Putty SSH2 key to the OpenSSH format. See How can I read RSA keys in Java?

Upvotes: 0

Related Questions