def _create_base_cipher(dict_parameters): """This method instantiates and returns a handle to a low-level base cipher. It will absorb named parameters in the process.""" use_aesni = dict_parameters.pop("use_aesni", True) try: key = dict_parameters.pop("key") except KeyError: raise TypeError("Missing 'key' parameter") if len(key) not in key_size: raise ValueError("Incorrect AES key length (%d bytes)" % len(key)) if use_aesni and _raw_aesni_lib: start_operation = _raw_aesni_lib.AESNI_start_operation stop_operation = _raw_aesni_lib.AESNI_stop_operation else: start_operation = _raw_aes_lib.AES_start_operation stop_operation = _raw_aes_lib.AES_stop_operation cipher = VoidPointer() result = start_operation(c_uint8_ptr(key), c_size_t(len(key)), cipher.address_of()) if result: raise ValueError("Error %X while instantiating the AES cipher" % result) return SmartPointer(cipher.get(), stop_operation)
def encrypt(self, plaintext): """Encrypt data with the key set at initialization. The data to encrypt can be broken up in two or more pieces and `encrypt` can be called multiple times. That is, the statement: >>> c.encrypt(a) + c.encrypt(b) is equivalent to: >>> c.encrypt(a+b) This function does not add any padding to the plaintext. :Parameters: plaintext : bytes/bytearray/memoryview The piece of data to encrypt. The length must be multiple of the cipher block length. :Return: the encrypted data, as a byte string. It is as long as *plaintext*. """ ciphertext = create_string_buffer(len(plaintext)) result = raw_ecb_lib.ECB_encrypt(self._state.get(), c_uint8_ptr(plaintext), ciphertext, c_size_t(len(plaintext))) if result: if result == 3: raise ValueError("Data must be aligned to block boundary in ECB mode") raise ValueError("Error %d while encrypting in ECB mode" % result) return get_raw_buffer(ciphertext)
def encrypt(self, plaintext): """Encrypt data with the key set at initialization. The data to encrypt can be broken up in two or more pieces and `encrypt` can be called multiple times. That is, the statement: >>> c.encrypt(a) + c.encrypt(b) is equivalent to: >>> c.encrypt(a+b) This function does not add any padding to the plaintext. :Parameters: plaintext : bytes/bytearray/memoryview The piece of data to encrypt. The length must be multiple of the cipher block length. :Return: the encrypted data, as a byte string. It is as long as *plaintext*. """ ciphertext = create_string_buffer(len(plaintext)) result = raw_ecb_lib.ECB_encrypt(self._state.get(), c_uint8_ptr(plaintext), ciphertext, c_size_t(len(plaintext))) if result: if result == 3: raise ValueError( "Data must be aligned to block boundary in ECB mode") raise ValueError("Error %d while encrypting in ECB mode" % result) return get_raw_buffer(ciphertext)