def encrypt(data): if encryption.is_encrypted(data): try: data = encryption.decrypt(data, key) except encryption.InvalidKeyException: raise ValueError("Attempt to re-encrypt file with an invalid key") return encryption.encrypt(data, key, padding)
def invalid_key_test(self): key1 = encryption.generate_key() key2 = encryption.generate_key() data = "test data 123" ciphertext = encryption.encrypt(data, key1) self.assertTrue(encryption.is_encrypted(ciphertext)) self.assertRaises(encryption.InvalidKeyException, lambda: encryption.decrypt(ciphertext, key2))
def decrypt(ciphertext): if not encryption.is_encrypted(ciphertext): return ciphertext try: plaintext = encryption.decrypt(ciphertext, key) nonlocal success success = True print_success("decrypted", path, "with", key) return plaintext except encryption.InvalidKeyException: return ciphertext
def assertEncrypted(self, path, keys): path = self.pi_path(path) with open(self.rel_path(path)) as f: encryption.decrypt(f.read(), keys[path])
def assertInverses(self, data, padding=None): key = encryption.generate_key() ciphertext = encryption.encrypt(data, key, padding) self.assertTrue(encryption.is_encrypted(ciphertext)) self.assertEqual(encryption.decrypt(ciphertext, key), data)