How to resolve BadPadding exception while RSA Signing?

583 views Asked by At

I am trying to create a signed JWT , but when I try to sign he JWT I am getting the following exception,

Caused by: javax.crypto.BadPaddingException: RSA private key operation failed
        at sun.security.rsa.RSACore.crtCrypt(RSACore.java:201)
        at sun.security.rsa.RSACore.rsa(RSACore.java:122)
        at sun.security.rsa.RSASignature.engineSign(RSASignature.java:192)
        ... 74 more

I have a two JWK which use RS256 alg to sign the JWT. Both are of bit size 2048, but I am able to sign the JWT successfully using one among them, but not with the other.(Cant share the JWK)

I have compared both the JWK and all the required key in the JWK JSON are same but only their modulus and exponent differ.

I am unable to understand what is causing the issue.

You can replicate the issue using the fiollowing code:

KeyPairGenerator gen= KeyPairGenerator.getInstance("RSA");
        gen.initialize(2048);

        JWK sigJWK = new RSAKey.Builder((RSAPublicKey)gen.generateKeyPair().getPublic())
                .privateKey((RSAPrivateKey)gen.generateKeyPair().getPrivate())
                .keyUse(KeyUse.SIGNATURE)
                .keyID("s1")
                .algorithm(JWSAlgorithm.RS256)
                .build();

        Map<String, Object> jwkParamMap = JsonUtil.parseJson(sigJWK.toString());
        PrivateKey sigKey= new RsaJsonWebKey(jwkParamMap).getRsaPrivateKey();
        String tokenEndpoint = request.getAttribute("scheme") + "://" + request.getAttribute("ip") +
                request.getAttribute("tokenurl");



        Random randomInt=new Random();
        JWTClaimsSet claims = new JWTClaimsSet.Builder()
        .issuer(clientID)
        .subject(clientID)
        .audience(tokenEndpoint)
        .jwtID("ItsmejwtID"+randomInt.nextInt())
        .expirationTime(new Date(new Date().getTime()+ 120* 1000))
        .build();

        JWSSigner signer = new RSASSASigner(sigKey);
        SignedJWT signedJWT = new SignedJWT(new JWSHeader(JWSAlgorithm.RS256), claims);
        signedJWT.sign(signer);

        return signedJWT.serialize(); 
0

There are 0 answers