def test_mac_direct_encoding(setup_mac_tests: tuple) -> None: _, test_input, test_output, test_intermediate, fail = setup_mac_tests mac = MacMessage( phdr=test_input['mac'].get('protected', {}), uhdr=test_input['mac'].get('unprotected', {}), payload=test_input.get('plaintext', '').encode('utf-8'), external_aad=unhexlify(test_input['mac'].get("external", b''))) assert mac._mac_structure == unhexlify(test_intermediate["ToMac_hex"]) alg = extract_alg(test_input["mac"]) # set up the CEK and KEK cek = create_cose_key(SymmetricKey, test_input['mac']['recipients'][0]['key'], alg=alg, usage=KeyOps.MAC_CREATE) kek = create_cose_key(SymmetricKey, test_input['mac']['recipients'][0]['key'], alg=CoseAlgorithms.DIRECT.id, usage=KeyOps.WRAP) assert cek.k == unhexlify(test_intermediate["CEK_hex"]) recipient = test_input["mac"]["recipients"][0] recipient = CoseRecipient( phdr=recipient.get('protected', {}), uhdr=recipient.get('unprotected', {}), payload=cek.k) mac.recipients.append(recipient) # verify encoding (with automatic tag computation) if fail: assert mac.encode(cek, mac_params=[RcptParams(key=kek)]) != unhexlify(test_output) else: assert mac.encode(cek, mac_params=[RcptParams(key=kek)]) == unhexlify(test_output)
def compute_tag(self, *args, **kwargs) -> bytes: target_algorithm = self.get_attr(headers.Algorithm) r_types = CoseRecipient.verify_recipients(self.recipients) if DirectEncryption in r_types: # key should already be known payload = super(MacMessage, self).compute_tag() elif DirectKeyAgreement in r_types: self.key = self.recipients[0].compute_cek(target_algorithm, "encrypt") payload = super(MacMessage, self).compute_tag() elif KeyWrap in r_types or KeyAgreementWithKeyWrap in r_types: key_bytes = os.urandom( self.get_attr(headers.Algorithm).get_key_length()) for r in self.recipients: if r.payload == b'': r.payload = key_bytes else: key_bytes = r.payload r.encrypt(target_algorithm) self.key = SymmetricKey(k=key_bytes, alg=target_algorithm, key_ops=[MacCreateOp]) payload = super(MacMessage, self).compute_tag() else: raise CoseException('Unsupported COSE recipient class') return payload
def from_cose_obj(cls, cose_obj: list, *args, **kwargs) -> 'EncMessage': msg = super().from_cose_obj(cose_obj) try: msg.recipients = [CoseRecipient.create_recipient(r, context='Enc_Recipient') for r in cose_obj.pop(0)] except (IndexError, ValueError): msg.recipients = [] return msg
def from_cose_obj(cls, cose_obj: list) -> 'EncMessage': msg = super().from_cose_obj(cose_obj) try: msg.recipients = [ CoseRecipient.from_recipient_obj(r) for r in cose_obj.pop(0) ] except (IndexError, ValueError): msg.recipients = [] return msg
def decrypt(self, recipient: 'Recipient', *args, **kwargs) -> bytes: target_algorithm = self.get_attr(headers.Algorithm) # check if recipient exists if not CoseRecipient.has_recipient(recipient, self.recipients): raise CoseException(f"Cannot find recipient: {recipient}") r_types = CoseRecipient.verify_recipients(self.recipients) if DirectEncryption in r_types: # key should already be known payload = super(EncMessage, self).decrypt() elif DirectKeyAgreement in r_types or KeyWrap in r_types or KeyAgreementWithKeyWrap in r_types: self.key = recipient.compute_cek(target_algorithm, "decrypt") payload = super(EncMessage, self).decrypt() else: raise CoseException('Unsupported COSE recipient class') return payload
def from_cose_obj(cls, cose_obj) -> 'MacMessage': msg = super().from_cose_obj(cose_obj) msg.auth_tag = cose_obj.pop(0) try: msg.recipients = [ CoseRecipient.from_recipient_obj(r) for r in cose_obj.pop(0) ] except (IndexError, ValueError): msg.recipients = None return msg
def test_encrypt_x25519_wrap_decode( setup_encrypt_x25519_direct_tests: tuple) -> None: _, test_input, test_output, test_intermediate, fail = setup_encrypt_x25519_direct_tests # DECODING # parse message and test for headers md: EncMessage = CoseMessage.decode(unhexlify(test_output)) assert md.phdr == extract_phdr(test_input, 'enveloped') assert md.uhdr == extract_uhdr(test_input, 'enveloped', 1) # check for external data and verify internal _enc_structure md.external_aad = unhexlify(test_input['enveloped'].get('external', b'')) assert md._enc_structure == unhexlify(test_intermediate['AAD_hex']) recipient = test_input['enveloped']['recipients'][0] assert md.recipients[0].phdr == recipient.get('protected', {}) # do not verify unprotected header since it contains the ephemeral public key of the sender # assert m.recipients[0].uhdr == rcpt.get('unprotected', {}) rcvr_skey, sender_key = setup_okp_receiver_keys( recipient, md.recipients[0].uhdr.get(CoseHeaderKeys.EPHEMERAL_KEY)) # create context KDF u = PartyInfo(nonce=unhexlify(test_input['rng_stream'][0]) ) if "sender_key" in recipient else PartyInfo() s = SuppPubInfo( len(test_intermediate['CEK_hex']) * 4, md.recipients[0].encode_phdr()) kdf_ctx = CoseKDFContext(md.phdr[CoseHeaderKeys.ALG], u, PartyInfo(), s) assert kdf_ctx.encode() == unhexlify( test_intermediate['recipients'][0]['Context_hex']) secret, kek_bytes = CoseRecipient.derive_kek(rcvr_skey, sender_key, context=kdf_ctx, expose_secret=True) assert secret == unhexlify( test_intermediate['recipients'][0]['Secret_hex']) assert kek_bytes == unhexlify(test_intermediate['CEK_hex']) alg = extract_alg(test_input['enveloped']) cek = SymmetricKey(k=kek_bytes) nonce = extract_nonce(test_input, 1) assert md.decrypt(nonce=nonce, alg=alg, key=cek) == test_input['plaintext'].encode('utf-8')
def test_encrypt_encoding(setup_encrypt_tests: tuple) -> None: title, test_input, test_output, test_intermediate, fail = setup_encrypt_tests alg = extract_alg(test_input["enveloped"]) nonce = extract_nonce( test_input, 0) if extract_nonce(test_input, 0) != b'' else extract_unsent_nonce( test_input, "enveloped") m = EncMessage(phdr=extract_phdr(test_input, 'enveloped'), uhdr=extract_uhdr(test_input, 'enveloped'), payload=test_input['plaintext'].encode('utf-8'), external_aad=unhexlify(test_input['enveloped'].get( 'external', b''))) # check for external data and verify internal _enc_structure assert m._enc_structure == unhexlify(test_intermediate['AAD_hex']) # set up the CEK and KEK cek = create_cose_key(SymmetricKey, test_input['enveloped']['recipients'][0]['key'], alg=alg, usage=KeyOps.ENCRYPT) kek = create_cose_key(SymmetricKey, test_input['enveloped']['recipients'][0]['key'], alg=CoseAlgorithms.DIRECT.id, usage=KeyOps.WRAP) # create the recipients r_info = test_input['enveloped']['recipients'][0] recipient = CoseRecipient(phdr=r_info.get('protected', {}), uhdr=r_info.get('unprotected', {}), payload=cek.k) m.recipients.append(recipient) # verify encoding (with automatic encryption) if fail: assert m.encode(key=cek, nonce=nonce, enc_params=[RcptParams( key=kek)]) != unhexlify(test_output) else: # test encoding/protection assert m.encode(key=cek, nonce=nonce, enc_params=[RcptParams(key=kek) ]) == unhexlify(test_output)
def encode(self, nonce: bytes, key: SymmetricKey, alg: Optional[CoseAlgorithms] = None, enc_params: Optional[List[RcptParams]] = None, tagged: bool = True, encrypt: bool = True) -> bytes: """ Encodes and protects the COSE_Encrypt message """ # encode/encrypt the base fields if encrypt: message = [ self.encode_phdr(), self.encode_uhdr(), self.encrypt(nonce=nonce, key=key, alg=alg) ] else: message = [self.encode_phdr(), self.encode_uhdr(), self.payload] if enc_params is None: enc_params = [] if len(self.recipients) == len(enc_params): if len(enc_params) > 0: message.append( CoseRecipient.recursive_encode(self.recipients, enc_params)) else: raise ValueError( "List with cryptographic parameters should have the same length as the recipient list." ) if tagged: message = cbor2.dumps(cbor2.CBORTag(self.cbor_tag, message), default=self._special_cbor_encoder) else: message = cbor2.dumps(message, default=self._special_cbor_encoder) return message
def test_encrypt_ecdh_wrap_decode(setup_encrypt_ecdh_wrap_tests: tuple): _, test_input, test_output, test_intermediate, fail = setup_encrypt_ecdh_wrap_tests # DECODING # parse message and test for headers md: EncMessage = CoseMessage.decode(unhexlify(test_output)) assert md.phdr == extract_phdr(test_input, 'enveloped') assert md.uhdr == extract_uhdr(test_input, 'enveloped', 1) # check for external data and verify internal _enc_structure md.external_aad = unhexlify(test_input['enveloped'].get('external', b'')) assert md._enc_structure == unhexlify(test_intermediate['AAD_hex']) recipient = test_input['enveloped']['recipients'][0] assert md.recipients[0].phdr == recipient.get('protected', {}) # do not verify unprotected header since it contains the ephemeral public key of the sender # assert m.recipients[0].uhdr == rcpt.get('unprotected', {}) rcvr_skey, sender_key = setup_ec_receiver_keys( recipient, md.recipients[0].uhdr.get(CoseHeaderKeys.EPHEMERAL_KEY)) # create context KDF s = SuppPubInfo( len(test_intermediate['recipients'][0]['KEK_hex']) * 4, md.recipients[0].encode_phdr()) if md.recipients[0].phdr[CoseHeaderKeys.ALG] in { CoseAlgorithms.ECDH_ES_A192KW, CoseAlgorithms.ECDH_SS_A192KW }: kdf_ctx = CoseKDFContext(CoseAlgorithms.A192KW, PartyInfo(), PartyInfo(), s) elif md.recipients[0].phdr[CoseHeaderKeys.ALG] in { CoseAlgorithms.ECDH_ES_A128KW, CoseAlgorithms.ECDH_SS_A128KW }: kdf_ctx = CoseKDFContext(CoseAlgorithms.A128KW, PartyInfo(), PartyInfo(), s) elif md.recipients[0].phdr[CoseHeaderKeys.ALG] in { CoseAlgorithms.ECDH_ES_A256KW, CoseAlgorithms.ECDH_SS_A256KW }: kdf_ctx = CoseKDFContext(CoseAlgorithms.A256KW, PartyInfo(), PartyInfo(), s) else: raise ValueError("Missed an algorithm?") assert kdf_ctx.encode() == unhexlify( test_intermediate['recipients'][0]['Context_hex']) secret, kek = CoseRecipient.derive_kek(rcvr_skey, sender_key, context=kdf_ctx, expose_secret=True) assert secret == unhexlify( test_intermediate['recipients'][0]['Secret_hex']) assert kek == unhexlify(test_intermediate['recipients'][0]['KEK_hex']) r1 = md.recipients[0] cek = r1.decrypt(key=SymmetricKey(k=kek, alg=r1.phdr[CoseHeaderKeys.ALG])) assert cek == unhexlify(test_intermediate['CEK_hex']) cek = SymmetricKey(k=cek, alg=extract_alg(test_input["enveloped"])) pld = md.decrypt(key=cek, nonce=extract_nonce(test_input, 1)) assert pld == test_input['plaintext'].encode('utf-8')
def test_encrypt_ecdh_direct_decode_encode( setup_encrypt_ecdh_direct_tests: tuple) -> None: title, test_input, test_output, test_intermediate, fail = setup_encrypt_ecdh_direct_tests # DECODING # parse message and test for headers md: EncMessage = CoseMessage.decode(unhexlify(test_output)) assert md.phdr == extract_phdr(test_input, 'enveloped') assert md.uhdr == extract_uhdr(test_input, 'enveloped', 1) # check for external data and verify internal _enc_structure md.external_aad = unhexlify(test_input['enveloped'].get('external', b'')) assert md._enc_structure == unhexlify(test_intermediate['AAD_hex']) # verify the receiver and set up the keying material recipient = test_input['enveloped']['recipients'][0] assert md.recipients[0].phdr == recipient.get('protected', {}) # do not verify unprotected header since it contains the ephemeral public key of the sender # assert m.recipients[0].uhdr == rcpt.get('unprotected', {}) rcvr_skey, sender_key = setup_ec_receiver_keys( recipient, md.recipients[0].uhdr.get(CoseHeaderKeys.EPHEMERAL_KEY)) # create context KDF v = PartyInfo() u = PartyInfo(nonce=unhexlify(test_input['rng_stream'][0]) ) if "sender_key" in recipient else PartyInfo() s = SuppPubInfo( len(test_intermediate['CEK_hex']) * 4, md.recipients[0].encode_phdr()) kdf_ctx = CoseKDFContext(md.phdr[CoseHeaderKeys.ALG], u, v, s) assert kdf_ctx.encode() == unhexlify( test_intermediate['recipients'][0]['Context_hex']) secret, kek_bytes = CoseRecipient.derive_kek(rcvr_skey, sender_key, context=kdf_ctx, expose_secret=True) assert secret == unhexlify( test_intermediate['recipients'][0]['Secret_hex']) assert kek_bytes == unhexlify(test_intermediate['CEK_hex']) alg = extract_alg(test_input['enveloped']) cek = SymmetricKey(k=kek_bytes) nonce = extract_nonce(test_input, 1) assert md.decrypt(nonce=nonce, alg=alg, key=cek) == test_input['plaintext'].encode('utf-8') # ENCODING me = EncMessage(phdr=test_input['enveloped'].get("protected", {}), uhdr=test_input['enveloped'].get("unprotected", {}), payload=test_input['plaintext'].encode('utf-8')) if 'rng_stream' in test_input: me.uhdr_update( {CoseHeaderKeys.IV: unhexlify(test_input['rng_stream'][1])}) # Set up recipients and keys recipient = test_input['enveloped']['recipients'][0] if 'sender_key' in recipient: r1 = CoseRecipient(phdr=recipient.get('protected', {})) r1.uhdr_update( {CoseHeaderKeys.STATIC_KEY: sender_key.encode('crv', 'x', 'y')}) r1.uhdr_update(recipient.get('unprotected', {})) r1.uhdr_update({ CoseHeaderKeys.PARTY_U_NONCE: unhexlify(test_input['rng_stream'][0]) }) else: r1 = CoseRecipient(phdr=recipient.get('protected', {})) r1.uhdr_update( {CoseHeaderKeys.EPHEMERAL_KEY: sender_key.encode('crv', 'x', 'y')}) r1.uhdr_update(recipient.get('unprotected', {})) # append the first and only recipient me.recipients.append(r1) # set up cek cek = SymmetricKey(k=kek_bytes, alg=alg) kek = SymmetricKey(k=kek_bytes, alg=CoseAlgorithms.DIRECT.id) # without sorting probably does not match because the order of the recipient elements is not the same assert sorted( me.encode(key=cek, nonce=nonce, enc_params=[RcptParams(key=kek) ])) == sorted(unhexlify(test_output))