Skip to content

Commit

Permalink
allow non flattened representation
Browse files Browse the repository at this point in the history
  • Loading branch information
Thomas-Mollard committed Apr 4, 2024
1 parent ecde4ef commit 7c4c70f
Showing 1 changed file with 22 additions and 13 deletions.
35 changes: 22 additions & 13 deletions jwcrypto/jwe.py
Original file line number Diff line number Diff line change
Expand Up @@ -82,7 +82,7 @@ class JWE:

def __init__(self, plaintext=None, protected=None, unprotected=None,
aad=None, algs=None, recipient=None, header=None,
header_registry=None):
header_registry=None, flattened=True):
"""Creates a JWE token.
:param plaintext(bytes): An arbitrary plaintext to be encrypted.
Expand All @@ -93,11 +93,13 @@ def __init__(self, plaintext=None, protected=None, unprotected=None,
:param recipient: An optional, default recipient key
:param header: An optional header for the default recipient
:param header_registry: Optional additions to the header registry
:param flattened: Use flattened serialization syntax (default True)
"""
self._allowed_algs = None
self.objects = {}
self.plaintext = None
self.header_registry = JWSEHeaderRegistry(JWEHeaderRegistry)
self.flattened = flattened
if header_registry:
self.header_registry.update(header_registry)
if plaintext is not None:
Expand Down Expand Up @@ -251,19 +253,26 @@ def add_recipient(self, key, header=None):
if 'ciphertext' not in self.objects:
self._encrypt(alg, enc, jh)

if 'recipients' in self.objects:
self.objects['recipients'].append(rec)
elif 'encrypted_key' in self.objects or 'header' in self.objects:
self.objects['recipients'] = []
n = {}
if 'encrypted_key' in self.objects:
n['encrypted_key'] = self.objects.pop('encrypted_key')
if 'header' in self.objects:
n['header'] = self.objects.pop('header')
self.objects['recipients'].append(n)
self.objects['recipients'].append(rec)
if self.flattened:
if 'recipients' in self.objects:
self.objects['recipients'].append(rec)
elif 'encrypted_key' in self.objects or 'header' in self.objects:
self.objects['recipients'] = []
n = {}
if 'encrypted_key' in self.objects:
n['encrypted_key'] = self.objects.pop('encrypted_key')
if 'header' in self.objects:
n['header'] = self.objects.pop('header')
self.objects['recipients'].append(n)
self.objects['recipients'].append(rec)
else:
self.objects.update(rec)
else:
self.objects.update(rec)
if 'recipients' in self.objects:
self.objects['recipients'].append(rec)
else:
self.objects['recipients'] = [rec]


def serialize(self, compact=False):
"""Serializes the object into a JWE token.
Expand Down

0 comments on commit 7c4c70f

Please sign in to comment.