0

I am trying to use Jose (https://bitbucket.org/b_c/jose4j/wiki/Home) to generate a signed JsonWebToken. I am running into a problem creating the RsaKeyPairs that I need to use in the signature of the token.

This is the code I am using to generate the public/private Keys and I need to turn this to String so I can store them in the database and then retrieve them.

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

The Problem I am Encountering is when I do rsaJsonWebKey.toJson(OutputControlLevel.INCLUDE_PRIVATE)

I get this error:

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)

I tried to debug the code in Jose and the error is in PublicJsonWebKey class this line:

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

rsaPrivateKey is java.security.interfaces.RSAPrivateKey while getRsaPrivateKey() returns org.jose4j.jwk.RsaJsonWebKey

What am I doing wrong?

My requirement is to generate KeyPairs, store them in the database in varchar type field or something similar and then whenever needed, I can retrieve the String from the database, convert it back to private/public keys and use them to sign the token?

daoud175
  • 106
  • 1
  • 18

1 Answers1

0

After some research, I found out that if I create the keys using this constructor

 rsaJsonWebKey = RsaJwkGenerator.generateJwk(keySize); 

then I don't get the error.

daoud175
  • 106
  • 1
  • 18