2017-07-11 230 views
0

我想利用何塞(https://bitbucket.org/b_c/jose4j/wiki/Home)生成一个签名JsonWebToken。我遇到了一个问题,创造,我需要在令牌的签名使用RsaKeyPairs。何塞RSAPrivateKey和JsonWebKey数据库存储

这是我用来生成公钥/私钥的代码,我需要将此转换为字符串,所以我可以将它们存储在数据库中,然后检索它们。

WebKeyManager wkm = null; 
    Object obj; 
    EncryptionKey encKey = null; 
    RsaJsonWebKey rsaJsonWebKey = null; 

    try 
    { 
     wkm = new WebKeyManager(); 
     int keySize = 512; 

     // Initialize KeyPairGenerator. 

     SecureRandom random = SecureRandom.getInstanceStrong(); //cryptographically strong random number generator 

     // Generate an RSA key pair, which will be used for signing and verification of the JWT, wrapped in a JWK    
     rsaJsonWebKey = RsaJwkGenerator.generateJwk(keySize, random.getProvider().getName(),random); 

     // Give the JWK a Key ID (kid), which is just the polite thing to do 
     rsaJsonWebKey.setKeyId(""+System.currentTimeMillis()); 

     String json = rsaJsonWebKey.toJson(OutputControlLevel.INCLUDE_PRIVATE); 

} 
catch (Exception e) 
{ 
    e.printStackTrace(); 
} 

我遇到的问题是,当我做rsaJsonWebKey.toJson(OutputControlLevel.INCLUDE_PRIVATE)

我得到这个错误:

java.lang.ClassCastException: sun.security.mscapi.RSAPrivateKey cannot be cast to java.security.interfaces.RSAPrivateKey 
    at org.jose4j.jwk.RsaJsonWebKey.getRsaPrivateKey(RsaJsonWebKey.java:123) 
    at org.jose4j.jwk.RsaJsonWebKey.fillPrivateTypeSpecificParams(RsaJsonWebKey.java:135) 
    at org.jose4j.jwk.PublicJsonWebKey.fillTypeSpecificParams(PublicJsonWebKey.java:122) 
    at org.jose4j.jwk.JsonWebKey.toParams(JsonWebKey.java:166) 
    at org.jose4j.jwk.JsonWebKey.toJson(JsonWebKey.java:178) 

我试着调试代码何塞和错误发生在PublicJsonWebKey类的这一行:

protected void fillPrivateTypeSpecificParams(Map<String,Object> params) 
{ 
    RSAPrivateKey rsaPrivateKey = getRsaPrivateKey(); 

rsaPrivateKey is java.security.inte rfaces.RSAPrivateKey而getRsaPrivateKey()返回org.jose4j.jwk.RsaJsonWebKey

我在做什么错?

我的要求是生成KeyPair,将它们存储在数据库中的varchar类型字段或类似的东西,然后在需要时,我可以从数据库检索字符串,将其转换回私钥/公钥并使用它们签名令牌?

回答

0

经过一番研究,我发现,如果我创建使用此构造

rsaJsonWebKey = RsaJwkGenerator.generateJwk(keySize); 

的钥匙,然后我得不到的错误。