2016-09-21 241 views
1

我从OAuth服务器接收jwt(访问令牌)。 OAuth服务器已经为我提供了秘密密钥,公钥和自签名CA证书。验证java中的jwt:无法为RSA签名指定密钥字节

我想编写一个代码,当我收到一个jwt时,我可以验证它并检查这个服务器是否发送给我。我使用下面的代码来验证我在java中的jwt。

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(); 

我得到的错误:Key bytes cannot be specified for RSA signatures. Please specify a PublicKey or PrivateKey instance.

任何帮助表示赞赏。

回答

-1

你有秘密密钥使用RSA像

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

使用相同的秘密密钥密钥生成JWT字符串,并使用相同的私有密钥像

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(); 
+0

解密它来创建你不需要再次创建关键。您是否尝试使用自签名CA证书密钥?如果他们给你有效的密钥,它应该工作。在你的代码中,你尝试使用“秘密”,它不是一个有效的RSA密钥。那为什么你会得到错误。 –

+1

我尝试了你的建议:Claims claims = Jwts.parser()。setSigningKey(self_signed_CA_Certificate) .parseClaimsJws(jwt).getBody();但仍然得到相同的错误。难道我应该给编码?例如......类似于使用DatatypeConverter.parseBase64Binary? – Pegah

+0

self_signed_CA_Certificate是字符串还是密钥对象?如果它的id字符串,那么你可以通过DatatypeConverter.parseBase64Binary –