Skip to content

Commit

Permalink
remove cryptography backend and reformat
Browse files Browse the repository at this point in the history
pass curve as instance and always pass as keyword argument
  • Loading branch information
jschlyter committed Apr 22, 2024
1 parent 727bb9b commit 0ee8d4a
Show file tree
Hide file tree
Showing 17 changed files with 42 additions and 58 deletions.
2 changes: 1 addition & 1 deletion pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@ exclude_lines = [

[tool.poetry]
name = "cryptojwt"
version = "1.9.0"
version = "1.9.1"
description = "Python implementation of JWT, JWE, JWS and JWK"
authors = ["Roland Hedberg <[email protected]>"]
license = "Apache-2.0"
Expand Down
1 change: 1 addition & 0 deletions src/cryptojwt/__init__.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
"""JSON Web Token"""

import logging

import pkg_resources
Expand Down
7 changes: 3 additions & 4 deletions src/cryptojwt/jwe/aes.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
import os
from struct import pack

from cryptography.hazmat.backends import default_backend
from cryptography.hazmat.primitives import hmac
from cryptography.hazmat.primitives.ciphers import Cipher
from cryptography.hazmat.primitives.ciphers import algorithms
Expand Down Expand Up @@ -37,7 +36,7 @@ def __init__(self, key_len=32, key=None, msg_padding="PKCS7"):

def _mac(self, hash_key, hash_func, auth_data, iv, enc_msg, key_len):
al = pack("!Q", 8 * len(auth_data))
h = hmac.HMAC(hash_key, hash_func(), backend=default_backend())
h = hmac.HMAC(hash_key, hash_func())
h.update(auth_data)
h.update(iv)
h.update(enc_msg)
Expand All @@ -54,7 +53,7 @@ def encrypt(self, msg, iv="", auth_data=b""):

hash_key, enc_key, key_len, hash_func = get_keys_seclen_dgst(self.key, iv)

cipher = Cipher(algorithms.AES(enc_key), modes.CBC(iv), backend=default_backend())
cipher = Cipher(algorithms.AES(enc_key), modes.CBC(iv))
encryptor = cipher.encryptor()

pmsg = self.padder.update(msg)
Expand All @@ -77,7 +76,7 @@ def decrypt(self, msg, iv="", auth_data=b"", tag=b"", key=None):
if comp_tag != tag:
raise VerificationError("AES-CBC HMAC")

cipher = Cipher(algorithms.AES(enc_key), modes.CBC(iv), backend=default_backend())
cipher = Cipher(algorithms.AES(enc_key), modes.CBC(iv))
decryptor = cipher.decryptor()

ctext = decryptor.update(msg)
Expand Down
7 changes: 3 additions & 4 deletions src/cryptojwt/jwe/jwe_ec.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
import struct

from cryptography.hazmat.backends import default_backend
from cryptography.hazmat.primitives.asymmetric import ec
from cryptography.hazmat.primitives.keywrap import aes_key_unwrap
from cryptography.hazmat.primitives.keywrap import aes_key_wrap
Expand Down Expand Up @@ -87,7 +86,7 @@ def enc_setup(self, msg, key=None, auth_data=b"", **kwargs):
try:
_epk = kwargs["epk"]
except KeyError:
_epk = ec.generate_private_key(NIST2SEC[as_unicode(key.crv)], default_backend())
_epk = ec.generate_private_key(curve=NIST2SEC[as_unicode(key.crv)]())
epk = ECKey().load_key(_epk.public_key())
else:
if isinstance(_epk, ec.EllipticCurvePrivateKey):
Expand Down Expand Up @@ -120,7 +119,7 @@ def enc_setup(self, msg, key=None, auth_data=b"", **kwargs):
klen = int(_post[1:4])
kek = ecdh_derive_key(_epk, key.pub_key, apu, apv, str(_post).encode(), klen)
cek = self._generate_key(self.enc, cek=cek)
encrypted_key = aes_key_wrap(kek, cek, default_backend())
encrypted_key = aes_key_wrap(kek, cek)
else:
raise Exception("Unsupported algorithm %s" % self.alg)

Expand Down Expand Up @@ -172,7 +171,7 @@ def dec_setup(self, token, key=None, **kwargs):
_pre, _post = self.headers["alg"].split("+")
klen = int(_post[1:4])
kek = ecdh_derive_key(key, epubkey.pub_key, apu, apv, str(_post).encode(), klen)
self.cek = aes_key_unwrap(kek, token.encrypted_key(), default_backend())
self.cek = aes_key_unwrap(kek, token.encrypted_key())
else:
raise Exception("Unsupported algorithm %s" % self.headers["alg"])

Expand Down
5 changes: 2 additions & 3 deletions src/cryptojwt/jwe/jwe_hmac.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
import logging
import zlib

from cryptography.hazmat.backends import default_backend
from cryptography.hazmat.primitives.keywrap import aes_key_unwrap
from cryptography.hazmat.primitives.keywrap import aes_key_wrap

Expand Down Expand Up @@ -57,7 +56,7 @@ def encrypt(self, key, iv="", cek="", **kwargs):

# The iv for this function must be 64 bit
# Which is certainly different from the one above
jek = aes_key_wrap(kek, cek, default_backend())
jek = aes_key_wrap(kek, cek)

_enc = self["enc"]
_auth_data = jwe.b64_encode_header()
Expand Down Expand Up @@ -85,7 +84,7 @@ def decrypt(self, token, key=None, cek=None):
except AttributeError:
key = key.key
# The iv for this function must be 64 bit
cek = aes_key_unwrap(key, jek, default_backend())
cek = aes_key_unwrap(key, jek)

auth_data = jwe.b64_protected_header()
msg = self._decrypt(
Expand Down
3 changes: 1 addition & 2 deletions src/cryptojwt/jwe/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,6 @@
import struct
from math import ceil

from cryptography.hazmat.backends import default_backend
from cryptography.hazmat.primitives import hashes
from cryptography.hazmat.primitives.hashes import SHA256
from cryptography.hazmat.primitives.hashes import SHA384
Expand Down Expand Up @@ -107,7 +106,7 @@ def concat_sha256(secret, dk_len, other_info):
while len(dkm) < dk_bytes:
counter += 1
counter_bytes = struct.pack("!I", counter)
digest = hashes.Hash(hashes.SHA256(), backend=default_backend())
digest = hashes.Hash(hashes.SHA256())
digest.update(counter_bytes)
digest.update(secret)
digest.update(other_info)
Expand Down
7 changes: 3 additions & 4 deletions src/cryptojwt/jwk/ec.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
from cryptography.hazmat.backends import default_backend
from cryptography.hazmat.primitives.asymmetric import ec

from cryptojwt.exception import KeyNotFound
Expand Down Expand Up @@ -50,7 +49,7 @@ def ec_construct_public(num):
raise UnsupportedECurve("Unsupported elliptic curve: {}".format(num["crv"]))

ecpn = ec.EllipticCurvePublicNumbers(num["x"], num["y"], _sec_crv())
return ecpn.public_key(default_backend())
return ecpn.public_key()


def ec_construct_private(num):
Expand All @@ -64,7 +63,7 @@ def ec_construct_private(num):
"""
pub_ecpn = ec.EllipticCurvePublicNumbers(num["x"], num["y"], NIST2SEC[as_unicode(num["crv"])]())
priv_ecpn = ec.EllipticCurvePrivateNumbers(num["d"], pub_ecpn)
return priv_ecpn.private_key(default_backend())
return priv_ecpn.private_key()


class ECKey(AsymmetricKey):
Expand Down Expand Up @@ -285,7 +284,7 @@ def cmp_keys(a, b, key_type):


def new_ec_key(crv, kid="", **kwargs):
_key = ec.generate_private_key(curve=NIST2SEC[crv], backend=default_backend())
_key = ec.generate_private_key(curve=NIST2SEC[crv]())

_rk = ECKey(priv_key=_key, kid=kid, **kwargs)
if not kid:
Expand Down
11 changes: 4 additions & 7 deletions src/cryptojwt/jwk/jwk.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,6 @@
import json
import os

from cryptography.hazmat import backends
from cryptography.hazmat.primitives.asymmetric import ec
from cryptography.hazmat.primitives.asymmetric import ed448
from cryptography.hazmat.primitives.asymmetric import ed25519
Expand Down Expand Up @@ -105,9 +104,7 @@ def key_from_jwk_dict(jwk_dict, private=None):

if _jwk_dict.get("d", None) is not None:
# Ecdsa private key.
_jwk_dict["priv_key"] = ec.derive_private_key(
base64url_to_long(_jwk_dict["d"]), curve, backends.default_backend()
)
_jwk_dict["priv_key"] = ec.derive_private_key(base64url_to_long(_jwk_dict["d"]), curve)
_jwk_dict["pub_key"] = _jwk_dict["priv_key"].public_key()
else:
# Ecdsa public key.
Expand All @@ -116,7 +113,7 @@ def key_from_jwk_dict(jwk_dict, private=None):
base64url_to_long(_jwk_dict["y"]),
curve,
)
_jwk_dict["pub_key"] = ec_pub_numbers.public_key(backends.default_backend())
_jwk_dict["pub_key"] = ec_pub_numbers.public_key()
return ECKey(**_jwk_dict)
elif _jwk_dict["kty"] == "RSA":
ensure_rsa_params(_jwk_dict, private)
Expand Down Expand Up @@ -151,10 +148,10 @@ def key_from_jwk_dict(jwk_dict, private=None):
rsa_priv_numbers = rsa.RSAPrivateNumbers(
p_long, q_long, d_long, dp_long, dq_long, qi_long, rsa_pub_numbers
)
_jwk_dict["priv_key"] = rsa_priv_numbers.private_key(backends.default_backend())
_jwk_dict["priv_key"] = rsa_priv_numbers.private_key()
_jwk_dict["pub_key"] = _jwk_dict["priv_key"].public_key()
else:
_jwk_dict["pub_key"] = rsa_pub_numbers.public_key(backends.default_backend())
_jwk_dict["pub_key"] = rsa_pub_numbers.public_key()

if _jwk_dict["kty"] != "RSA":
raise WrongKeyType('"{}" should have been "RSA"'.format(_jwk_dict["kty"]))
Expand Down
13 changes: 4 additions & 9 deletions src/cryptojwt/jwk/rsa.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
import base64
import logging

from cryptography.hazmat.backends import default_backend
from cryptography.hazmat.primitives import serialization
from cryptography.hazmat.primitives.asymmetric import rsa

Expand Down Expand Up @@ -40,9 +39,7 @@ def generate_and_store_rsa_key(key_size=2048, filename="rsa.key", passphrase="")
:return: A
cryptography.hazmat.primitives.asymmetric.rsa.RSAPrivateKey instance
"""
private_key = rsa.generate_private_key(
public_exponent=65537, key_size=key_size, backend=default_backend()
)
private_key = rsa.generate_private_key(public_exponent=65537, key_size=key_size)

with open(filename, "wb") as keyfile:
if passphrase:
Expand Down Expand Up @@ -141,7 +138,7 @@ def x509_rsa_load(txt):

def rsa_construct_public(numbers):
rpn = rsa.RSAPublicNumbers(**numbers)
return rpn.public_key(default_backend())
return rpn.public_key()


def rsa_construct_private(numbers):
Expand Down Expand Up @@ -181,7 +178,7 @@ def rsa_construct_private(numbers):

rpubn = rsa.RSAPublicNumbers(e=numbers["e"], n=numbers["n"])
rprivn = rsa.RSAPrivateNumbers(public_numbers=rpubn, **cnum)
return rprivn.private_key(default_backend())
return rprivn.private_key()


def cmp_public_numbers(pn1, pn2):
Expand Down Expand Up @@ -492,9 +489,7 @@ def new_rsa_key(key_size=2048, kid="", public_exponent=65537, **kwargs):
:return: A :py:class:`cryptojwt.jwk.rsa.RSAKey` instance
"""

_key = rsa.generate_private_key(
public_exponent=public_exponent, key_size=key_size, backend=default_backend()
)
_key = rsa.generate_private_key(public_exponent=public_exponent, key_size=key_size)

_rk = RSAKey(priv_key=_key, kid=kid, **kwargs)
if not _rk.kid:
Expand Down
13 changes: 5 additions & 8 deletions src/cryptojwt/jwk/x509.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,6 @@
import logging

from cryptography import x509
from cryptography.hazmat.backends import default_backend
from cryptography.hazmat.primitives import serialization
from cryptography.hazmat.primitives.asymmetric import ec
from cryptography.hazmat.primitives.asymmetric import rsa
Expand All @@ -22,7 +21,7 @@ def import_public_key_from_pem_file(filename):
:return: A public key instance
"""
with open(filename, "rb") as key_file:
public_key = serialization.load_pem_public_key(key_file.read(), backend=default_backend())
public_key = serialization.load_pem_public_key(key_file.read())
return public_key


Expand All @@ -35,9 +34,7 @@ def import_private_key_from_pem_file(filename, passphrase=None):
:return: A private key instance
"""
with open(filename, "rb") as key_file:
private_key = serialization.load_pem_private_key(
key_file.read(), password=passphrase, backend=default_backend()
)
private_key = serialization.load_pem_private_key(key_file.read(), password=passphrase)
return private_key


Expand All @@ -56,7 +53,7 @@ def import_public_key_from_pem_data(pem_data):
pem_data = bytes("{}\n{}\n{}".format(PREFIX, pem_data, POSTFIX), "utf-8")
else:
pem_data = bytes(pem_data, "utf-8")
cert = x509.load_pem_x509_certificate(pem_data, default_backend())
cert = x509.load_pem_x509_certificate(pem_data)
return cert.public_key()


Expand All @@ -68,7 +65,7 @@ def import_public_key_from_cert_file(filename):
:return: A public key instance
"""
with open(filename, "rb") as key_file:
cert = x509.load_pem_x509_certificate(key_file.read(), backend=default_backend())
cert = x509.load_pem_x509_certificate(key_file.read())
return cert.public_key()


Expand All @@ -81,7 +78,7 @@ def der_cert(der_data):
"""
if isinstance(der_data, str):
der_data = bytes(der_data, "utf-8")
return x509.load_der_x509_certificate(der_data, default_backend())
return x509.load_der_x509_certificate(der_data)


def load_x509_cert(url, httpc, spec2key, **get_args):
Expand Down
5 changes: 2 additions & 3 deletions src/cryptojwt/jws/hmac.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
from cryptography.hazmat.backends import default_backend
from cryptography.hazmat.primitives import hashes
from cryptography.hazmat.primitives import hmac

Expand Down Expand Up @@ -26,7 +25,7 @@ def sign(self, msg, key):
:param key: The key
:return: A signature
"""
h = hmac.HMAC(key, self.algorithm(), default_backend())
h = hmac.HMAC(key, self.algorithm())
h.update(msg)
return h.finalize()

Expand All @@ -41,7 +40,7 @@ def verify(self, msg, sig, key):
Exception.
"""
try:
h = hmac.HMAC(key, self.algorithm(), default_backend())
h = hmac.HMAC(key, self.algorithm())
h.update(msg)
h.verify(sig)
return True
Expand Down
1 change: 1 addition & 0 deletions src/cryptojwt/jws/jws.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
"""JSON Web Token"""

import json
import logging

Expand Down
3 changes: 1 addition & 2 deletions src/cryptojwt/jws/pss.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
import logging

from cryptography.exceptions import InvalidSignature
from cryptography.hazmat.backends import default_backend
from cryptography.hazmat.primitives import hashes
from cryptography.hazmat.primitives.asymmetric import padding
from cryptography.hazmat.primitives.asymmetric import utils
Expand Down Expand Up @@ -32,7 +31,7 @@ def sign(self, msg, key):
:param key: The key
:return: A signature
"""
hasher = hashes.Hash(self.hash_algorithm(), backend=default_backend())
hasher = hashes.Hash(self.hash_algorithm())
hasher.update(msg)
digest = hasher.finalize()
sig = key.sign(
Expand Down
1 change: 1 addition & 0 deletions src/cryptojwt/jwt.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
"""Basic JSON Web Token implementation."""

import json
import logging
import time
Expand Down
1 change: 1 addition & 0 deletions src/cryptojwt/jwx.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
"""A basic class on which to build the JWS and JWE classes."""

import json
import logging
import warnings
Expand Down
Loading

0 comments on commit 0ee8d4a

Please sign in to comment.