def encrypt_with_cbc_mode(plain_text: bytes, public_key: bytes, iv: bytes = b'') -> (bytes, bytes, bytes): if not isinstance(public_key, bytes): raise SDKException( ErrorCode.other_error( 'the type of public key should be bytes.')) if len(public_key) != 33: raise SDKException( ErrorCode.other_error( 'the length of public key should be 33 bytes.')) if not (public_key.startswith(b'\x02') or public_key.startswith(b'\x03')): raise SDKException(ErrorCode.other_error('Invalid public key.')) public_key = ECIES.__uncompress_public_key(public_key) r = randint(1, NIST256p.order) g_tilde = r * NIST256p.generator h_tilde = r * VerifyingKey.from_string(string=public_key, curve=NIST256p).pubkey.point str_g_tilde_x = number_to_string(g_tilde.x(), NIST256p.order) str_g_tilde_y = number_to_string(g_tilde.y(), NIST256p.order) encode_g_tilde = b''.join([b'\x04', str_g_tilde_x, str_g_tilde_y]) str_h_tilde_x = number_to_string(h_tilde.x(), NIST256p.order) seed = b''.join([encode_g_tilde, str_h_tilde_x]) aes_key = pbkdf2(seed, 32) aes_iv, cipher_text = AESHandler.aes_cbc_encrypt( plain_text, aes_key, iv) return aes_iv, encode_g_tilde, cipher_text
def encrypt_with_cbc_mode(plain_text: bytes, public_key: bytes, iv: bytes = b'') -> (bytes, bytes, bytes): aes_key, encode_g_tilde = ECIES.generate_encrypt_aes_key(public_key) aes_iv, cipher_text = AESHandler.aes_cbc_encrypt( plain_text, aes_key, iv) return aes_iv, encode_g_tilde, cipher_text
def test_aes_cbc(self): key = b'Sixteen byte key' plain_text = b'Attack at dawn' iv, cipher_text = AESHandler.aes_cbc_encrypt(plain_text, key) decrypt_out = AESHandler.aes_cbc_decrypt(cipher_text, iv, key) self.assertEqual(plain_text, decrypt_out)