Welcome to JWCrypto’s documentation!

JWCrypto is an implementation of the Javascript Object Signing and Encryption (JOSE) Web Standards as they are being developed in the JOSE IETF Working Group and related technology.

JWCrypto is Python2 and Python3 compatible and uses the Cryptography package for all the crypto functions.

Contents:

JSON Web Key (JWK)

The jwk Module implements the JSON Web Key standard. A JSON Web Key is represented by a JWK object, related utility classes and functions are availbale in this module too.

Classes

class jwcrypto.jwk.JWK(**kwargs)

Bases: object

JSON Web Key object

This object represent a Key. It must be instantiated by using the standard defined key/value pairs as arguments of the initialization function.

Creates a new JWK object.

The function arguments must be valid parameters as defined in the ‘IANA JSON Web Key Set Parameters registry’ and specified in the JWKParamsRegistry variable. The ‘kty’ parameter must always be provided and its value must be a valid one as defined by the ‘IANA JSON Web Key Types registry’ and specified in the JWKTypesRegistry variable. The valid key parameters per key type are defined in the JWKValuesregistry variable.

To generate a new random key call the class method generate() with the appropriate ‘kty’ parameter, and other parameters as needed (key size, public exponents, curve types, etc..)

Valid options per type, when generating new keys:
  • oct: size(int)
  • RSA: public_exponent(int), size(int)
  • EC: curve(str) (one of P-256, P-384, P-521)

Deprecated: Alternatively if the ‘generate’ parameter is provided, with a valid key type as value then a new key will be generated according to the defaults or provided key strenght options (type specific).

Raises:
export(private_key=True)

Exports the key in the standard JSON format. Exports the key regardless of type, if private_key is False and the key is_symmetric an exceptionis raised.

Parameters:private_key(bool) – Whether to export the private key. Defaults to True.
export_private()

Export the private key in the standard JSON format. It fails for a JWK that has only a public key or is symmetric.

export_public()

Exports the public key in the standard JSON format. It fails if one is not available like when this function is called on a symmetric key.

export_to_pem(private_key=False, password=False)

Exports keys to a data buffer suitable to be stored as a PEM file. Either the public or the private key can be exported to a PEM file. For private keys the PKCS#8 format is used. If a password is provided the best encryption method available as determined by the cryptography module is used to wrap the key.

Parameters:
  • private_key – Whether the private key should be exported. Defaults to False which means the public key is exported by default.
  • password(bytes) – A password for wrapping the private key. Defaults to False which will cause the operation to fail. To avoid encryption the user must explicitly pass None, otherwise the user needs to provide a password in a bytes buffer.
classmethod from_pem(data, password=None)
Creates a key from PKCS#8 formatted data loaded from a PEM file.
See the function import_from_pem for details.
Parameters:
  • data(bytes) – The data contained in a PEM file.
  • password(bytes) – An optional password to unwrap the key.
get_curve(arg)

Gets the Elliptic Curve associated with the key.

Parameters:

arg – an optional curve name

Raises:
get_op_key(operation=None, arg=None)

Get the key object associated to the requested opration. For example the public RSA key for the ‘verify’ operation or the private EC key for the ‘decrypt’ operation.

Parameters:
  • operation – The requested operation. The valid set of operations is availble in the JWKOperationsRegistry registry.
  • arg – an optional, context specific, argument For example a curve name.
Raises:
import_from_pem(data, password=None)

Imports a key from data loaded from a PEM file. The key may be encrypted with a password. Private keys (PKCS#8 format), public keys, and X509 certificate’s public keys can be imported with this interface.

Parameters:
  • data(bytes) – The data contained in a PEM file.
  • password(bytes) – An optional password to unwrap the key.
thumbprint(hashalg=<cryptography.hazmat.primitives.hashes.SHA256 object>)

Returns the key thumbprint as specified by RFC 7638.

Parameters:hashalg – A hash function (defaults to SHA256)
has_private

Whether this JWK has an asymmetric key Private key.

has_public

Whether this JWK has an asymmetric Public key.

is_symmetric

Whether this JWK is a symmetric key.

key_curve

The Curve Name.

key_id

The Key ID. Provided by the kid parameter if present, otherwise returns None.

key_type

The Key type

class jwcrypto.jwk.JWKSet(*args, **kwargs)

Bases: dict

A set of JWK objects.

Inherits from the standard ‘dict’ bultin type. Creates a special key ‘keys’ that is of a type derived from ‘set’ The ‘keys’ attribute accepts only jwcrypto.jwk.JWK elements.

export(private_keys=True)

Exports a RFC 7517 keyset using the standard JSON format

Parameters:private_key(bool) – Whether to export private keys. Defaults to True.
classmethod from_json(keyset)

Creates a RFC 7517 keyset from the standard JSON format.

Parameters:keyset – The RFC 7517 representation of a JOSE Keyset.
get_key(kid)

Gets a key from the set. :param kid: the ‘kid’ key identifier.

import_keyset(keyset)

Imports a RFC 7517 keyset using the standard JSON format.

Parameters:keyset – The RFC 7517 representation of a JOSE Keyset.

Exceptions

class jwcrypto.jwk.InvalidJWKType(value=None)

Bases: exceptions.Exception

Invalid JWK Type Exception.

This exception is raised when an invalid parameter type is used.

class jwcrypto.jwk.InvalidJWKValue

Bases: exceptions.Exception

Invalid JWK Value Exception.

This exception is raised when an invalid/unknown value is used in the context of an operation that requires specific values to be used based on the key type or other constraints.

class jwcrypto.jwk.InvalidJWKOperation(operation, values)

Bases: exceptions.Exception

Invalid JWK Operation Exception.

This exception is raised when an invalid key operation is requested, based on the key type and declared usage constraints.

class jwcrypto.jwk.InvalidJWKUsage(use, value)

Bases: exceptions.Exception

Invalid JWK usage Exception.

This exception is raised when an invalid key usage is requested, based on the key type and declared usage constraints.

Registries

jwcrypto.jwk.JWKTypesRegistry

Registry of valid Key Types

jwcrypto.jwk.JWKValuesRegistry

Registry of valid key values

jwcrypto.jwk.JWKParamsRegistry

Regstry of valid key parameters

jwcrypto.jwk.JWKEllipticCurveRegistry

Registry of allowed Elliptic Curves

jwcrypto.jwk.JWKUseRegistry

Registry of allowed uses

jwcrypto.jwk.JWKOperationsRegistry

Registry of allowed operations

Examples

Create a 256bit symmetric key::
>>> from jwcrypto import jwk
>>> key = jwk.JWK.generate(kty='oct', size=256)
Export the key with::
>>> key.export()
'{"k":"X6TBlwY2so8EwKZ2TFXM7XHSgWBKQJhcspzYydp5Y-o","kty":"oct"}'
Create a 2048bit RSA keypair::
>>> jwk.JWK.generate(kty='RSA', size=2048)
Create a P-256 EC keypair and export the public key::
>>> key = jwk.JWK.generate(kty='EC', crv='P-256')
>>> key.export(private_key=False)
'{"y":"VYlYwBfOTIICojCPfdUjnmkpN-g-lzZKxzjAoFmDRm8",
  "x":"3mdE0rODWRju6qqU01Kw5oPYdNxBOMisFvJFH1vEu9Q",
  "crv":"P-256","kty":"EC"}'
Import a P-256 Public Key::
>>> expkey = {"y":"VYlYwBfOTIICojCPfdUjnmkpN-g-lzZKxzjAoFmDRm8",
              "x":"3mdE0rODWRju6qqU01Kw5oPYdNxBOMisFvJFH1vEu9Q",
              "crv":"P-256","kty":"EC"}
>>> key = jwk.JWK(**expkey)
Import a Key from a PEM file::
>>> with open("public.pem", "rb") as pemfile:
>>>     key = jwk.JWK.from_pem(pemfile.read())

JSON Web Signature (JWS)

The jws Module implements the JSON Web Signature standard. A JSON Web Signature is represented by a JWS object, related utility classes and functions are available in this module too.

Classes

class jwcrypto.jws.JWS(payload=None)

Bases: object

JSON Web Signature object

This object represent a JWS token.

Creates a JWS object.

Parameters:payload(bytes) – An arbitrary value (optional).
add_signature(key, alg=None, protected=None, header=None)

Adds a new signature to the object.

Parameters:
  • key – A (jwcrypto.jwk.JWK) key of appropriate for the “alg” provided.
  • alg – An optional algorithm name. If already provided as an element of the protected or unprotected header it can be safely omitted.
  • potected – The Protected Header (optional)
  • header – The Unprotected Header (optional)
Raises:
  • InvalidJWSObject – if no payload has been set on the object.
  • ValueError – if the key is not a JWK object.
  • ValueError – if the algorithm is missing or is not provided by one of the headers.
  • InvalidJWAAlgorithm – if the algorithm is not valid, is unknown or otherwise not yet implemented.
deserialize(raw_jws, key=None, alg=None)

Deserialize a JWS token.

NOTE: Destroys any current status and tries to import the raw JWS provided.

Parameters:
  • raw_jws – a ‘raw’ JWS token (JSON Encoded or Compact notation) string.
  • key – A (jwcrypto.jwk.JWK) verification key (optional). If a key is provided a verification step will be attempted after the object is successfully deserialized.
  • alg – The signing algorithm (optional). usually the algorithm is known as it is provided with the JOSE Headers of the token.
Raises:
serialize(compact=False)

Serializes the object into a JWS token.

Parameters:

compact(boolean) – if True generates the compact representation, otherwise generates a standard JSON format.

Raises:
  • InvalidJWSOperation – if the object cannot serialized with the compact representation and compat is True.
  • InvalidJWSSignature – if no signature has been added to the object, or no valid signature can be found.
verify(key, alg=None)

Verifies a JWS token.

Parameters:
  • key – The (jwcrypto.jwk.JWK) verification key.
  • alg – The signing algorithm (optional). usually the algorithm is known as it is provided with the JOSE Headers of the token.
Raises:

InvalidJWSSignature – if the verification fails.

allowed_algs

Allowed algorithms.

The list of allowed algorithms. Can be changed by setting a list of algorithm names.

class jwcrypto.jws.JWSCore(alg, key, header, payload, algs=None)

Bases: object

The inner JWS Core object.

This object SHOULD NOT be used directly, the JWS object should be used instead as JWS perform necessary checks on the validity of the object and requested operations.

Core JWS token handling.

Parameters:
  • alg – The algorithm used to produce the signature. See RFC 7518
  • key – A (jwcrypto.jwk.JWK) key of appropriate type for the “alg” provided in the ‘protected’ json string.
  • header – A JSON string representing the protected header.
  • payload(bytes) – An arbitrary value
  • algs – An optional list of allowed algorithms
Raises:
  • ValueError – if the key is not a JWK object
  • InvalidJWAAlgorithm – if the algorithm is not valid, is unknown or otherwise not yet implemented.
sign()

Generates a signature

verify(signature)

Verifies a signature

Raises:InvalidJWSSignature – if the verification fails.

Variables

jwcrypto.jws.default_allowed_algs = ['HS256', 'HS384', 'HS512', 'RS256', 'RS384', 'RS512', 'ES256', 'ES384', 'ES512', 'PS256', 'PS384', 'PS512']

Default allowed algorithms

Exceptions

class jwcrypto.jws.InvalidJWSSignature(message=None, exception=None)

Bases: exceptions.Exception

Invalid JWS Signature.

This exception is raised when a signature cannot be validated.

class jwcrypto.jws.InvalidJWSObject(message=None, exception=None)

Bases: exceptions.Exception

Invalid JWS Object.

This exception is raised when the JWS Object is invalid and/or improperly formatted.

class jwcrypto.jws.InvalidJWSOperation(message=None, exception=None)

Bases: exceptions.Exception

Invalid JWS Object.

This exception is raised when a requested operation cannot be execute due to unsatisfied conditions.

Registries

jwcrypto.jws.JWSHeaderRegistry

Registry of valid header parameters

Examples

Sign a JWS token::
>>> from jwcrypto import jwk, jws
>>> from jwcrypto.common import json_encode
>>> key = jwk.JWK.generate(kty='oct', size=256)
>>> payload = "My Integrity protected message"
>>> jwstoken = jws.JWS(payload.encode('utf-8'))
>>> jwstoken.add_signature(key, None,
                           json_encode({"alg": "HS256"}),
                           json_encode({"kid": key.thumbprint()}))
>>> sig = jwstoken.serialize()
Verify a JWS token::
>>> jwstoken = jws.JWS()
>>> jwstoken.deserialize(sig)
>>> jwstoken.verify(key)
>>> payload = jwstoken.payload

JSON Web Encryption (JWE)

The jwe Module implements the JSON Web Encryption standard. A JSON Web Encryption is represented by a JWE object, related utility classes and functions are availbale in this module too.

Classes

class jwcrypto.jwe.JWE(plaintext=None, protected=None, unprotected=None, aad=None, algs=None, recipient=None, header=None)

Bases: object

JSON Web Encryption object

This object represent a JWE token.

Creates a JWE token.

Parameters:
  • plaintext(bytes) – An arbitrary plaintext to be encrypted.
  • protected – A JSON string with the protected header.
  • unprotected – A JSON string with the shared unprotected header.
  • aad(bytes) – Arbitrary additional authenticated data
  • algs – An optional list of allowed algorithms
  • recipient – An optional, default recipient key
  • header – An optional header for the default recipient
add_recipient(key, header=None)

Encrypt the plaintext with the given key.

Parameters:
  • key – A JWK key or password of appropriate type for the ‘alg’ provided in the JOSE Headers.
  • header – A JSON string representing the per-recipient header.
Raises:
  • ValueError – if the plaintext is missing or not of type bytes.
  • ValueError – if the compression type is unknown.
  • InvalidJWAAlgorithm – if the ‘alg’ provided in the JOSE headers is missing or unknown, or otherwise not implemented.
decrypt(key)

Decrypt a JWE token.

Parameters:
Raises:
deserialize(raw_jwe, key=None)

Deserialize a JWE token.

NOTE: Destroys any current status and tries to import the raw JWE provided.

Parameters:
  • raw_jwe – a ‘raw’ JWE token (JSON Encoded or Compact notation) string.
  • key – A (jwcrypto.jwk.JWK) decryption key or a password string (optional). If a key is provided a decryption step will be attempted after the object is successfully deserialized.
Raises:
serialize(compact=False)

Serializes the object into a JWE token.

Parameters:

compact(boolean) – if True generates the compact representation, otherwise generates a standard JSON format.

Raises:
allowed_algs

Allowed algorithms.

The list of allowed algorithms. Can be changed by setting a list of algorithm names.

Variables

jwcrypto.jwe.default_allowed_algs = ['RSA1_5', 'RSA-OAEP', 'RSA-OAEP-256', 'A128KW', 'A192KW', 'A256KW', 'dir', 'ECDH-ES', 'ECDH-ES+A128KW', 'ECDH-ES+A192KW', 'ECDH-ES+A256KW', 'A128GCMKW', 'A192GCMKW', 'A256GCMKW', 'PBES2-HS256+A128KW', 'PBES2-HS384+A192KW', 'PBES2-HS512+A256KW', 'A128CBC-HS256', 'A192CBC-HS384', 'A256CBC-HS512', 'A128GCM', 'A192GCM', 'A256GCM']

Default allowed algorithms

Exceptions

class jwcrypto.jwe.InvalidJWEOperation(message=None, exception=None)

Bases: jwcrypto.common.JWException

Invalid JWS Object.

This exception is raised when a requested operation cannot be execute due to unsatisfied conditions.

class jwcrypto.jwe.InvalidJWEData(message=None, exception=None)

Bases: exceptions.Exception

Invalid JWE Object.

This exception is raised when the JWE Object is invalid and/or improperly formatted.

class jwcrypto.jwe.InvalidJWEKeyType(expected, obtained)

Bases: jwcrypto.common.JWException

Invalid JWE Key Type.

This exception is raised when the provided JWK Key does not match the type required by the sepcified algorithm.

class jwcrypto.jwe.InvalidJWEKeyLength(expected, obtained)

Bases: jwcrypto.common.JWException

Invalid JWE Key Length.

This exception is raised when the provided JWK Key does not match the lenght required by the sepcified algorithm.

class jwcrypto.jwe.InvalidCEKeyLength(expected, obtained)

Bases: jwcrypto.common.JWException

Invalid CEK Key Length.

This exception is raised when a Content Encryption Key does not match the required lenght.

Registries

jwcrypto.jwe.JWEHeaderRegistry

Registry of valid header parameters

Examples

Encrypt a JWE token::
>>> from jwcrypto import jwk, jwe
>>> from jwcrypto.common import json_encode
>>> key = jwk.JWK.generate(kty='oct', size=256)
>>> payload = "My Encrypted message"
>>> jwetoken = jwe.JWE(payload.encode('utf-8'),
                       json_encode({"alg": "A256KW",
                                    "enc": "A256CBC-HS512"}))
>>> jwetoken.add_recipient(key)
>>> enc = jwetoken.serialize()
Decrypt a JWE token::
>>> jwetoken = jwe.JWE()
>>> jwetoken.deserialize(enc)
>>> jwetoken.decrypt(key)
>>> payload = jwetoken.payload

JSON Web Token (JWT)

The jwt Module implements the JSON Web Token standard. A JSON Web Token is represented by a JWT object, related utility classes and functions are availbale in this module too.

Classes

class jwcrypto.jwt.JWT(header=None, claims=None, jwt=None, key=None, algs=None, default_claims=None, check_claims=None)

Bases: object

JSON Web token object

This object represent a generic token.

Creates a JWT object.

Parameters:
  • header – A dict or a JSON string with the JWT Header data.
  • claims – A dict or a string withthe JWT Claims data.
  • jwt – a ‘raw’ JWT token
  • key – A (jwcrypto.jwk.JWK) key to deserialize the token. A (jwcrypt.jwk.JWKSet) can also be used.
  • algs – An optional list of allowed algorithms
  • default_claims – An optional dict with default values for registred claims. A None value for NumericDate type claims will cause generation according to system time. Only the values fro RFC 7519 - 4.1 are evaluated.
  • check_claims – An optional dict of claims that must be present in the token, if the value is not None the claim must match exactly.

Note: either the header,claims or jwt,key parameters should be provided as a deserialization operation (which occurs if the jwt is provided will wipe any header os claim provided by setting those obtained from the deserialization of the jwt token.

Note: if check_claims is not provided the ‘exp’ and ‘nbf’ claims are checked if they are set on the token but not enforced if not set. Any other RFC 7519 registered claims are checked only for format conformance.

deserialize(jwt, key=None)

Deserialize a JWT token.

NOTE: Destroys any current status and tries to import the raw token provided.

Parameters:
  • jwt – a ‘raw’ JWT token.
  • key – A (jwcrypto.jwk.JWK) verification or decryption key, or a (jwcrypt.jwk.JWKSet) that contains a key indexed by the ‘kid’ header.
make_encrypted_token(key)

Encrypts the payload.

Creates a JWE token with the header as the JWE protected header and the claims as the plaintext. See (jwcrypto.jwe.JWE) for details on the exceptions that may be reaised.

Parameters:key – A (jwcrypto.jwk.JWK) key.
make_signed_token(key)

Signs the payload.

Creates a JWS token with the header as the JWS protected header and the claims as the payload. See (jwcrypto.jws.JWS) for details on the exceptions that may be reaised.

Parameters:key – A (jwcrypto.jwk.JWK) key.
serialize(compact=True)

Serializes the object into a JWS token.

Parameters:compact(boolean) – must be True.

Note: the compact parameter is provided for general compatibility with the serialize() functions of jwcrypto.jws.JWS and jwcrypto.jwe.JWE so that these objects can all be used interchangeably. However the only valid JWT representtion is the compact representation.

Examples

Create a symmetric key::
>>> from jwcrypto import jwt, jwk
>>> key = jwk.JWK(generate='oct', size=256)
>>> key.export()
'{"k":"Wal4ZHCBsml0Al_Y8faoNTKsXCkw8eefKXYFuwTBOpA","kty":"oct"}'
Create a signed token with the generated key::
>>> Token = jwt.JWT(header={"alg": "HS256"},
                    claims={"info": "I'm a signed token"})
>>> Token.make_signed_token(key)
>>> Token.serialize()
u'eyJhbGciOiJIUzI1NiJ9.eyJpbmZvIjoiSSdtIGEgc2lnbmVkIHRva2VuIn0.rjnRMAKcaRamEHnENhg0_Fqv7Obo-30U4bcI_v-nfEM'
Further encrypt the token with the same key::
>>> Etoken = jwt.JWT(header={"alg": "A256KW", "enc": "A256CBC-HS512"},
                     claims=Token.serialize())
>>> Etoken.make_encrypted_token(key)
>>> Etoken.serialize()
u'eyJhbGciOiJBMjU2S1ciLCJlbmMiOiJBMjU2Q0JDLUhTNTEyIn0.ST5RmjqDLj696xo7YFTFuKUhcd3naCrm6yMjBM3cqWiFD6U8j2JIsbclsF7ryNg8Ktmt1kQJRKavV6DaTl1T840tP3sIs1qz.wSxVhZH5GyzbJnPBAUMdzQ.6uiVYwrRBzAm7Uge9rEUjExPWGbgerF177A7tMuQurJAqBhgk3_5vee5DRH84kHSapFOxcEuDdMBEQLI7V2E0F57-d01TFStHzwtgtSmeZRQ6JSIL5XlgJouwHfSxn9Z_TGl5xxq4TksORHED1vnRA.5jPyPWanJVqlOohApEbHmxi3JHp1MXbmvQe2_dVd8FI'
Now decrypt and verify::
>>> from jwcrypto import jwt, jwk
>>> k = {"k": "Wal4ZHCBsml0Al_Y8faoNTKsXCkw8eefKXYFuwTBOpA", "kty": "oct"}
>>> key = jwk.JWK(**k)
>>> e = u'eyJhbGciOiJBMjU2S1ciLCJlbmMiOiJBMjU2Q0JDLUhTNTEyIn0.ST5RmjqDLj696xo7YFTFuKUhcd3naCrm6yMjBM3cqWiFD6U8j2JIsbclsF7ryNg8Ktmt1kQJRKavV6DaTl1T840tP3sIs1qz.wSxVhZH5GyzbJnPBAUMdzQ.6uiVYwrRBzAm7Uge9rEUjExPWGbgerF177A7tMuQurJAqBhgk3_5vee5DRH84kHSapFOxcEuDdMBEQLI7V2E0F57-d01TFStHzwtgtSmeZRQ6JSIL5XlgJouwHfSxn9Z_TGl5xxq4TksORHED1vnRA.5jPyPWanJVqlOohApEbHmxi3JHp1MXbmvQe2_dVd8FI'
>>> ET = jwt.JWT(key=key, jwt=e)
>>> ST = jwt.JWT(key=key, jwt=ET.claims)
>>> ST.claims
u'{"info":"I\'m a signed token"}'

Indices and tables