Search code examples
javajsonencryptionjwtjose4j

Why does my Jose4j JSON Web Key cause this InvalidKeyException?


I am using Jose4j to perform the encryption of a JSON Web Token in Java.

I create a key as a String in JSON format to pass to the JsonWebKey.Factory.newJwk method, thus:

    String jwkJson = "{\"kty\":\"oct\",\"k\":\"5uP3r53cR37k3yPW\"}";

I pass it to the factory and get a JsonWebKey (jwk) back. Then pass the key (from the jwk.getKey() method) in to the JsonWebEncryption's setKey() method. I set the AlgorithmHeaderValue and the EncryptionMethodHeaderParameter...

Then, when I call jwe.getCompactSerialization() it throws the following exception

    org.jose4j.lang.InvalidKeyException: 
    Invalid key for JWE A128KW, expected a 128 bit key but a 96 bit key was provided.

I passed in 16 bytes, so why does this evaluate to 96 bits insted of 128??


Solution

  • You need to base64 encode the key string before adding it to the JSON object jwkJson.

    E.G.

        String pass = "5uP3r53cR37k3yPW";
        String jwkJson = "{\"kty\":\"oct\",\"k\":\""+ Base64Url.encodeUtf8ByteRepresentation(pass) +"\"}";
    

    In the factory method of JsonWebKey, after it has retrieved the key (k) value from the JSON object, it base64 decodes it. This has the effect (if you have not encoded it first) of reducing the number of characters that the bit pattern represents by 3.

    As to why this occurs, I am a little confused. I would assume that if you took a binary string that describes a string of characters using an 8 bit representation (UTF-8, the native charset in Java), that re-interpreting that binary string as characters using a 6 bit representation (base64), would yield a longer string!