Skip to content

Commit

Permalink
Updating CryptographyAESKey::encrypt to generate 96 bit IVs for GCM…
Browse files Browse the repository at this point in the history
… block cipher mode to adhere to the RFC for JWA in `jose/backends/cryptography_backend.py`

See https://www.rfc-editor.org/rfc/rfc7518.html#section-5.3 for the official RFC requirements for JWA

See panva/jose#678 for related discussion on this issue
  • Loading branch information
twwildey committed May 30, 2024
1 parent 4b0701b commit 56105d0
Show file tree
Hide file tree
Showing 4 changed files with 7 additions and 1 deletion.
1 change: 1 addition & 0 deletions jose/backends/_asn1.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
Required by rsa_backend but not cryptography_backend.
"""

from pyasn1.codec.der import decoder, encoder
from pyasn1.type import namedtype, univ

Expand Down
5 changes: 4 additions & 1 deletion jose/backends/cryptography_backend.py
Original file line number Diff line number Diff line change
Expand Up @@ -439,6 +439,8 @@ class CryptographyAESKey(Key):
ALGORITHMS.A256KW: None,
}

IV_BYTE_LENGTH_MODE_MAP = {"CBC": algorithms.AES.block_size // 8, "GCM": 96 // 8}

def __init__(self, key, algorithm):
if algorithm not in ALGORITHMS.AES:
raise JWKError("%s is not a valid AES algorithm" % algorithm)
Expand Down Expand Up @@ -468,7 +470,8 @@ def to_dict(self):
def encrypt(self, plain_text, aad=None):
plain_text = ensure_binary(plain_text)
try:
iv = get_random_bytes(algorithms.AES.block_size // 8)
iv_byte_length = self.IV_BYTE_LENGTH_MODE_MAP.get(self._mode.name, algorithms.AES.block_size)
iv = get_random_bytes(iv_byte_length)
mode = self._mode(iv)
if mode.name == "GCM":
cipher = aead.AESGCM(self._key)
Expand Down
1 change: 1 addition & 0 deletions tests/test_asn1.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
"""Tests for ``jose.backends._asn1``."""

import base64

import pytest
Expand Down
1 change: 1 addition & 0 deletions tests/test_backends.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
"""Test the default import handling."""

try:
from jose.backends.rsa_backend import RSAKey as PurePythonRSAKey
except ImportError:
Expand Down

0 comments on commit 56105d0

Please sign in to comment.