sun.security.mscapi.RSAPrivateKey cannot be cast to java.security.interfaces.RSAPrivateKey
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?
Comments (4)
-
repo owner -
repo owner also note that JWT requires a key of size 2048 bits or larger for RSA
-
Hi,
Yes this worked with only size
RsaJwkGenerator.generateJwk(keySize);
Thank you for the quick reply.
-
repo owner - changed status to invalid
not a defect
- Log in to comment
Try calling RsaJwkGenerator without specifying a provider, i.e.
RsaJwkGenerator.generateJwk(keySize, null, random);
or even justRsaJwkGenerator.generateJwk(keySize);