2016-09-21 240 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 –