Validating jwt in java: Key bytes cannot be specif

2019-07-15 03:33发布

问题:

I receive the jwt (access token) from an OAuth Server. The OAuth server has already provided me with the secret, public key, and self-signed CA certificate.

I want to write a code that when I receive a jwt, I can validate it and check if this server has sent it to me. I use the following code to validat my jwt in java.

String jwt = "xxx.yyy.zzz";

        //This line will throw an exception if it is not a signed JWS (as expected)
Claims claims = Jwts.parser().setSigningKey(DatatypeConverter.parseBase64Binary(self_signed_CA_Certificate))
                .parseClaimsJws(jwt).getBody();

I get the error: Key bytes cannot be specified for RSA signatures. Please specify a PublicKey or PrivateKey instance.

Any help is appreciated.

回答1:

I had the same problem, it was my solution

in my case I gad a certificate that give the ability that can be signed with different keys,

   CertificateFactory fact = CertificateFactory.getInstance("X.509");
   FileInputStream is = new FileInputStream ("yourcertificate.jks");
   Certificate cer = fact.generateCertificate(is);
   PublicKey  publicKey = cer.getPublicKey();

and then to verify the jwt token used:

 Claims body = Jwts.parser()
                .setSigningKey(publicKey)
                .parseClaimsJws(token)
                .getBody();


回答2:

you have to create secretKey using RSA like

SecretKey secretKey = KeyGenerator.getInstance("AES").generateKey(); 
or 
Key secretKey = MacProvider.generateKey();

use same secretKey key to generate jwt string and decrypt it using same secrete key like

SecretKey secretKey = KeyGenerator.getInstance("AES").generateKey();
String compactJws = Jwts.builder()
                  .setSubject("Joe")
                  .signWith(SignatureAlgorithm.HS512, secretKey)
                  .compact();


Claims claims = Jwts.parser().setSigningKey(secretKey)
                        .parseClaimsJws(compactJws).getBody();


标签: java jwt