Alex Gaynor | bd458ae | 2013-10-16 11:59:30 -0700 | [diff] [blame] | 1 | import binascii |
| 2 | import os |
| 3 | |
| 4 | import pytest |
| 5 | |
| 6 | from cryptography.bindings import openssl |
| 7 | from cryptography.primitives.block import BlockCipher |
| 8 | |
| 9 | |
Alex Gaynor | 016eed1 | 2013-10-16 14:16:04 -0700 | [diff] [blame^] | 10 | def generate_encrypt_test(param_loader, path, file_names, cipher_factory, |
| 11 | mode_factory, only_if=lambda api: True): |
Alex Gaynor | bd458ae | 2013-10-16 11:59:30 -0700 | [diff] [blame] | 12 | def test_encryption(self): |
| 13 | for api in [openssl.api]: |
| 14 | if not only_if(api): |
| 15 | yield encrypt_skipped |
| 16 | else: |
| 17 | for file_name in file_names: |
Alex Gaynor | 016eed1 | 2013-10-16 14:16:04 -0700 | [diff] [blame^] | 18 | for params in param_loader(os.path.join(path, file_name)): |
Alex Gaynor | bd458ae | 2013-10-16 11:59:30 -0700 | [diff] [blame] | 19 | yield encrypt_test, api, cipher_factory, mode_factory, params |
| 20 | return test_encryption |
| 21 | |
| 22 | |
| 23 | def encrypt_test(api, cipher_factory, mode_factory, params): |
| 24 | plaintext = params.pop("plaintext") |
| 25 | ciphertext = params.pop("ciphertext") |
| 26 | cipher = BlockCipher( |
| 27 | cipher_factory(**params), |
| 28 | mode_factory(**params), |
| 29 | api |
| 30 | ) |
| 31 | actual_ciphertext = cipher.encrypt(binascii.unhexlify(plaintext)) |
| 32 | actual_ciphertext += cipher.finalize() |
| 33 | assert binascii.hexlify(actual_ciphertext) == ciphertext |
| 34 | |
| 35 | |
| 36 | def encrypt_skipped(): |
| 37 | pytest.skip("because reasons") |