def serialize_compact(self, protected, payload, key): """Generate a JWS Compact Serialization. The JWS Compact Serialization represents digitally signed or MACed content as a compact, URL-safe string, per `Section 7.1`_. .. code-block:: text BASE64URL(UTF8(JWS Protected Header)) || '.' || BASE64URL(JWS Payload) || '.' || BASE64URL(JWS Signature) :param protected: A dict of protected header :param payload: A bytes/string of payload :param key: Private key used to generate signature :return: byte """ jws_header = JWSHeader(protected, None) self._validate_private_headers(protected) algorithm, key = self._prepare_algorithm_key(protected, payload, key) protected_segment = json_b64encode(jws_header.protected) payload_segment = urlsafe_b64encode(to_bytes(payload)) # calculate signature signing_input = b'.'.join([protected_segment, payload_segment]) signature = urlsafe_b64encode(algorithm.sign(signing_input, key)) return b'.'.join([protected_segment, payload_segment, signature])
def serialize_compact(self, protected, payload, key): """Generate a JWE Compact Serialization. The JWE Compact Serialization represents encrypted content as a compact, URL-safe string. This string is: BASE64URL(UTF8(JWE Protected Header)) || '.' || BASE64URL(JWE Encrypted Key) || '.' || BASE64URL(JWE Initialization Vector) || '.' || BASE64URL(JWE Ciphertext) || '.' || BASE64URL(JWE Authentication Tag) Only one recipient is supported by the JWE Compact Serialization and it provides no syntax to represent JWE Shared Unprotected Header, JWE Per-Recipient Unprotected Header, or JWE AAD values. :param protected: A dict of protected header :param payload: A string/dict of payload :param key: Private key used to generate signature :return: byte """ self._pre_validate_header(protected) # step 1: Prepare algorithms algorithm, enc_alg, key = self._prepare_alg_enc_key(protected, key) self._post_validate_header(protected, algorithm) # step 2: Generate a random Content Encryption Key (CEK) cek = enc_alg.generate_cek() # step 3: Encrypt the CEK with the recipient's public key ek = algorithm.wrap(cek, protected, key) if isinstance(ek, dict): # AESGCMKW algorithm contains iv, tag in header header = ek.get('header') if header: protected.update(header) ek = ek.get('ek') # step 4: Generate a random JWE Initialization Vector iv = enc_alg.generate_iv() # step 5: Let the Additional Authenticated Data encryption parameter # be ASCII(BASE64URL(UTF8(JWE Protected Header))) protected_segment = json_b64encode(protected) aad = to_bytes(protected_segment, 'ascii') # step 6: compress message if required msg = self._zip_compress(payload, protected) # step 7: perform encryption ciphertext, tag = enc_alg.encrypt(msg, aad, iv, cek) return b'.'.join([ protected_segment, urlsafe_b64encode(ek), urlsafe_b64encode(iv), urlsafe_b64encode(ciphertext), urlsafe_b64encode(tag) ])
def serialize_json(self, header_obj, payload, key): """Generate a JWS JSON Serialization. The JWS JSON Serialization represents digitally signed or MACed content as a JSON object, per `Section 7.2`_. :param header_obj: A dict/list of header :param payload: A string/dict of payload :param key: Private key used to generate signature :return: JWSObject Example ``header_obj`` of JWS JSON Serialization:: { "protected: {"alg": "HS256"}, "header": {"kid": "jose"} } Pass a dict to generate flattened JSON Serialization, pass a list of header dict to generate standard JSON Serialization. """ payload_segment = json_b64encode(payload) def _sign(jws_header): self._validate_header(jws_header) _alg, _key = prepare_algorithm_key(self._algorithms, jws_header, payload, key, private=True) protected_segment = json_b64encode(jws_header.protected) signing_input = b'.'.join([protected_segment, payload_segment]) signature = urlsafe_b64encode(_alg.sign(signing_input, _key)) rv = { 'protected': to_unicode(protected_segment), 'signature': to_unicode(signature) } if jws_header.header is not None: rv['header'] = jws_header.header return rv if isinstance(header_obj, dict): data = _sign(JWSHeader.from_dict(header_obj)) data['payload'] = to_unicode(payload_segment) return data signatures = [_sign(JWSHeader.from_dict(h)) for h in header_obj] return { 'payload': to_unicode(payload_segment), 'signatures': signatures }
def _sign(jws_header): self._validate_private_headers(jws_header) _alg, _key = self._prepare_algorithm_key(jws_header, payload, key) protected_segment = json_b64encode(jws_header.protected) signing_input = b'.'.join([protected_segment, payload_segment]) signature = urlsafe_b64encode(_alg.sign(signing_input, _key)) rv = { 'protected': to_unicode(protected_segment), 'signature': to_unicode(signature) } if jws_header.header is not None: rv['header'] = jws_header.header return rv
def test_keys(): """Try to store/get/remove keys""" # JWS jws = JsonWebSignature(algorithms=["RS256"]) code_payload = { "user_id": "user", "scope": "scope", "client_id": "client", "redirect_uri": "redirect_uri", "code_challenge": "code_challenge", } # Token metadata header = {"alg": "RS256"} payload = { "sub": "user", "iss": "issuer", "scope": "scope", "setup": "setup", "group": "my_group" } # Remove all keys result = db.removeKeys() assert result["OK"], result["Message"] # Check active keys result = db.getActiveKeys() assert result["OK"], result["Message"] assert result["Value"] == [] # Create new one result = db.getPrivateKey() assert result["OK"], result["Message"] private_key = result["Value"] assert isinstance(private_key, RSAKey) # Sign token header["kid"] = private_key.thumbprint() # Find key by KID result = db.getPrivateKey(header["kid"]) assert result["OK"], result["Message"] # as_dict has no arguments for authlib < 1.0.0 # for authlib >= 1.0.0: assert result["Value"].as_dict(True) == private_key.as_dict(True) # Sign token token = jwt.encode(header, payload, private_key) # Sign auth code code = jws.serialize_compact(header, json_b64encode(code_payload), private_key) # Get public key set result = db.getKeySet() keyset = result["Value"] assert result["OK"], result["Message"] # as_dict has no arguments for authlib < 1.0.0 # for authlib >= 1.0.0: assert bool([ key for key in keyset.as_dict(True)["keys"] if key["kid"] == header["kid"] ]) # Read token _payload = jwt.decode(token, JsonWebKey.import_key_set(keyset.as_dict())) assert _payload == payload # Read auth code data = jws.deserialize_compact(code, keyset.keys[0]) _code_payload = json_loads(urlsafe_b64decode(data["payload"])) assert _code_payload == code_payload
def serialize_compact(self, protected, payload, key, sender_key=None): """Generate a JWE Compact Serialization. The JWE Compact Serialization represents encrypted content as a compact, URL-safe string. This string is:: BASE64URL(UTF8(JWE Protected Header)) || '.' || BASE64URL(JWE Encrypted Key) || '.' || BASE64URL(JWE Initialization Vector) || '.' || BASE64URL(JWE Ciphertext) || '.' || BASE64URL(JWE Authentication Tag) Only one recipient is supported by the JWE Compact Serialization and it provides no syntax to represent JWE Shared Unprotected Header, JWE Per-Recipient Unprotected Header, or JWE AAD values. :param protected: A dict of protected header :param payload: Payload (bytes or a value convertible to bytes) :param key: Public key used to encrypt payload :param sender_key: Sender's private key in case JWEAlgorithmWithTagAwareKeyAgreement is used :return: JWE compact serialization as bytes """ # step 1: Prepare algorithms & key alg = self.get_header_alg(protected) enc = self.get_header_enc(protected) zip_alg = self.get_header_zip(protected) self._validate_sender_key(sender_key, alg) self._validate_private_headers(protected, alg) key = prepare_key(alg, protected, key) if sender_key is not None: sender_key = alg.prepare_key(sender_key) # self._post_validate_header(protected, algorithm) # step 2: Generate a random Content Encryption Key (CEK) # use enc_alg.generate_cek() in scope of upcoming .wrap or .generate_keys_and_prepare_headers call # step 3: Encrypt the CEK with the recipient's public key if isinstance(alg, JWEAlgorithmWithTagAwareKeyAgreement) and alg.key_size is not None: # For a JWE algorithm with tag-aware key agreement in case key agreement with key wrapping mode is used: # Defer key agreement with key wrapping until authentication tag is computed prep = alg.generate_keys_and_prepare_headers(enc, key, sender_key) epk = prep['epk'] cek = prep['cek'] protected.update(prep['header']) else: # In any other case: # Keep the normal steps order defined by RFC 7516 if isinstance(alg, JWEAlgorithmWithTagAwareKeyAgreement): wrapped = alg.wrap(enc, protected, key, sender_key) else: wrapped = alg.wrap(enc, protected, key) cek = wrapped['cek'] ek = wrapped['ek'] if 'header' in wrapped: protected.update(wrapped['header']) # step 4: Generate a random JWE Initialization Vector iv = enc.generate_iv() # step 5: Let the Additional Authenticated Data encryption parameter # be ASCII(BASE64URL(UTF8(JWE Protected Header))) protected_segment = json_b64encode(protected) aad = to_bytes(protected_segment, 'ascii') # step 6: compress message if required if zip_alg: msg = zip_alg.compress(to_bytes(payload)) else: msg = to_bytes(payload) # step 7: perform encryption ciphertext, tag = enc.encrypt(msg, aad, iv, cek) if isinstance(alg, JWEAlgorithmWithTagAwareKeyAgreement) and alg.key_size is not None: # For a JWE algorithm with tag-aware key agreement in case key agreement with key wrapping mode is used: # Perform key agreement with key wrapping deferred at step 3 wrapped = alg.agree_upon_key_and_wrap_cek(enc, protected, key, sender_key, epk, cek, tag) ek = wrapped['ek'] # step 8: build resulting message return b'.'.join([ protected_segment, urlsafe_b64encode(ek), urlsafe_b64encode(iv), urlsafe_b64encode(ciphertext), urlsafe_b64encode(tag) ])
def serialize_json(self, header_obj, payload, keys, sender_key=None): """Generate a JWE JSON Serialization (in fully general syntax). The JWE JSON Serialization represents encrypted content as a JSON object. This representation is neither optimized for compactness nor URL safe. The following members are defined for use in top-level JSON objects used for the fully general JWE JSON Serialization syntax: protected The "protected" member MUST be present and contain the value BASE64URL(UTF8(JWE Protected Header)) when the JWE Protected Header value is non-empty; otherwise, it MUST be absent. These Header Parameter values are integrity protected. unprotected The "unprotected" member MUST be present and contain the value JWE Shared Unprotected Header when the JWE Shared Unprotected Header value is non-empty; otherwise, it MUST be absent. This value is represented as an unencoded JSON object, rather than as a string. These Header Parameter values are not integrity protected. iv The "iv" member MUST be present and contain the value BASE64URL(JWE Initialization Vector) when the JWE Initialization Vector value is non-empty; otherwise, it MUST be absent. aad The "aad" member MUST be present and contain the value BASE64URL(JWE AAD)) when the JWE AAD value is non-empty; otherwise, it MUST be absent. A JWE AAD value can be included to supply a base64url-encoded value to be integrity protected but not encrypted. ciphertext The "ciphertext" member MUST be present and contain the value BASE64URL(JWE Ciphertext). tag The "tag" member MUST be present and contain the value BASE64URL(JWE Authentication Tag) when the JWE Authentication Tag value is non-empty; otherwise, it MUST be absent. recipients The "recipients" member value MUST be an array of JSON objects. Each object contains information specific to a single recipient. This member MUST be present with exactly one array element per recipient, even if some or all of the array element values are the empty JSON object "{}" (which can happen when all Header Parameter values are shared between all recipients and when no encrypted key is used, such as when doing Direct Encryption). The following members are defined for use in the JSON objects that are elements of the "recipients" array: header The "header" member MUST be present and contain the value JWE Per- Recipient Unprotected Header when the JWE Per-Recipient Unprotected Header value is non-empty; otherwise, it MUST be absent. This value is represented as an unencoded JSON object, rather than as a string. These Header Parameter values are not integrity protected. encrypted_key The "encrypted_key" member MUST be present and contain the value BASE64URL(JWE Encrypted Key) when the JWE Encrypted Key value is non-empty; otherwise, it MUST be absent. This implementation assumes that "alg" and "enc" header fields are contained in the protected or shared unprotected header. :param header_obj: A dict of headers (in addition optionally contains JWE AAD) :param payload: Payload (bytes or a value convertible to bytes) :param keys: Public keys (or a single public key) used to encrypt payload :param sender_key: Sender's private key in case JWEAlgorithmWithTagAwareKeyAgreement is used :return: JWE JSON serialization (in fully general syntax) as dict Example of `header_obj`:: { "protected": { "alg": "ECDH-1PU+A128KW", "enc": "A256CBC-HS512", "apu": "QWxpY2U", "apv": "Qm9iIGFuZCBDaGFybGll" }, "unprotected": { "jku": "https://alice.example.com/keys.jwks" }, "recipients": [ { "header": { "kid": "bob-key-2" } }, { "header": { "kid": "2021-05-06" } } ], "aad": b'Authenticate me too.' } """ if not isinstance(keys, list): # single key keys = [keys] if not keys: raise ValueError("No keys have been provided") header_obj = deepcopy(header_obj) shared_header = JWESharedHeader.from_dict(header_obj) recipients = header_obj.get('recipients') if recipients is None: recipients = [{} for _ in keys] for i in range(len(recipients)): if recipients[i] is None: recipients[i] = {} if 'header' not in recipients[i]: recipients[i]['header'] = {} jwe_aad = header_obj.get('aad') if len(keys) != len(recipients): raise ValueError("Count of recipient keys {} does not equal to count of recipients {}" .format(len(keys), len(recipients))) # step 1: Prepare algorithms & key alg = self.get_header_alg(shared_header) enc = self.get_header_enc(shared_header) zip_alg = self.get_header_zip(shared_header) self._validate_sender_key(sender_key, alg) self._validate_private_headers(shared_header, alg) for recipient in recipients: self._validate_private_headers(recipient['header'], alg) for i in range(len(keys)): keys[i] = prepare_key(alg, recipients[i]['header'], keys[i]) if sender_key is not None: sender_key = alg.prepare_key(sender_key) # self._post_validate_header(protected, algorithm) # step 2: Generate a random Content Encryption Key (CEK) # use enc_alg.generate_cek() in scope of upcoming .wrap or .generate_keys_and_prepare_headers call # step 3: Encrypt the CEK with the recipient's public key preset = alg.generate_preset(enc, keys[0]) if 'cek' in preset: cek = preset['cek'] else: cek = None if len(keys) > 1 and cek is None: raise InvalidAlgorithmForMultipleRecipientsMode(alg.name) if 'header' in preset: shared_header.update_protected(preset['header']) if isinstance(alg, JWEAlgorithmWithTagAwareKeyAgreement) and alg.key_size is not None: # For a JWE algorithm with tag-aware key agreement in case key agreement with key wrapping mode is used: # Defer key agreement with key wrapping until authentication tag is computed epks = [] for i in range(len(keys)): prep = alg.generate_keys_and_prepare_headers(enc, keys[i], sender_key, preset) if cek is None: cek = prep['cek'] epks.append(prep['epk']) recipients[i]['header'].update(prep['header']) else: # In any other case: # Keep the normal steps order defined by RFC 7516 for i in range(len(keys)): if isinstance(alg, JWEAlgorithmWithTagAwareKeyAgreement): wrapped = alg.wrap(enc, shared_header, keys[i], sender_key, preset) else: wrapped = alg.wrap(enc, shared_header, keys[i], preset) if cek is None: cek = wrapped['cek'] recipients[i]['encrypted_key'] = wrapped['ek'] if 'header' in wrapped: recipients[i]['header'].update(wrapped['header']) # step 4: Generate a random JWE Initialization Vector iv = enc.generate_iv() # step 5: Compute the Encoded Protected Header value # BASE64URL(UTF8(JWE Protected Header)). If the JWE Protected Header # is not present, let this value be the empty string. # Let the Additional Authenticated Data encryption parameter be # ASCII(Encoded Protected Header). However, if a JWE AAD value is # present, instead let the Additional Authenticated Data encryption # parameter be ASCII(Encoded Protected Header || '.' || BASE64URL(JWE AAD)). aad = json_b64encode(shared_header.protected) if shared_header.protected else b'' if jwe_aad is not None: aad += b'.' + urlsafe_b64encode(jwe_aad) aad = to_bytes(aad, 'ascii') # step 6: compress message if required if zip_alg: msg = zip_alg.compress(to_bytes(payload)) else: msg = to_bytes(payload) # step 7: perform encryption ciphertext, tag = enc.encrypt(msg, aad, iv, cek) if isinstance(alg, JWEAlgorithmWithTagAwareKeyAgreement) and alg.key_size is not None: # For a JWE algorithm with tag-aware key agreement in case key agreement with key wrapping mode is used: # Perform key agreement with key wrapping deferred at step 3 for i in range(len(keys)): wrapped = alg.agree_upon_key_and_wrap_cek(enc, shared_header, keys[i], sender_key, epks[i], cek, tag) recipients[i]['encrypted_key'] = wrapped['ek'] # step 8: build resulting message obj = OrderedDict() if shared_header.protected: obj['protected'] = to_unicode(json_b64encode(shared_header.protected)) if shared_header.unprotected: obj['unprotected'] = shared_header.unprotected for recipient in recipients: if not recipient['header']: del recipient['header'] recipient['encrypted_key'] = to_unicode(urlsafe_b64encode(recipient['encrypted_key'])) for member in set(recipient.keys()): if member not in {'header', 'encrypted_key'}: del recipient[member] obj['recipients'] = recipients if jwe_aad is not None: obj['aad'] = to_unicode(urlsafe_b64encode(jwe_aad)) obj['iv'] = to_unicode(urlsafe_b64encode(iv)) obj['ciphertext'] = to_unicode(urlsafe_b64encode(ciphertext)) obj['tag'] = to_unicode(urlsafe_b64encode(tag)) return obj
def serialize_compact(self, protected, payload, key): """Generate a JWE Compact Serialization. The JWE Compact Serialization represents encrypted content as a compact, URL-safe string. This string is: BASE64URL(UTF8(JWE Protected Header)) || '.' || BASE64URL(JWE Encrypted Key) || '.' || BASE64URL(JWE Initialization Vector) || '.' || BASE64URL(JWE Ciphertext) || '.' || BASE64URL(JWE Authentication Tag) Only one recipient is supported by the JWE Compact Serialization and it provides no syntax to represent JWE Shared Unprotected Header, JWE Per-Recipient Unprotected Header, or JWE AAD values. :param protected: A dict of protected header :param payload: A string/dict of payload :param key: Private key used to generate signature :return: byte """ # step 1: Prepare algorithms & key alg = self.get_header_alg(protected) enc = self.get_header_enc(protected) zip_alg = self.get_header_zip(protected) self._validate_private_headers(protected, alg) key = prepare_key(alg, protected, key) # self._post_validate_header(protected, algorithm) # step 2: Generate a random Content Encryption Key (CEK) # use enc_alg.generate_cek() in .wrap method # step 3: Encrypt the CEK with the recipient's public key wrapped = alg.wrap(enc, protected, key) cek = wrapped['cek'] ek = wrapped['ek'] if 'header' in wrapped: protected.update(wrapped['header']) # step 4: Generate a random JWE Initialization Vector iv = enc.generate_iv() # step 5: Let the Additional Authenticated Data encryption parameter # be ASCII(BASE64URL(UTF8(JWE Protected Header))) protected_segment = json_b64encode(protected) aad = to_bytes(protected_segment, 'ascii') # step 6: compress message if required if zip_alg: msg = zip_alg.compress(to_bytes(payload)) else: msg = to_bytes(payload) # step 7: perform encryption ciphertext, tag = enc.encrypt(msg, aad, iv, cek) return b'.'.join([ protected_segment, urlsafe_b64encode(ek), urlsafe_b64encode(iv), urlsafe_b64encode(ciphertext), urlsafe_b64encode(tag) ])