diff options
author | JohannesWill <johannes.will@siemens.com> | 2021-04-28 13:42:22 +0200 |
---|---|---|
committer | GitHub <noreply@github.com> | 2021-04-28 07:42:22 -0400 |
commit | 545931dafd9ec318e8d8acff6d5a4daeedf50863 (patch) | |
tree | 75e4217b59ba46ecf8e6a18ffde584ecb1731d91 /jwt/algorithms.py | |
parent | 7f6a2361943ffae20007eb014900060c6b21d9cc (diff) | |
download | pyjwt-545931dafd9ec318e8d8acff6d5a4daeedf50863.tar.gz |
Add to_jwk to Ed25519Algorithm. (#642) (#643)
* Add to_jwk to Ed25519Algorithm. (#642)
* add test for invalid key
* [pre-commit.ci] auto fixes from pre-commit.com hooks
for more information, see https://pre-commit.ci
* update CHANGELOG for #643
* remove alg from jwk
Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>
Diffstat (limited to 'jwt/algorithms.py')
-rw-r--r-- | jwt/algorithms.py | 43 |
1 files changed, 43 insertions, 0 deletions
diff --git a/jwt/algorithms.py b/jwt/algorithms.py index bed4033..cee66a4 100644 --- a/jwt/algorithms.py +++ b/jwt/algorithms.py @@ -37,6 +37,10 @@ try: rsa_recover_prime_factors, ) from cryptography.hazmat.primitives.serialization import ( + Encoding, + NoEncryption, + PrivateFormat, + PublicFormat, load_pem_private_key, load_pem_public_key, load_ssh_public_key, @@ -590,6 +594,45 @@ if has_crypto: return False @staticmethod + def to_jwk(key): + if isinstance(key, Ed25519PublicKey): + x = key.public_bytes( + encoding=Encoding.Raw, + format=PublicFormat.Raw, + ) + + return json.dumps( + { + "x": base64url_encode(force_bytes(x)).decode(), + "kty": "OKP", + "crv": "Ed25519", + } + ) + + if isinstance(key, Ed25519PrivateKey): + d = key.private_bytes( + encoding=Encoding.Raw, + format=PrivateFormat.Raw, + encryption_algorithm=NoEncryption(), + ) + + x = key.public_key().public_bytes( + encoding=Encoding.Raw, + format=PublicFormat.Raw, + ) + + return json.dumps( + { + "x": base64url_encode(force_bytes(x)).decode(), + "d": base64url_encode(force_bytes(d)).decode(), + "kty": "OKP", + "crv": "Ed25519", + } + ) + + raise InvalidKeyError("Not a public or private key") + + @staticmethod def from_jwk(jwk): try: if isinstance(jwk, str): |