JWE - nov/json-jwt GitHub Wiki

JSON Web Encryption (JWE)

Encrypting

Call JSON::JWT#encrypt(key, algorithm, encryption_method).

When the given key is a JSON::JWK instance, and it has kid, then generated JSON::JWE instance has the same kid value in its header automatically.

public_key = OpenSSL::PKey::RSA.new <<-PEM
-----BEGIN RSA PUBLIC KEY-----
MIIBCgKCAQEAx9vNhcvSrxjsegZAAo4OEuoZOV/oxINEeWneJYczS80/bQ1J6lSS
 :
-----END RSA PUBLIC KEY-----
PEM

jwe = jwt.encrypt(public_key, :'RSA-OAEP', :A256GCM)

Decrypting

JSON::JWT.decode(jwe_string, key) is for decoding and decrypting compact-seiralized JWE token.

After decryption, JSON::JWE#plain_text will return original input as String.

Usually the plain text is also a JWT/JWS token, so you'll need decode it.

private_key = OpenSSL::PKey::RSA.new <<-PEM
-----BEGIN RSA PRIVATE KEY-----
MIIEpAIBAAKCAQEAzHEJiUJDN59jUomP1pl7r0AGKXJAgR2DjmBTbN4kpvjWqcRR
 :
-----END RSA PRIVATE KEY-----
PEM

jwe = JSON::JWT.decode 'eyJ...', private_key
jwe.plain_text # => 'eyJ..'

jws = JSON::JWT.decode jwe.plain_text, :skip_verification

You can explicitly specify expected enc & alg.
If you didn't specify the alg, this gem automatically detect it from given JWT header and class of given public key / secret instance.

jwe = JSON::JWT.decode 'eyJ...', private_key, :'RSA-OAEP', :A256GCM 

You can also decode without decryption, then decrypt it later.

jwe = JSON::JWT.decode 'eyJ...', :skip_decryption
jwe.plain_text # => nil

jwe.decrypt! private_key
jwe.plain_text # => 'eyJ..'

Serialization

Follow JWT's Serialization section.

jwe = jwt.encrypt(public_key)
jwe.to_s # => "eyJ..."

Supported Algorithms

Key Encryption Algorithms

These values are supported as key encryption algorithms.

  • RSA1_5 (default)
  • RSA-OAEP
  • dir
  • A128KW
  • A256KW

These are not supported.

  • ECDH-ES
  • ECDH-ES+A128KW
  • ECDH-ES+A256KW

For each algorithm details, read [RFC7518] JSON Web Algorithms (JWA).

Content Encryption Algorithms

These values are supported as content encryption algorithms.

  • A128GCM (default)
  • A256GCM
  • A128CBC-HS256
  • A256CBC-HS512

A192CBC-HS384 is not supported.

For each algorithm details, read [RFC7518] JSON Web Algorithms (JWA).

Key Representation

Follow JWS's Key Representation section.