Пример #1
0
def decrypt(cipher, mode, key, iv, encrypted_content):
    if cipher == 'aes':
        symkey = AES(key)
    elif cipher == 'tripledes':
        symkey = TripleDES(key)
    else:
        symkey =TripleDES(key)

    cipher = Cipher(symkey, mode_for_type(mode_type=mode, iv_or_tweak=iv), backend=default_backend())
    decryptor = cipher.decryptor()

    return decryptor.update(encrypted_content) + decryptor.finalize()
Пример #2
0
    def _encrypt_data(
            self, data: bytes) -> Tuple[Union[TripleDES, AES], bytes, bytes]:
        """Build the ciphertext of the ``messageData``.

        Args:
              data (bytes): Data to encrypt as the ``messageData`` of the SCEP Request

        Returns:
              Tuple of 3DES key, IV, and cipher text encrypted with 3DES
        """
        symkey, iv = None, None

        # TODO: this is horribad and needs abstraction
        if self._encryption_algorithm_id.native == 'tripledes_3key':
            symkey = TripleDES(os.urandom(8))
            iv = os.urandom(8)
        elif self._encryption_algorithm_id.native == 'aes128_cbc':
            symkey = AES(os.urandom(16))
            iv = os.urandom(16)

        cipher = Cipher(symkey, modes.CBC(iv), backend=default_backend())
        encryptor = cipher.encryptor()

        if self._encryption_algorithm_id.native == 'tripledes_3key':
            padder = PKCS7(TripleDES.block_size).padder()
        elif self._encryption_algorithm_id.native == 'aes128_cbc':
            padder = PKCS7(AES.block_size).padder()

        padded = padder.update(data)
        padded += padder.finalize()

        ciphertext = encryptor.update(padded) + encryptor.finalize()

        return symkey, iv, ciphertext
Пример #3
0
    def get_decrypted_envelope_data(self, certificate: x509.Certificate,
                                    key: rsa.RSAPrivateKey) -> bytes:
        """Decrypt the encrypted envelope data:
        
        Decrypt encrypted_key using public key of CA
        encrypted_key is available at content.recipient_infos[x].encrypted_key
        algo is content.recipient_infos[x].key_encryption_algorithm
        at the moment this is RSA
        """
        encap = self.encap_content_info
        ct = encap['content_type'].native
        print(ct)
        recipient_info = encap['content']['recipient_infos'][0]

        encryption_algo = recipient_info.chosen[
            'key_encryption_algorithm'].native
        encrypted_key = recipient_info.chosen['encrypted_key'].native

        assert encryption_algo['algorithm'] == 'rsa'

        plain_key = key.decrypt(
            encrypted_key,
            padding=asympad.PKCS1v15(),
        )

        # Now we have the plain key, we can decrypt the encrypted data
        encrypted_contentinfo = encap['content']['encrypted_content_info']
        print('encrypted content type: {}'.format(
            encrypted_contentinfo['content_type'].native))

        algorithm = encrypted_contentinfo[
            'content_encryption_algorithm']  #: EncryptionAlgorithm
        encrypted_content_bytes = encrypted_contentinfo[
            'encrypted_content'].native

        symkey = None

        if algorithm.encryption_cipher == 'aes':
            symkey = AES(plain_key)
            print('cipher AES')
        elif algorithm.encryption_cipher == 'tripledes':
            symkey = TripleDES(plain_key)
            print('cipher 3DES')
        else:
            print('Dont understand encryption cipher: ',
                  algorithm.encryption_cipher)

        print('key length: ', algorithm.key_length)
        print('enc mode: ', algorithm.encryption_mode)

        cipher = Cipher(symkey,
                        modes.CBC(algorithm.encryption_iv),
                        backend=default_backend())
        decryptor = cipher.decryptor()

        return decryptor.update(encrypted_content_bytes) + decryptor.finalize()
Пример #4
0
    def test_3des_generate(self, backend, params):
        key1 = params["key1"]
        key2 = params["key2"]
        key3 = params["key3"]

        key = key1 + key2 + key3

        message = params["message"]
        output = params["output"]

        cmac = CMAC(TripleDES(binascii.unhexlify(key)), backend)
        cmac.update(binascii.unhexlify(message))
        assert binascii.hexlify(cmac.finalize()) == output
Пример #5
0
    def test_3des_verify(self, backend, params):
        key1 = params["key1"]
        key2 = params["key2"]
        key3 = params["key3"]

        key = key1 + key2 + key3

        message = params["message"]
        output = params["output"]

        cmac = CMAC(TripleDES(binascii.unhexlify(key)), backend)
        cmac.update(binascii.unhexlify(message))
        assert cmac.verify(binascii.unhexlify(output)) is None
Пример #6
0
def encrypt_with_key_and_iv_tripledes_cbc(key: bytes, iv: bytes,
                                          msg: bytes) -> bytes:
    from cryptography.hazmat.primitives.ciphers import Cipher
    from cryptography.hazmat.primitives.ciphers.algorithms import TripleDES
    from cryptography.hazmat.primitives.ciphers.modes import CBC
    from cryptography.hazmat.backends import default_backend

    tripledes_cbc_cipher = Cipher(TripleDES(key),
                                  mode=CBC(iv),
                                  backend=default_backend())
    tripledes_cbc_encryptor = tripledes_cbc_cipher.encryptor()

    final = tripledes_cbc_encryptor.update(msg)
    final += tripledes_cbc_encryptor.finalize()

    return final
Пример #7
0
def decrypt_smime_content(payload: bytes, key: rsa.RSAPrivateKey) -> bytes:
    content_info = ContentInfo.load(payload)

    assert content_info['content_type'].native == 'enveloped_data'
    content: EnvelopedData = content_info['content']

    matching_recipient = content['recipient_infos'][0]

    # Need to see if we hold the key for any valid recipient.
    # for recipient_info in content['recipient_infos']:
    #     assert recipient_info.name == 'ktri'  # Only support KeyTransRecipientInfo
    #     ktri: KeyTransRecipientInfo = recipient_info.chosen
    #     recipient_id: RecipientIdentifier = ktri['rid']
    #     assert recipient_id.name == 'issuer_and_serial_number'  # Only support IssuerAndSerialNumber
    #     matching_recipient = recipient_info

    encryption_algo = matching_recipient.chosen['key_encryption_algorithm'].native
    encrypted_key = matching_recipient.chosen['encrypted_key'].native

    assert encryption_algo['algorithm'] == 'rsa'

    # Get the content key
    plain_key = key.decrypt(
        encrypted_key,
        padding=padding.PKCS1v15(),
    )

    # Now we have the plain key, we can decrypt the encrypted data
    encrypted_contentinfo = content['encrypted_content_info']

    algorithm: EncryptionAlgorithm = encrypted_contentinfo['content_encryption_algorithm']  #: EncryptionAlgorithm
    encrypted_content_bytes = encrypted_contentinfo['encrypted_content'].native

    symkey = None

    if algorithm.encryption_cipher == 'aes':
        symkey = AES(plain_key)
    elif algorithm.encryption_cipher == 'tripledes':
        symkey = TripleDES(plain_key)
    else:
        print('Dont understand encryption cipher: ', algorithm.encryption_cipher)

    cipher = Cipher(symkey, modes.CBC(algorithm.encryption_iv), backend=default_backend())
    decryptor = cipher.decryptor()

    decrypted_data = decryptor.update(encrypted_content_bytes) + decryptor.finalize()
    return decrypted_data
Пример #8
0
 def test_invalid_key_size(self):
     with pytest.raises(ValueError):
         TripleDES(binascii.unhexlify(b"0" * 12))
Пример #9
0
 def test_key_size(self, key):
     cipher = TripleDES(binascii.unhexlify(key))
     assert cipher.key_size == 192
Пример #10
0
 def test_invalid_key_type(self):
     with pytest.raises(TypeError, match="key must be bytes"):
         TripleDES(u"0" * 16)
Пример #11
0
class TestCMAC(object):
    @pytest.mark.supported(
        only_if=lambda backend: backend.cmac_algorithm_supported(AES(fake_key)
                                                                 ),
        skip_message="Does not support CMAC.",
    )
    @pytest.mark.parametrize("params", vectors_aes)
    def test_aes_generate(self, backend, params):
        key = params["key"]
        message = params["message"]
        output = params["output"]

        cmac = CMAC(AES(binascii.unhexlify(key)), backend)
        cmac.update(binascii.unhexlify(message))
        assert binascii.hexlify(cmac.finalize()) == output

    @pytest.mark.supported(
        only_if=lambda backend: backend.cmac_algorithm_supported(AES(fake_key)
                                                                 ),
        skip_message="Does not support CMAC.",
    )
    @pytest.mark.parametrize("params", vectors_aes)
    def test_aes_verify(self, backend, params):
        key = params["key"]
        message = params["message"]
        output = params["output"]

        cmac = CMAC(AES(binascii.unhexlify(key)), backend)
        cmac.update(binascii.unhexlify(message))
        assert cmac.verify(binascii.unhexlify(output)) is None

    @pytest.mark.supported(
        only_if=lambda backend: backend.cmac_algorithm_supported(
            TripleDES(fake_key)),
        skip_message="Does not support CMAC.",
    )
    @pytest.mark.parametrize("params", vectors_3des)
    def test_3des_generate(self, backend, params):
        key1 = params["key1"]
        key2 = params["key2"]
        key3 = params["key3"]

        key = key1 + key2 + key3

        message = params["message"]
        output = params["output"]

        cmac = CMAC(TripleDES(binascii.unhexlify(key)), backend)
        cmac.update(binascii.unhexlify(message))
        assert binascii.hexlify(cmac.finalize()) == output

    @pytest.mark.supported(
        only_if=lambda backend: backend.cmac_algorithm_supported(
            TripleDES(fake_key)),
        skip_message="Does not support CMAC.",
    )
    @pytest.mark.parametrize("params", vectors_3des)
    def test_3des_verify(self, backend, params):
        key1 = params["key1"]
        key2 = params["key2"]
        key3 = params["key3"]

        key = key1 + key2 + key3

        message = params["message"]
        output = params["output"]

        cmac = CMAC(TripleDES(binascii.unhexlify(key)), backend)
        cmac.update(binascii.unhexlify(message))
        assert cmac.verify(binascii.unhexlify(output)) is None

    @pytest.mark.supported(
        only_if=lambda backend: backend.cmac_algorithm_supported(AES(fake_key)
                                                                 ),
        skip_message="Does not support CMAC.",
    )
    def test_invalid_verify(self, backend):
        key = b"2b7e151628aed2a6abf7158809cf4f3c"
        cmac = CMAC(AES(key), backend)
        cmac.update(b"6bc1bee22e409f96e93d7e117393172a")

        with pytest.raises(InvalidSignature):
            cmac.verify(b"foobar")

    @pytest.mark.supported(
        only_if=lambda backend: backend.cipher_supported(ARC4(fake_key), None),
        skip_message="Does not support CMAC.",
    )
    def test_invalid_algorithm(self, backend):
        key = b"0102030405"
        with pytest.raises(TypeError):
            CMAC(ARC4(key), backend)

    @pytest.mark.supported(
        only_if=lambda backend: backend.cmac_algorithm_supported(AES(fake_key)
                                                                 ),
        skip_message="Does not support CMAC.",
    )
    def test_raises_after_finalize(self, backend):
        key = b"2b7e151628aed2a6abf7158809cf4f3c"
        cmac = CMAC(AES(key), backend)
        cmac.finalize()

        with pytest.raises(AlreadyFinalized):
            cmac.update(b"foo")

        with pytest.raises(AlreadyFinalized):
            cmac.copy()

        with pytest.raises(AlreadyFinalized):
            cmac.finalize()

        with pytest.raises(AlreadyFinalized):
            cmac.verify(b"")

    @pytest.mark.supported(
        only_if=lambda backend: backend.cmac_algorithm_supported(AES(fake_key)
                                                                 ),
        skip_message="Does not support CMAC.",
    )
    def test_verify_reject_unicode(self, backend):
        key = b"2b7e151628aed2a6abf7158809cf4f3c"
        cmac = CMAC(AES(key), backend)

        with pytest.raises(TypeError):
            cmac.update("")

        with pytest.raises(TypeError):
            cmac.verify("")

    @pytest.mark.supported(
        only_if=lambda backend: backend.cmac_algorithm_supported(AES(fake_key)
                                                                 ),
        skip_message="Does not support CMAC.",
    )
    def test_copy_with_backend(self, backend):
        key = b"2b7e151628aed2a6abf7158809cf4f3c"
        cmac = CMAC(AES(key), backend)
        cmac.update(b"6bc1bee22e409f96e93d7e117393172a")
        copy_cmac = cmac.copy()
        assert cmac.finalize() == copy_cmac.finalize()

    @pytest.mark.supported(
        only_if=lambda backend: backend.cmac_algorithm_supported(AES(fake_key)
                                                                 ),
        skip_message="Does not support CMAC.",
    )
    def test_buffer_protocol(self, backend):
        key = bytearray(b"2b7e151628aed2a6abf7158809cf4f3c")
        cmac = CMAC(AES(key), backend)
        cmac.update(b"6bc1bee22e409f96e93d7e117393172a")
        assert cmac.finalize() == binascii.unhexlify(
            b"a21e6e647bfeaf5ca0a5e1bcd957dfad")
Пример #12
0
 def test_invalid_key_type(self):
     with pytest.raises(TypeError, match="key must be bytes"):
         TripleDES("0" * 16)  # type: ignore[arg-type]