async def encrypt_wallet(self, password: str): """Encrypt wallet seed with password""" async with in_transaction() as conn: # If password is empty string then decrypted wallet if len(password.strip()) == 0: self.encrypted = False for a in await self.adhoc_accounts.all(): decrypted = SeedStorage.instnace().get_decrypted_seed( f"{self.id}:{a.address}") if decrypted is not None: a.private_key = decrypted await a.save(using_db=conn, update_fields=['private_key']) else: crypt = AESCrypt(password) encrypted = crypt.encrypt(self.seed) self.seed = encrypted self.encrypted = True for a in await self.adhoc_accounts.all(): a.private_key = crypt.encrypt(a.private_key_get()) await a.save(using_db=conn, update_fields=['private_key']) await self.save(using_db=conn, update_fields=['seed', 'encrypted'])
class TestAESCrypt(unittest.TestCase): def setUp(self): self.crypt1 = AESCrypt('mypassword') self.crypt2 = AESCrypt('someotherpassword') def test_encrypt_decrypt(self): """Test encryption and decryption""" some_string = "Some Random String to Encrypt" encrypted = self.crypt1.encrypt(some_string) self.assertNotEqual(encrypted, some_string) self.assertEqual(self.crypt1.decrypt(encrypted), some_string) with self.assertRaises(DecryptionError) as exc: self.crypt2.decrypt(encrypted)
async def adhoc_account_create(self, key: str, password: str = None) -> str: """Add an adhoc private key to the wallet, raise AccountAlreadyExists if it already exists""" pubkey = nanopy.ed25519_blake2b.publickey(bytes.fromhex(key)).hex() address = nanopy.account_get(pubkey) # See if address already exists a = await self.accounts.filter(address=address).first() if a is None: a = await self.adhoc_accounts.filter(address=address).first() if a is not None: raise AccountAlreadyExists(a) # Create it crypt = None if password is not None: crypt = AESCrypt(password) a = adhoc_acct.AdHocAccount( wallet=self, private_key=crypt.encrypt(key) if crypt is not None else key, address=address) await a.save() return address