Skip to content

Added Fernet encrypter. #120

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 9 commits into from
Apr 9, 2022
Merged
Show file tree
Hide file tree
Changes from 6 commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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.7.1"
version = "1.7.2"
description = "Python implementation of JWT, JWE, JWS and JWK"
authors = ["Roland Hedberg <roland@catalogix.se>"]
license = "Apache-2.0"
Expand Down
37 changes: 37 additions & 0 deletions src/cryptojwt/jwe/fernet.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
import base64
import os
from typing import Optional
from typing import Union

from cryptography.fernet import Fernet
from cryptography.hazmat.primitives import hashes
from cryptography.hazmat.primitives.kdf.pbkdf2 import PBKDF2HMAC

from cryptojwt import as_unicode
from cryptojwt.jwe import Encrypter
from cryptojwt.utils import as_bytes


class FernetEncrypter(Encrypter):
def __init__(self, password: str, salt: Optional[bytes] = ""):
Encrypter.__init__(self)
if not salt:
salt = os.urandom(16)
else:
salt = as_bytes(salt)

kdf = PBKDF2HMAC(algorithm=hashes.SHA256(), length=32, salt=salt, iterations=390000)
self.key = base64.urlsafe_b64encode(kdf.derive(as_bytes(password)))
self.core = Fernet(self.key)

def encrypt(self, msg: Union[str, bytes], **kwargs) -> bytes:
text = as_bytes(msg)
# Padding to block size of AES
if len(text) % 16:
text += b" " * (16 - len(text) % 16)
return self.core.encrypt(as_bytes(text))

def decrypt(self, msg: Union[str, bytes], **kwargs) -> bytes:
dec_text = self.core.decrypt(as_bytes(msg))
dec_text = dec_text.rstrip(b" ")
return dec_text
2 changes: 1 addition & 1 deletion src/cryptojwt/jws/jws.py
Original file line number Diff line number Diff line change
Expand Up @@ -116,7 +116,7 @@ def sign_compact(self, keys=None, protected=None, **kwargs):
key, xargs, _alg = self.alg_keys(keys, "sig", protected)

if "typ" in self:
xargs["typ"] = self["typ"]
xargs["type"] = self["typ"]

_headers.update(xargs)
jwt = JWSig(**_headers)
Expand Down
12 changes: 12 additions & 0 deletions tests/test_07_jwe.py
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@
from cryptojwt.jwe.exception import NoSuitableEncryptionKey
from cryptojwt.jwe.exception import UnsupportedBitLength
from cryptojwt.jwe.exception import WrongEncryptionAlgorithm
from cryptojwt.jwe.fernet import FernetEncrypter
from cryptojwt.jwe.jwe import JWE
from cryptojwt.jwe.jwe import factory
from cryptojwt.jwe.jwe_ec import JWE_EC
Expand Down Expand Up @@ -643,3 +644,14 @@ def test_invalid():
decrypter = JWE(plain, alg="A128KW", enc="A128CBC-HS256")
with pytest.raises(BadSyntax):
decrypter.decrypt("a.b.c.d.e", keys=[encryption_key])


def test_fernet():
encryption_key = SYMKey(use="enc", key="DukeofHazardpass", kid="some-key-id")

encrypter = FernetEncrypter(encryption_key.key)
_token = encrypter.encrypt(plain)

decrypter = encrypter
resp = decrypter.decrypt(_token)
assert resp == plain