1

I am trying to generate an encrypted JWT in Android using 'nimbus-jose-jwt' library. But when I call the method 'encrypt()' of library, I get the error 'Cannot resolve symbol 'encrypt', even though the source code of library has the method 'encrypt()' for the object I specified.

This is my code:

 public class EncryptedJWTGenerator {
   
 public EncryptedJWTGenerator() throws NoSuchAlgorithmException, JOSEException {
    }

    JWEAlgorithm alg = JWEAlgorithm.RSA_OAEP_256;
    EncryptionMethod enc = EncryptionMethod.A128CBC_HS256;

    KeyPairGenerator rsaGen = KeyPairGenerator.getInstance("RSA");
    //rsaGen.initialize(2048);
    KeyPair rsaKeyPair = rsaGen.generateKeyPair();
    RSAPublicKey rsaPublicKey = (RSAPublicKey)rsaKeyPair.getPublic();


    // Generate the preset Content Encryption (CEK) key
    KeyGenerator keyGenerator = KeyGenerator.getInstance("AES");

    SecretKey cek = keyGenerator.generateKey();

    // Encrypt the JWE with the RSA public key + specified AES CEK
    JWEObject jweObject = new JWEObject(new JWEHeader(alg, enc), new Payload("Hello, world!"));

    jweObject.encrypt(new RSAEncrypter(rsaPublicKey, cek)); //**ERROR IN THIS LINE**

    String jweString = jweObject.serialize();
    
}

I have been trying to resolve this for hours, but not successful yet. Please suggest a solution.

Sparsh Dutta
  • 2,450
  • 4
  • 27
  • 54
  • Try it after removing the wrong closing bracket in the 3rd line (this typo produces the posted error message on my machine). – Topaco Jul 26 '21 at 11:44
  • However, you must initialize the `KeyGenerator` with `EncryptionMethod.A128CBC_HS256.cekBitLength()` when generating the CEK. – Topaco Jul 26 '21 at 12:01
  • Topaco, sorry for the late reply. Now I am getting: com.nimbusds.jose.JOSEException: too much data for RSA block in the ecrypt() method call line. – Sparsh Dutta Jul 26 '21 at 13:51
  • I cannot reproduce this on my machine with the posted code and the changes I suggested (API28/P). – Topaco Jul 26 '21 at 14:09
  • Sorry man, it's working fine now. I had initialized KeyPairGenerator instead of KeyGenerator. Please post an answer so that I can mark it as correct. – Sparsh Dutta Jul 26 '21 at 14:11
  • Sure, I put my comment as an answer. – Topaco Jul 26 '21 at 18:00

1 Answers1

1

There are two bugs in the code:

  • First, a typo: the closing bracket in the 3rd line must be removed.

  • Secondly, the KeyGenerator must be initialized as follows when generating the CEK:

    keyGenerator.init(EncryptionMethod.A128CBC_HS256.cekBitLength());
    

With these changes the code works on my machine (API28/P).

Topaco
  • 40,594
  • 4
  • 35
  • 62