JSON Web Keys for JOSE (Effect's effect/jose/Jwk)::
pair = yield from jwk.generate_key_pair("ES256", kid="k1")
signing = yield from jwk.import_private(pair.private_key, "ES256")
verifying = yield from jwk.import_public(pair.public_key, "ES256")Importing checks a JWK's alg, use and key_ops against the
algorithm and operation it is imported for, refuses private members in a
public JWK and RSA moduli below 2048 bits. Private and secret JWKs travel
as Redacted. thumbprint is RFC 7638's (thumbprint_uri RFC 9278's).
Re-exports#
Values#
| Attribute | Type | Description |
|---|---|---|
ASYMMETRIC_ALGORITHMS | tuple[AsymmetricAlgorithm, ...] = ('RS256', 'RS384', 'RS512', 'PS256', 'PS384', 'PS512', 'ES256', 'ES384', 'ES512', 'EdDSA') | |
ALGORITHMS | tuple[Algorithm, ...] | |
AsymmetricAlgorithmSchema | LiteralsSchema[Literal['RS256', 'RS384', 'RS512', 'PS256', 'PS384', 'PS512', 'ES256', 'ES384', 'ES512', 'EdDSA']] | |
AlgorithmSchema | LiteralsSchema[Literal['HS256', 'HS384', 'HS512', 'RS256', 'RS384', 'RS512', 'PS256', 'PS384', 'PS512', 'ES256', 'ES384', 'ES512', 'EdDSA']] | |
PublicJwkSchema | UnionSchema[RsaPublicJwk | EcPublicJwk | OkpPublicJwk, Mapping[str, object], Never, Never] | |
PrivateJwkSchema | UnionSchema[RsaPrivateJwk | EcPrivateJwk | OkpPrivateJwk, Mapping[str, object], Never, Never] | |
SecretJwkSchema | StructSchema[SecretJwk, Never, Never] |
Types#
| Type | Definition | Description |
|---|---|---|
AsymmetricAlgorithm | type AsymmetricAlgorithm = Literal['RS256', 'RS384', 'RS512', 'PS256', 'PS384', 'PS512', 'ES256', 'ES384', 'ES512', 'EdDSA'] | |
HmacAlgorithm | type HmacAlgorithm = Literal['HS256', 'HS384', 'HS512'] | |
Algorithm | type Algorithm = HmacAlgorithm | AsymmetricAlgorithm | |
SecretAlgorithm | type SecretAlgorithm = HmacAlgorithm | Literal['dir'] | |
PublicJwk | type PublicJwk = RsaPublicJwk | EcPublicJwk | OkpPublicJwk | |
PrivateJwk | type PrivateJwk = RsaPrivateJwk | EcPrivateJwk | OkpPrivateJwk | |
SecretKey | type SecretKey = HmacKey | DirKey | |
SigningKey | type SigningKey = PrivateKey | HmacKey | |
VerificationKey | type VerificationKey = PublicKey | HmacKey | |
ThumbprintInput | type ThumbprintInput = PublicJwk | Redacted[PrivateJwk] | Redacted[SecretJwk] | PublicKey | PrivateKey | SecretKey |
Classes#
Functions#
generate_key_pair#
generate_key_pair(algorithm, *, kid=None, modulus_length=None) -> Effect[KeyPair, JoseError, Signature]A new key pair as JWKs; RSA moduli default to 2048 bits and must be at least that.
| Parameter | Type | Description |
|---|---|---|
algorithm | AsymmetricAlgorithm | |
kid | str | None = None | |
modulus_length | int | None = None |
Returns Effect[KeyPair, JoseError, Signature]
def generate_key_pair(
algorithm: AsymmetricAlgorithm, *, kid: str | None = None, modulus_length: int | None = None
) -> Effect[KeyPair, JoseError, Signature]:
"""A new key pair as JWKs; RSA moduli default to 2048 bits and must be
at least that."""
@gen
def body():
if modulus_length is not None and not (
type(modulus_length) is int and 2048 <= modulus_length <= 2**53 - 1
):
return (
yield from invalid_argument("modulusLength must be an integer of at least 2048")
)
service = yield from Signature()
pair = yield from service.generate_key_pair(
_signature_algorithm(algorithm, modulus_length or 2048)
).map_error(crypto_failure(f"Could not generate a {algorithm} key pair"))
public_jwk = yield from _export_jwk(pair.public_key, algorithm, kid)
private_jwk = yield from _export_jwk(pair.private_key, algorithm, kid)
return KeyPair(cast("PublicJwk", public_jwk), redacted(cast("PrivateJwk", private_jwk)))
return bodygenerate_secret#
generate_secret(algorithm, *, kid=None) -> Effect[Redacted[SecretJwk], Never, SecureRandom]A random secret JWK of the algorithm's key length.
| Parameter | Type | Description |
|---|---|---|
algorithm | SecretAlgorithm | |
kid | str | None = None |
Returns Effect[Redacted[SecretJwk], Never, SecureRandom]
def generate_secret(
algorithm: SecretAlgorithm, *, kid: str | None = None
) -> Effect[Redacted[SecretJwk], Never, SecureRandom]:
"""A random secret JWK of the algorithm's key length."""
def make(data: bytes) -> Redacted[SecretJwk]:
jwk: SecretJwk = {
"kty": "oct",
"k": base64_url_encode(data),
"alg": algorithm,
"use": "enc" if algorithm == "dir" else "sig",
}
if kid is not None:
jwk["kid"] = kid
return redacted(jwk)
return (
SecureRandom()
.flat_map(lambda random: random.random_bytes(_secret_key_length(algorithm)))
.map(make)
)import_public#
import_public(jwk, algorithm) -> Effect[PublicKey, JoseError]A verification key; the JWK must allow verify for sig.
| Parameter | Type | Description |
|---|---|---|
jwk | PublicJwk | |
algorithm | AsymmetricAlgorithm |
Returns Effect[PublicKey, JoseError]
def import_public(jwk: PublicJwk, algorithm: AsymmetricAlgorithm) -> Effect[PublicKey, JoseError]:
"""A verification key; the JWK must allow ``verify`` for ``sig``."""
@gen
def body():
data = cast("Mapping[str, object]", jwk)
if has_private_members(data):
return (yield from invalid_key("A public JWK cannot contain private members"))
yield from _check_metadata(data, algorithm, "sig", ("verify",))
if not _is_public_jwk(jwk):
return (yield from invalid_key("Expected a public JWK with base64url key members"))
key = yield from key_format.decode_public(
key_format.jwk, _signature_algorithm(algorithm), _json_web_key(data)
).map_error(public_key_failure)
yield from _check_modulus(key)
return PublicKey(algorithm, jwk.get("kid"), jwk, key)
return bodyimport_private#
import_private(input, algorithm) -> Effect[PrivateKey, JoseError]A signing key; the JWK must allow sign for sig.
| Parameter | Type | Description |
|---|---|---|
input | Redacted[PrivateJwk] | |
algorithm | AsymmetricAlgorithm |
Returns Effect[PrivateKey, JoseError]
def import_private(
input: Redacted[PrivateJwk], algorithm: AsymmetricAlgorithm
) -> Effect[PrivateKey, JoseError]:
"""A signing key; the JWK must allow ``sign`` for ``sig``."""
@gen
def body():
jwk = reveal(input)
data = cast("Mapping[str, object]", jwk)
yield from _check_metadata(data, algorithm, "sig", ("sign",))
if not _is_private_jwk(jwk):
return (yield from invalid_key("Expected a private JWK with base64url key members"))
key = yield from key_format.decode_private(
key_format.jwk, _signature_algorithm(algorithm), _json_web_key(data)
).map_error(crypto_failure(f"Could not import the private JWK for {algorithm}"))
yield from _check_modulus(key)
return PrivateKey(algorithm, jwk.get("kid"), key)
return bodyimport_spki#
import_spki(input, algorithm, *, kid=None) -> Effect[PublicKey, JoseError]A verification key from SPKI DER bytes or PEM text.
| Parameter | Type | Description |
|---|---|---|
input | bytes | str | |
algorithm | AsymmetricAlgorithm | |
kid | str | None = None |
Returns Effect[PublicKey, JoseError]
def import_spki(
input: bytes | str, algorithm: AsymmetricAlgorithm, *, kid: str | None = None
) -> Effect[PublicKey, JoseError]:
"""A verification key from SPKI DER bytes or PEM text."""
@gen
def body():
decoded = (
key_format.decode_public(
key_format.pem(key_format.spki), _signature_algorithm(algorithm), input
)
if isinstance(input, str)
else key_format.decode_public(key_format.spki, _signature_algorithm(algorithm), input)
)
key = yield from decoded.map_error(public_key_failure)
yield from _check_modulus(key)
jwk = yield from _export_jwk(key, algorithm, kid)
return PublicKey(algorithm, kid, cast("PublicJwk", jwk), key)
return bodyimport_pkcs8#
import_pkcs8(input, algorithm, *, kid=None) -> Effect[PrivateKey, JoseError]A signing key from PKCS#8 DER bytes or PEM text.
| Parameter | Type | Description |
|---|---|---|
input | Redacted[bytes] | Redacted[str] | |
algorithm | AsymmetricAlgorithm | |
kid | str | None = None |
Returns Effect[PrivateKey, JoseError]
def import_pkcs8(
input: Redacted[bytes] | Redacted[str],
algorithm: AsymmetricAlgorithm,
*,
kid: str | None = None,
) -> Effect[PrivateKey, JoseError]:
"""A signing key from PKCS#8 DER bytes or PEM text."""
@gen
def body():
data: bytes | str = reveal(input)
decoded = (
key_format.decode_private(
key_format.pem(key_format.pkcs8), _signature_algorithm(algorithm), data
)
if isinstance(data, str)
else key_format.decode_private(key_format.pkcs8, _signature_algorithm(algorithm), data)
)
key = yield from decoded.map_error(
crypto_failure(f"Could not import the PKCS#8 key for {algorithm}")
)
yield from _check_modulus(key)
return PrivateKey(algorithm, kid, key)
return bodyimport_hmac#
import_hmac(input, algorithm) -> Effect[HmacKey, JoseError]An HS* key (Effect's importSecret for an HMAC algorithm); the
JWK must allow sign and verify for sig.
| Parameter | Type | Description |
|---|---|---|
input | Redacted[SecretJwk] | |
algorithm | HmacAlgorithm |
Returns Effect[HmacKey, JoseError]
def import_hmac(input: Redacted[SecretJwk], algorithm: HmacAlgorithm) -> Effect[HmacKey, JoseError]:
"""An ``HS*`` key (Effect's ``importSecret`` for an HMAC algorithm); the
JWK must allow ``sign`` and ``verify`` for ``sig``."""
@gen
def body():
jwk, data = yield from _secret_bytes(input, algorithm)
key = yield from mac.key(_HMAC_ALGORITHMS[algorithm], data).map_error(
crypto_failure(f"Could not import the {algorithm} key")
)
return HmacKey(algorithm, jwk.get("kid"), key)
return bodyimport_dir#
import_dir(input) -> Effect[DirKey, JoseError]A 32-byte dir (A256GCM) key (Effect's importSecret(jwk, "dir"));
the JWK must allow encrypt and decrypt for enc.
| Parameter | Type | Description |
|---|---|---|
input | Redacted[SecretJwk] |
Returns Effect[DirKey, JoseError]
def import_dir(input: Redacted[SecretJwk]) -> Effect[DirKey, JoseError]:
"""A 32-byte ``dir`` (A256GCM) key (Effect's ``importSecret(jwk, "dir")``);
the JWK must allow ``encrypt`` and ``decrypt`` for ``enc``."""
@gen
def body():
jwk, data = yield from _secret_bytes(input, "dir")
key = yield from aead.key(aead.aes256_gcm, data).map_error(
crypto_failure("Could not import the dir key")
)
return DirKey("dir", jwk.get("kid"), key)
return bodyimport_secret#
import_secret(input, algorithm) -> Effect[SecretKey, JoseError]import_hmac or import_dir by algorithm (Effect's
importSecret).
| Parameter | Type | Description |
|---|---|---|
input | Redacted[SecretJwk] | |
algorithm | SecretAlgorithm |
Returns Effect[SecretKey, JoseError]
def import_secret(
input: Redacted[SecretJwk], algorithm: SecretAlgorithm
) -> Effect[SecretKey, JoseError]:
"""``import_hmac`` or ``import_dir`` by ``algorithm`` (Effect's
``importSecret``)."""
if algorithm == "dir":
return import_dir(input).map(lambda key: key)
return import_hmac(input, algorithm).map(lambda key: key)export_public#
export_public(key) -> Effect[PublicJwk, JoseError]| Parameter | Type | Description |
|---|---|---|
key | PublicKey |
Returns Effect[PublicJwk, JoseError]
def export_public(key: PublicKey) -> Effect[PublicJwk, JoseError]:
return _export_jwk(key.key, key.algorithm, key.kid).map(lambda jwk: cast("PublicJwk", jwk))export_private#
export_private(key) -> Effect[Redacted[PrivateJwk], JoseError]| Parameter | Type | Description |
|---|---|---|
key | PrivateKey |
Returns Effect[Redacted[PrivateJwk], JoseError]
def export_private(key: PrivateKey) -> Effect[Redacted[PrivateJwk], JoseError]:
return _export_jwk(key.key, key.algorithm, key.kid).map(
lambda jwk: redacted(cast("PrivateJwk", jwk))
)export_spki#
export_spki(key) -> Effect[bytes, JoseError]The key as SPKI DER bytes.
| Parameter | Type | Description |
|---|---|---|
key | PublicKey |
Returns Effect[bytes, JoseError]
def export_spki(key: PublicKey) -> Effect[bytes, JoseError]:
"""The key as SPKI DER bytes."""
return key_format.encode(key_format.spki, key.key).map_error(
crypto_failure("Could not export the SPKI key")
)export_spki_pem#
export_spki_pem(key) -> Effect[str, JoseError]The key as SPKI PEM text (Effect's exportSpki(key, { format: "pem" })).
| Parameter | Type | Description |
|---|---|---|
key | PublicKey |
Returns Effect[str, JoseError]
def export_spki_pem(key: PublicKey) -> Effect[str, JoseError]:
"""The key as SPKI PEM text (Effect's ``exportSpki(key, { format: "pem" })``)."""
return key_format.encode(key_format.pem(key_format.spki), key.key).map_error(
crypto_failure("Could not export the SPKI key")
)export_pkcs8#
export_pkcs8(key) -> Effect[Redacted[bytes], JoseError]The key as PKCS#8 DER bytes.
| Parameter | Type | Description |
|---|---|---|
key | PrivateKey |
Returns Effect[Redacted[bytes], JoseError]
def export_pkcs8(key: PrivateKey) -> Effect[Redacted[bytes], JoseError]:
"""The key as PKCS#8 DER bytes."""
return key_format.encode(key_format.pkcs8, key.key).map_both(
on_failure=crypto_failure("Could not export the PKCS#8 key"), on_success=redacted
)export_pkcs8_pem#
export_pkcs8_pem(key) -> Effect[Redacted[str], JoseError]The key as PKCS#8 PEM text (Effect's exportPkcs8(key, { format: "pem" })).
| Parameter | Type | Description |
|---|---|---|
key | PrivateKey |
Returns Effect[Redacted[str], JoseError]
def export_pkcs8_pem(key: PrivateKey) -> Effect[Redacted[str], JoseError]:
"""The key as PKCS#8 PEM text (Effect's ``exportPkcs8(key, { format: "pem" })``)."""
return key_format.encode(key_format.pem(key_format.pkcs8), key.key).map_both(
on_failure=crypto_failure("Could not export the PKCS#8 key"), on_success=redacted
)thumbprint#
thumbprint(input, hash=digest.sha256) -> Effect[str, JoseError, Digest]RFC 7638's thumbprint: the hash of the required members, as base64url.
| Parameter | Type | Description |
|---|---|---|
input | ThumbprintInput | |
hash | digest.Algorithm = digest.sha256 |
Returns Effect[str, JoseError, Digest]
def thumbprint(
input: ThumbprintInput, hash: digest.Algorithm = digest.sha256
) -> Effect[str, JoseError, Digest]:
"""RFC 7638's thumbprint: the hash of the required members, as
base64url."""
@gen
def body():
if hash.name not in _THUMBPRINT_HASHES:
return (
yield from invalid_argument("JWK thumbprints require SHA-256, SHA-384, or SHA-512")
)
jwk = yield from _thumbprint_jwk(input)
required = _required_members(jwk)
if required is None:
return (yield from invalid_key("Unsupported JWK key type for a thumbprint"))
members_ok = all(isinstance(value, str) and value for value in required.values())
if not members_ok or (
not is_canonical_segment(cast("str", required["k"]))
if required["kty"] == "oct"
else not _is_public_jwk(required)
):
return (yield from invalid_key("Expected a JWK with canonical base64url key members"))
service = yield from Digest()
hashed = yield from service.digest(hash, utf8(stringify(required)))
return base64_url_encode(hashed)
return bodythumbprint_uri#
thumbprint_uri(input, hash=digest.sha256) -> Effect[str, JoseError, Digest]RFC 9278's thumbprint URI.
| Parameter | Type | Description |
|---|---|---|
input | ThumbprintInput | |
hash | digest.Algorithm = digest.sha256 |
Returns Effect[str, JoseError, Digest]
def thumbprint_uri(
input: ThumbprintInput, hash: digest.Algorithm = digest.sha256
) -> Effect[str, JoseError, Digest]:
"""RFC 9278's thumbprint URI."""
return thumbprint(input, hash).map(
lambda value: f"urn:ietf:params:oauth:jwk-thumbprint:{hash.name.lower()}:{value}"
)