tAES: use PyCrypto if available - electrum - Electrum Bitcoin wallet HTML git clone https://git.parazyd.org/electrum DIR Log DIR Files DIR Refs DIR Submodules --- DIR commit 7e76e4ac556bdce1d3405f63db1e9db44a1bb013 DIR parent 5513a6454937d4c4b5c770a30a14c0fd45f33dc1 HTML Author: ThomasV <thomasv@electrum.org> Date: Tue, 28 Feb 2017 15:10:42 +0100 AES: use PyCrypto if available Diffstat: M lib/bitcoin.py | 41 ++++++++++++++++++++++++------- 1 file changed, 32 insertions(+), 9 deletions(-) --- DIR diff --git a/lib/bitcoin.py b/lib/bitcoin.py t@@ -74,19 +74,42 @@ TYPE_ADDRESS = 0 TYPE_PUBKEY = 1 TYPE_SCRIPT = 2 - # AES encryption +try: + from Crypto.Cipher import AES +except: + AES = None + def aes_encrypt_with_iv(key, iv, data): - aes_cbc = pyaes.AESModeOfOperationCBC(key, iv=iv) - aes = pyaes.Encrypter(aes_cbc) - e = aes.feed(data) + aes.feed() # empty aes.feed() appends pkcs padding - return e + if AES: + AES.block_size = 16 + AES.key_size = 32 + padlen = 16 - (len(data) % 16) + if padlen == 0: + padlen = 16 + data += chr(padlen) * padlen + e = AES.new(key, AES.MODE_CBC, iv).encrypt(data) + return e + else: + aes_cbc = pyaes.AESModeOfOperationCBC(key, iv=iv) + aes = pyaes.Encrypter(aes_cbc) + e = aes.feed(data) + aes.feed() # empty aes.feed() appends pkcs padding + return e def aes_decrypt_with_iv(key, iv, data): - aes_cbc = pyaes.AESModeOfOperationCBC(key, iv=iv) - aes = pyaes.Decrypter(aes_cbc) - s = aes.feed(data) + aes.feed() # empty aes.feed() strips pkcs padding - return s + if AES: + cipher = AES.new(key, AES.MODE_CBC, iv) + data = cipher.decrypt(data) + padlen = ord(data[-1]) + for i in data[-padlen:]: + if ord(i) != padlen: + raise InvalidPassword() + return data[0:-padlen] + else: + aes_cbc = pyaes.AESModeOfOperationCBC(key, iv=iv) + aes = pyaes.Decrypter(aes_cbc) + s = aes.feed(data) + aes.feed() # empty aes.feed() strips pkcs padding + return s def EncodeAES(secret, s): iv = bytes(os.urandom(16))