Search code examples
jsonjwtjwe

Is there any standard order for nesting JWS and JWE tokens?


I need to pass JSON-encoded signed (and sometimes additionally encrypted) objects between multiple instances of my software. The obvious choice here is JWT.

Yet, JWT allows apparently to both sign and encrypt a token (JWS and JWE) or nest JWS into a JWE (nested JWE).

While both approaches seem reasonable for me, is there a "standard" way of doing this? I haven't found any specifics on this.


Solution

  • Short answer

    When both signing and encryption are necessary, you should first sign the message and then encrypt the result. That is, nesting a JWS into a JWE is a valid approach.

    Long answer

    JSON Web Token (JWT) is an open standard that defines a compact and self-contained way for securely transmitting information between parties as a JSON object. JWT is a generic name for the following types of token:

    • JSON Web Signature (JWS): The payload is encoded and signed so the integrity of the claims can be verified.

    • JSON Web Encryption (JWE): They payload is encrypted so the claims are hidden from other parties.

    JWT, JWS and JWE
    The image was extracted from this page.

    JWT allows apparently to both sign and encrypt a token (JWS and JWE) or nest JWS into a JWE (nested JWE).

    While both approaches seem reasonable for me, is there a "standard" way of doing this? I haven't found any specifics on this.

    The concept of nested JWT is defined in the RFC 7519:

    A JWT in which nested signing and/or encryption are employed. In Nested JWTs, a JWT is used as the payload or plaintext value of an enclosing JWS or JWE structure, respectively.

    Regarding the order of the operations, it's advisable to first sign the message and then encrypt the result, as mentioned in the same document:

    11.2. Signing and Encryption Order

    While syntactically the signing and encryption operations for Nested JWTs may be applied in any order, if both signing and encryption are necessary, normally producers should sign the message and then encrypt the result (thus encrypting the signature). This prevents attacks in which the signature is stripped, leaving just an encrypted message, as well as providing privacy for the signer. Furthermore, signatures over encrypted text are not considered valid in many jurisdictions.