def test_wan_account_prepared_encrypt(acct, private_key, password, kdf, iterations, expected_decrypted_key, expected_kdf): account = acct.from_key(private_key) if kdf is None: encrypted = account.encrypt(password, iterations=iterations) else: encrypted = account.encrypt(password, kdf=kdf, iterations=iterations) assert encrypted['address'] == '2c7536e3605d9c16a7a3d7b1898e529396a65c23' assert encrypted['version'] == 3 assert encrypted['crypto']['kdf'] == expected_kdf if iterations is None: expected_iterations = get_default_work_factor_for_kdf(expected_kdf) else: expected_iterations = iterations if expected_kdf == 'pbkdf2': assert encrypted['crypto']['kdfparams']['c'] == expected_iterations elif expected_kdf == 'scrypt': assert encrypted['crypto']['kdfparams']['n'] == expected_iterations else: raise Exception( "test must be upgraded to confirm iterations with kdf %s" % expected_kdf) decrypted_key = acct.decrypt(encrypted, password) assert isinstance(decrypted_key, HexBytes) assert decrypted_key == expected_decrypted_key
def _create_v3_keyfile_json(message_to_encrypt, password, kdf="pbkdf2", work_factor=None): """ Encrypt message by a given password. Most of this code is copied from eth_key_file.key_file, removed address and is from json result. """ salt = Random.get_random_bytes(16) if work_factor is None: work_factor = get_default_work_factor_for_kdf(kdf) if kdf == 'pbkdf2': derived_key = _pbkdf2_hash( password, hash_name='sha256', salt=salt, iterations=work_factor, dklen=DKLEN, ) kdfparams = { 'c': work_factor, 'dklen': DKLEN, 'prf': 'hmac-sha256', 'salt': encode_hex_no_prefix(salt), } elif kdf == 'scrypt': derived_key = _scrypt_hash( password, salt=salt, buflen=DKLEN, r=SCRYPT_R, p=SCRYPT_P, n=work_factor, ) kdfparams = { 'dklen': DKLEN, 'n': work_factor, 'r': SCRYPT_R, 'p': SCRYPT_P, 'salt': encode_hex_no_prefix(salt), } else: raise NotImplementedError("KDF not implemented: {0}".format(kdf)) iv = big_endian_to_int(Random.get_random_bytes(16)) encrypt_key = derived_key[:16] ciphertext = encrypt_aes_ctr(message_to_encrypt, encrypt_key, iv) mac = keccak(derived_key[16:32] + ciphertext) return { 'crypto': { 'cipher': 'aes-128-ctr', 'cipherparams': { 'iv': encode_hex_no_prefix(int_to_big_endian(iv)), }, 'ciphertext': encode_hex_no_prefix(ciphertext), 'kdf': kdf, 'kdfparams': kdfparams, 'mac': encode_hex_no_prefix(mac), }, 'version': 3, }