Skip to content

Commit

Permalink
Show clearer warnings when try to open encrypted database
Browse files Browse the repository at this point in the history
  • Loading branch information
Cryp Toon committed Feb 25, 2024
1 parent 5905559 commit 2c6a3c5
Show file tree
Hide file tree
Showing 3 changed files with 19 additions and 3 deletions.
4 changes: 2 additions & 2 deletions bitcoinlib/db.py
Original file line number Diff line number Diff line change
Expand Up @@ -188,9 +188,9 @@ def process_bind_param(self, value, dialect):

def process_result_value(self, value, dialect):
if value is None or self.key is None or not (DB_FIELD_ENCRYPTION_KEY or DB_FIELD_ENCRYPTION_PASSWORD):
if isinstance(value, bytes):
raise ValueError("Data is encrypted please provide key in environment")
return value
# if value.startswith('\\x'):
# value = bytes.fromhex(value[2:])
return aes_decrypt(value, self.key).decode('utf8')


Expand Down
6 changes: 5 additions & 1 deletion bitcoinlib/encoding.py
Original file line number Diff line number Diff line change
Expand Up @@ -946,7 +946,11 @@ def aes_decrypt(encrypted_data, key):
ct = encrypted_data[:-16]
tag = encrypted_data[-16:]
cipher2 = AES.new(key, AES.MODE_SIV)
return cipher2.decrypt_and_verify(ct, tag)
try:
res = cipher2.decrypt_and_verify(ct, tag)
except ValueError as e:
raise EncodingError("Could not decrypt value (password incorrect?): %s" % e)
return res


def bip38_decrypt(encrypted_privkey, password):
Expand Down
12 changes: 12 additions & 0 deletions tests/test_security.py
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@
from bitcoinlib.db import BCL_DATABASE_DIR
from bitcoinlib.wallets import Wallet
from bitcoinlib.keys import HDKey
from bitcoinlib.encoding import EncodingError


try:
Expand Down Expand Up @@ -117,6 +118,17 @@ def test_security_wallet_field_encryption_password(self):
self.assertEqual(encrypted_main_key_private.hex(), pk_enc_hex)
self.assertNotEqual(encrypted_main_key_private, HDKey(pk).private_byte)

def test_security_encrypted_db_incorrect_password(self):
db = os.path.join(os.path.dirname(os.path.realpath(__file__)), 'bitcoinlib_encrypted.sqlite')
self.assertRaisesRegex(EncodingError, "Could not decrypt value \(password incorrect\?\): MAC check failed",
Wallet, 'wlt-encryption-test', db_uri=db)

def test_security_encrypted_db_no_password(self):
db = os.path.join(os.path.dirname(os.path.realpath(__file__)), 'bitcoinlib_encrypted.sqlite')
if os.environ.get('DB_FIELD_ENCRYPTION_PASSWORD') or os.environ.get('DB_FIELD_ENCRYPTION_KEY'):
self.skipTest("This test only runs when no encryption keys are provided")
self.assertRaisesRegex(ValueError, "Data is encrypted please provide key in environment",
Wallet, 'wlt-encryption-test', db_uri=db)

if __name__ == '__main__':
main()

0 comments on commit 2c6a3c5

Please sign in to comment.