Example: JWE w/ AES encryption, RSA alg

Issue #189 resolved
Former user created an issue

I can't figure out how to use the library to encrypt content using AES, while using RSA to protect the content encryption key (CEK). The only complete JWE example shows Direct encryption only (http://connect2id.com/products/nimbus-jose-jwt/examples/jwe-with-shared-key). Can you provide some direction or point me to a sample? Thanks so much.

Comments (10)

  1. m

    Appreciate the help, but how do I apply encryption to a JWE object? Is there an equivalent to EncryptedJWT? I tried subclasses of JWEEncrypter but they only encrypt the plaintext, they don't touch the content key at all.

  2. m

    Cool, thanks for your help. I found that jose4j made it easier to construct the object I wanted (in particular, it has utilities for generating random bytes to make an IV, and it creates the intermediate AES key when constructing a JWE with RSA + AES encryption).

    Feel free to close this issue.

  3. Connect2id OSS

    You're welcome.

    Jose4j is another fine library and is also JOSE compliant.

    Our approach is to hide IV and AES key gen (handled by package private utils), so users can't mess these up by accident. You can set dedicated JCA providers for each crypto op though.

  4. m

    I didn't realize how simple you'd made this. I actually like it quite a bit. The docs you added will help a lot, but the examples should also be updated. Here's a minimum scala program for doing RSA/AES encryption:

    // Uses  '"org.bitbucket.b_c" % "jose4j" % "0.5.1"' 
    // and '"com.nimbusds" % "nimbus-jose-jwt" % "4.23"'
    
    object Nimbus extends App {
      import java.security.KeyPairGenerator
      import java.security.interfaces.RSAPublicKey
    
      import com.nimbusds.jose._
      import com.nimbusds.jose.crypto.RSAEncrypter
      import org.jose4j.jwe.JsonWebEncryption
    
      val gen = KeyPairGenerator.getInstance("RSA")
      gen.initialize(3072)
      val keyPair = gen.generateKeyPair()
      val jwe = new JWEObject(
        new JWEHeader(JWEAlgorithm.RSA1_5, EncryptionMethod.A256GCM),
        new Payload("Hello, world!")
      )
      jwe.encrypt(new RSAEncrypter(keyPair.getPublic.asInstanceOf[RSAPublicKey]))
    
      val str: String = jwe.serialize()
      println(s"JWE: ${str}")
    
      // Decrypt with jose4j
      val jwe2 = new JsonWebEncryption()
      jwe2.setCompactSerialization(str)
      jwe2.setKey(keyPair.getPrivate)
      println(s"Message: ${jwe2.getPlaintextString}")
    }
    
  5. Log in to comment