Skip to content

Commit

Permalink
better tests
Browse files Browse the repository at this point in the history
set salt on password only
  • Loading branch information
jschlyter committed Apr 12, 2022
1 parent 03af3f5 commit d4908be
Show file tree
Hide file tree
Showing 2 changed files with 12 additions and 6 deletions.
11 changes: 5 additions & 6 deletions src/cryptojwt/jwe/fernet.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,17 +17,13 @@ class FernetEncrypter(Encrypter):
def __init__(
self,
password: Optional[str] = None,
key: Optional[bytes] = None,
salt: Optional[bytes] = "",
key: Optional[bytes] = None,
hash_alg: Optional[str] = "SHA256",
digest_size: Optional[int] = 0,
iterations: Optional[int] = DEFAULT_ITERATIONS,
):
Encrypter.__init__(self)
if not salt:
salt = os.urandom(16)
else:
salt = as_bytes(salt)

if password is not None:
_alg = getattr(hashes, hash_alg)
Expand All @@ -36,12 +32,15 @@ def __init__(
_algorithm = _alg(digest_size)
else:
_algorithm = _alg()
salt = as_bytes(salt) if salt else os.urandom(16)
kdf = PBKDF2HMAC(algorithm=_algorithm, length=32, salt=salt, iterations=iterations)
self.key = base64.urlsafe_b64encode(kdf.derive(as_bytes(password)))
elif key is not None:
if not isinstance(key, bytes):
raise TypeError("Raw key must be bytes")
if len(key) != 32:
raise ValueError("Raw key must be 32 bytes")
self.key = base64.urlsafe_b64encode(as_bytes(key))
self.key = base64.urlsafe_b64encode(key)
else:
self.key = Fernet.generate_key()

Expand Down
7 changes: 7 additions & 0 deletions tests/test_07_jwe.py
Original file line number Diff line number Diff line change
Expand Up @@ -668,6 +668,13 @@ def test_fernet_symkey():
assert resp == plain


def test_fernet_bad():
with pytest.raises(TypeError):
encrypter = FernetEncrypter(key="xyzzy")
with pytest.raises(ValueError):
encrypter = FernetEncrypter(key=os.urandom(16))


def test_fernet_bytes():
key = os.urandom(32)

Expand Down

0 comments on commit d4908be

Please sign in to comment.