Need a Better Error Message when Key Length Does Not Match Algorithm

Issue #195 resolved
m created an issue

If the DirectEncrypter is used with a keylength that does not match the algorithm given, the message is very confusing. For example, when a 32-byte key (256-bit) key is used with A128GCM, you get this exception:

com.nimbusds.jose.JOSEException: The "A128GCM" encryption method is not supported by the JWE encrypter: Supported methods: [A256GCM, A128CBC-HS256, A128CBC+HS256]

The error made me think I didn't have the correct crypto provider installed, when in fact it's just a mismatch between the provided key and the expected key.

Near minimal Scala example:

import com.nimbusds.jose._
import com.nimbusds.jose.crypto._

class Test {
  private val key = {
    val random = new java.security.SecureRandom()
    val sharedSecret = new Array[Byte](32)
    random.nextBytes(sharedSecret)
    sharedSecret
  }

    val jwe = new JWEObject(new JWEHeader(JWEAlgorithm.DIR, EncryptionMethod.A128GCM), new Payload("Hello"))
    jwe.encrypt(new DirectEncrypter(key))
    jwe.serialize()
}

The last line (jwe.serialize) will throw the error above.

Comments (4)

  1. Vladimir Dzhuvinov

    Added hint to error message that key length may be inappropriate. The enc checking is done inside the JWEObject and not by the DirectEncrypter, so at present it's not possible to output the supported key lengths for a configured DirectEncrypter.

    Also updated the JavaDocs to list the required key lengths for each JWE enc.

    Commit 67561bd

  2. Log in to comment