def test_aes_gcm(self): key = b'Sixteen byte key' plain_text = b'Attack at dawn' hdr = b'To your eyes only' nonce, mac, cipher_text = AESHandler.aes_gcm_encrypt( plain_text, hdr, key) decrypt_out = AESHandler.aes_gcm_decrypt(cipher_text, hdr, nonce, mac, key) self.assertEqual(plain_text, decrypt_out)
def test_aes_gcm_with_iv(self): key = b'Sixteen byte key' plain_text = b'Attack at dawn' hdr = b'To your eyes only' iv = Random.new().read(AES.block_size) mac, cipher_text = AESHandler.aes_gcm_encrypt_with_iv( plain_text, hdr, key, iv) decrypt_out = AESHandler.aes_gcm_decrypt_with_iv( cipher_text, hdr, mac, key, iv) self.assertEqual(plain_text, decrypt_out)
def decrypt_with_cbc_mode(cipher_text: bytes, private_key: bytes, iv: bytes, encode_g_tilde: bytes): if not isinstance(private_key, bytes): raise BotException(BotError.invalid_private_key) if len(private_key) != 32: raise BotException(BotError.invalid_private_key) str_g_tilde_x = encode_g_tilde[1:33] str_g_tilde_y = encode_g_tilde[33:65] g_tilde_x = string_to_number(str_g_tilde_x) g_tilde_y = string_to_number(str_g_tilde_y) g_tilde = Point(SECP256k1.curve, g_tilde_x, g_tilde_y, SECP256k1.order) h_tilde = g_tilde * SigningKey.from_string(string=private_key, curve=SECP256k1).privkey.secret_multiplier seed = b''.join([encode_g_tilde, number_to_string(h_tilde.x(), SECP256k1.order)]) aes_key = pbkdf2(seed, 32) plain_text = AESHandler.aes_cbc_decrypt(cipher_text, iv, aes_key) return plain_text
def encrypt_with_cbc_mode(plain_text: bytes, public_key: bytes) -> (bytes, bytes, bytes): if not isinstance(public_key, bytes): raise BotException(BotError.invalid_public_key) if len(public_key) != 64: raise BotException(BotError.invalid_public_key) r = randint(1, SECP256k1.order) g_tilde = r * SECP256k1.generator h_tilde = r * VerifyingKey.from_string(string=public_key, curve=SECP256k1).pubkey.point str_g_tilde_x = number_to_string(g_tilde.x(), SECP256k1.order) str_g_tilde_y = number_to_string(g_tilde.y(), SECP256k1.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(), SECP256k1.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) return aes_iv, encode_g_tilde, cipher_text
def test_aes_ctr(self): key = b'Sixteen byte key' plain_text = b'Attack at dawn' nonce, cipher_text = AESHandler.aes_ctr_encrypt(plain_text, key) decrypt_out = AESHandler.aes_ctr_decrypt(cipher_text, nonce, key) self.assertEqual(plain_text, decrypt_out)