def stealth_generate(filename): #Check to see if file is valid and does not already exist if type(filename) != str or len(filename) == 0: print("Stealth Address Generation Failed!") print("Please enter valid filename!") return if os.path.exists(filename): print("Stealth Address Generation Failed!") print("File \"" + filename + "\" already exists!") return #Get password for new keypair password = getpass() #Generate private keys print("Generating stealth address key pair...", end="") rng = SystemRandom() scan_key = (rng.getrandbits(256) % secp256k1.N).to_bytes(32, "big") pub_scan_key = secp256k1.privtopub(scan_key) js_scan = create_keyfile_json(scan_key, bytes(password, 'utf')) del scan_key spend_key = (rng.getrandbits(256) % secp256k1.N).to_bytes(32, "big") pub_spend_key = secp256k1.privtopub(spend_key) js_spend = create_keyfile_json(spend_key, bytes(password, 'utf')) del spend_key del password #Calculate Stealth Address and write to file with key pairs stealth_address = int.from_bytes( GetStealthAddressFromKeys(pub_scan_key, pub_spend_key), 'big') print("DONE!") print("New Stealth Address: " + hex(stealth_address)) print("Writing keystore file \"" + filename + "\"...", end="") with open(filename, mode='w') as file: js = "{\"stealth_address\":\"" + hex(stealth_address) + "\"," js += "\"scan_key\":" file.write(js) json.dump(js_scan, file) js = ",\"spend_key\":" file.write(js) json.dump(js_spend, file) js = "}" file.write(js) print("Done!")
def save(self, path: str, password: str): """Stores data of an instance of a derived wallet class on the file path with your password. :param path: File path of the keystore file. type(str) :param password: Password for the keystore file. Password must include alphabet character, number, and special character. type(str) """ try: if os.path.isfile(path): raise KeyStoreException("File already exists") keystore: dict = create_keyfile_json( self._private_key, password.encode("utf-8"), iterations=16384, kdf="scrypt", ) keystore["address"] = str(self._address) keystore["coinType"] = "icx" # validate the contents of a keystore file. if not is_keystore_valid(keystore): raise KeyStoreException("Invalid keystore") with open(path, "wt") as f: text: str = json.dumps(keystore) f.write(text) except PermissionError: raise KeyStoreException("Not enough permission") except FileNotFoundError: raise KeyStoreException("File not found") except IsADirectoryError: raise KeyStoreException("Invalid directory")
def new(cls, password: bytes, key: bytes = None, uuid=None, path=None, iterations=None): """ Create a new account. Note that this creates the account in memory and does not store it on disk. :param password: the password used to encrypt the private key :param key: the private key, or `None` to generate a random one :param uuid: an optional id """ if key is None: account = eth_account.Account.create() key = account.privateKey # [NOTE]: key and password should be bytes password = str.encode(password) # encrypted = eth_account.Account.encrypt(account.privateKey, password) keystore = create_keyfile_json(key, password, iterations=iterations) keystore['id'] = uuid return Account(keystore, password, path)
def create_wallet_by_private_key(password, hex_private_key=None): """ create wallet without keystore file :param hex_private_key: the private key with a hexadecimal number :param password :return: Instance of Wallet class. """ try: signer = IcxSigner( bytes.fromhex(hex_private_key) if hex_private_key else None, True if hex_private_key else None) key_store_contents = create_keyfile_json(signer.private_key_bytes, bytes(password, 'utf-8'), iterations=262144) key_store_contents['address'] = "hx" + signer.address.hex() key_store_contents['coinType'] = 'icx' wallet = Wallet(key_store_contents) return_value = (wallet, signer.private_key_bytes.hex()) return return_value except TypeError: raise TypeError
def create_keystore_file_of_wallet(keystore_file_path, password): """ create both a wallet and a keystore file :param keystore_file_path: File path for the keystore file of the wallet. :param password: Password including alphabet character, number, and special character. :return: Instance of Wallet class. """ if not validate_password(password): raise PasswordIsNotAcceptable try: signer = IcxSigner() byte_private_key = signer.private_key_bytes key_store_contents = create_keyfile_json(byte_private_key, bytes(password, 'utf-8'), iterations=262144) key_store_contents['address'] = "hx" + signer.address.hex() key_store_contents['coinType'] = 'icx' json_string_keystore_data = json.dumps(key_store_contents) store_wallet(keystore_file_path, json_string_keystore_data) wallet = Wallet(key_store_contents) return wallet, signer.private_key_bytes.hex() except FileExistsError: raise FileExists except PermissionError: raise NoPermissionToWriteFile except FileNotFoundError: raise FilePathIsWrong except IsADirectoryError: raise FilePathWithoutFileName
def store(self, file_path, password): """Stores data of an instance of a derived wallet class on the file path with your password. :param file_path: File path of the key store file. type(str) :param password: Password for the key store file. Password must include alphabet character, number, and special character. type(str) """ if not is_password_of_keystore_file(password): raise KeyStoreException('Invalid password.') try: key_store_contents = create_keyfile_json( self.__bytes_private_key, bytes(password, 'utf-8'), iterations=16384, kdf="scrypt" ) key_store_contents['address'] = self.get_address() key_store_contents['coinType'] = 'icx' # validate the contents of a keystore file. if is_keystore_file(key_store_contents): json_string_keystore_data = json.dumps(key_store_contents) store_keystore_file_on_the_path(file_path, json_string_keystore_data) except FileExistsError: raise KeyStoreException("File already exists.") except PermissionError: raise KeyStoreException("Not enough permission.") except FileNotFoundError: raise KeyStoreException("File not found.") except IsADirectoryError: raise KeyStoreException("Directory is invalid.")
def encrypt(cls, private_key, password, kdf=None, iterations=None): """ Creates a dictionary with an encrypted version of your private key. To import this keyfile into Ethereum clients like geth and parity: encode this dictionary with :func:`json.dumps` and save it to disk where your client keeps key files. :param private_key: The raw private key :type private_key: hex str, bytes, int or :class:`eth_keys.datatypes.PrivateKey` :param str password: The password which you will need to unlock the account in your client :param str kdf: The key derivation function to use when encrypting your private key :param int iterations: The work factor for the key derivation function :returns: The data to use in your encrypted file :rtype: dict If kdf is not set, the default key derivation function falls back to the environment variable :envvar:`ETH_ACCOUNT_KDF`. If that is not set, then 'scrypt' will be used as the default. .. doctest:: python >>> from pprint import pprint >>> encrypted = Account.encrypt( ... 0xb25c7db31feed9122727bf0939dc769a96564b2de4c4726d035b36ecf1e5b364, ... 'password' ... ) >>> pprint(encrypted) {'address': '5ce9454909639d2d17a3f753ce7d93fa0b9ab12e', 'crypto': {'cipher': 'aes-128-ctr', 'cipherparams': {'iv': '...'}, 'ciphertext': '...', 'kdf': 'scrypt', 'kdfparams': {'dklen': 32, 'n': 262144, 'p': 8, 'r': 1, 'salt': '...'}, 'mac': '...'}, 'id': '...', 'version': 3} >>> with open('my-keyfile', 'w') as f: # doctest: +SKIP ... f.write(json.dumps(encrypted)) """ if isinstance(private_key, keys.PrivateKey): key_bytes = private_key.to_bytes() else: key_bytes = HexBytes(private_key) if kdf is None: kdf = cls._default_kdf password_bytes = text_if_str(to_bytes, password) assert len(key_bytes) == 32 return create_keyfile_json(key_bytes, password_bytes, kdf=kdf, iterations=iterations)
def keyfile_contents(private_keys: List[PrivateKeyHex], passwords: List[str]) -> List[KeyfileContent]: return [ create_keyfile_json(decode_hex(private_key), password.encode(), iterations=1000) for private_key, password in zip(private_keys, passwords) ]
def keyfile(keyfile_auth): private_key, _, password = keyfile_auth xdg_ethpm_dir = get_xdg_ethpmcli_root() assert "pytest" in str(xdg_ethpm_dir) tmp_keyfile = xdg_ethpm_dir / KEYFILE_PATH keyfile_json = eth_keyfile.create_keyfile_json(private_key, password) tmp_keyfile.write_text(json.dumps(keyfile_json)) return tmp_keyfile
def encrypt(cls, private_key, password, kdf=None): ''' Creates a dictionary with an encrypted version of your private key. To import this keyfile into Ethereum clients like geth and parity: encode this dictionary with :func:`json.dumps` and save it to disk where your client keeps key files. :param private_key: The raw private key :type private_key: hex str, bytes, int or :class:`eth_keys.datatypes.PrivateKey` :param str password: The password which you will need to unlock the account in your client :param str kdf: The key derivation function to use when encrypting your private key :returns: The data to use in your encrypted file :rtype: dict .. code-block:: python >>> import getpass >>> encrypted = Account.encrypt( 0xb25c7db31feed9122727bf0939dc769a96564b2de4c4726d035b36ecf1e5b364, getpass.getpass() ) { 'address': '5ce9454909639d2d17a3f753ce7d93fa0b9ab12e', 'crypto': { 'cipher': 'aes-128-ctr', 'cipherparams': { 'iv': '0b7845a5c3597d3d378bde9b7c7319b7' }, 'ciphertext': 'a494f1feb3c854e99c1ff01e6aaa17d43c0752009073503b908457dc8de5d2a5', # noqa: E501 'kdf': 'scrypt', 'kdfparams': { 'dklen': 32, 'n': 262144, 'p': 8, 'r': 1, 'salt': '13c4a48123affaa29189e9097726c698' }, 'mac': 'f4cfb027eb0af9bd7a320b4374a3fa7bef02cfbafe0ec5d1fd7ad129401de0b1' }, 'id': 'a60e0578-0e5b-4a75-b991-d55ec6451a6f', 'version': 3 } >>> with open('my-keyfile', 'w') as f: f.write(json.dumps(encrypted)) ''' if isinstance(private_key, keys.PrivateKey): key_bytes = private_key.to_bytes() else: key_bytes = HexBytes(private_key) if kdf is None: kdf = cls.default_kdf password_bytes = text_if_str(to_bytes, password) assert len(key_bytes) == 32 return create_keyfile_json(key_bytes, password_bytes, kdf=kdf)
def _store_key_pairs(self) -> None: for public_key, private_key in self._key_pairs.items(): if self._is_persisted(public_key): continue password = self._password_provider(public_key) private_key_bytes = _serialize_private_key(private_key) key_file_json = eth_keyfile.create_keyfile_json(private_key_bytes, password) key_file_json["public_key"] = encode_hex(public_key) self._store_key_file(key_file_json)
def eth_create_account_file(keyfile_path: str, privkey: PrivateKey) -> None: keyfile_json = create_keyfile_json(privkey, bytes(DEFAULT_PASSPHRASE, "utf-8")) # Parity expects a string of length 32 here, but eth_keyfile does not pad iv = keyfile_json["crypto"]["cipherparams"]["iv"] keyfile_json["crypto"]["cipherparams"]["iv"] = f"{iv:0>32}" with open(keyfile_path, "w") as keyfile: json.dump(keyfile_json, keyfile)
def encrypt_keyfile(file: str, private_key: str, password: str): encoded_private_key = decode(private_key.encode(), "hex") output_dict = create_keyfile_json(encoded_private_key, password.encode()) output_str = dumps(output_dict) output_double_quoted = output_str.replace( "'", '"') # Replace single quote to double quote with open(file, "w") as f: f.write(output_double_quoted) print(f"{file} is created")
def create_keystore(password: str = "") -> dict: """ Create Keystore object """ m = mnemonic.Mnemonic() mnem = m.generate(256) root_key = keys.HDKey.from_seed(m.to_seed(mnem, password=password)) key = from_path(root_key=root_key, path=HDPATH) return create_keyfile_json(private_key=key.private_byte, password=bytes(password, "utf-8"))
def create_account(self, password): try: password = password.encode() private_key = utils.sha3(urandom(4096)) raw_address = utils.privtoaddr(private_key) account_addr = utils.checksum_encode(raw_address) keystore_data = create_keyfile_json(private_key, password) except Exception as err: return {'code': 101, 'error': str(err)}, None, None, None return None, account_addr, private_key.hex(), keystore_data
def keystore(self, password): """ TODO 对私钥进行对称加密 生成 keystore json 格式数据 :param password: 交易密码 :return: """ if self._private_key and isinstance(self._private_key, PrivateKey): return create_keyfile_json(bytes(self._private_key), bytes(password, encoding='utf8')) else: raise EtherError({"err": u"无效的私钥!", "code": 4000})
def stealth_receive(directory): #Import Scan and Spend Key wallet = GetKeysFromFile(directory + 'wallet.json') scan_key = wallet['scan_key'] spend_key = wallet['spend_key'] del wallet pub_scan_key = secp256k1.privtopub(scan_key) pub_spend_key = secp256k1.privtopub(spend_key) stealth_address = GetStealthAddressFromKeys(pub_scan_key, pub_spend_key) print("Stealth Address Imported: " + hex(int.from_bytes(stealth_address, 'big'))) #Import Inputs File input_json = json.load(open(directory + "input.json")) print() print("Input Count: " + str(len(input_json["keys"]))) for key in input_json["keys"]: #Extract and pad address and key fields addr = key["address"][2:] while len(addr) < 40: addr = "0" + addr addr = bytes.fromhex(addr) key = key["key"][2:] while len(key) < 66: key = "0" + key key = bytes.fromhex(key) print("Testing " + hex(int.from_bytes(addr, 'big')) + " ... ", end="") point = ExpandPoint(key) ss = GetSharedSecret(point, scan_key) addr_exp = GetAddrFromSharedSecret(ss, pub_spend_key) if addr == addr_exp: print("HIT!") priv_key = GetPrivKeyFromSharedSecret(ss, spend_key) filename = "Keystore--" + hex(int.from_bytes(addr_exp, 'big'))[2:] + ".json" print("Creating " + filename + " ... ", end="") filename = directory + filename with open(filename, mode='w') as file: js = create_keyfile_json(int.to_bytes(priv_key, 32, 'big'), bytes(password, 'utf')) json.dump(js, file) print("COMPLETE!") else: print("MISS!") del scan_key del spend_key
def _keystore_file(self): keystore_path = self._datadir.joinpath('keys') keystore_path.mkdir(exist_ok=True, parents=True) keystore_file = keystore_path.joinpath('UTC--1') if not keystore_file.exists(): log.debug('Initializing keystore', node=self._index) gevent.sleep() privkey = hashlib.sha256( f'{self._runner.scenario_name}-{self._index}'.encode(), ).digest() keystore_file.write_text(json.dumps(create_keyfile_json(privkey, b''))) return keystore_file
def keystores(tmp_path, account_keys, key_password): """paths to keystore files""" paths = [] for i, private_key in enumerate(account_keys[:2]): file_path = tmp_path / f"keyfile-{i}.json" file_path.write_text( json.dumps( create_keyfile_json(private_key.to_bytes(), key_password.encode("utf-8")))) paths.append(file_path) return paths
def make_keystore(output_path: str): password = click.prompt( 'Enter new password for keyfile', hide_input=True, confirmation_prompt=True, ).encode() now = datetime.utcnow().replace(microsecond=0) target_path = Path(output_path) target_path.mkdir(parents=True, exist_ok=True) keyfile_file = target_path.joinpath(f'UTC--{now.isoformat().replace(":", "-")}Z--{uuid4()!s}') keyfile_content = create_keyfile_json(os.urandom(32), password) keyfile_file.write_text(json.dumps(keyfile_content)) return str(keyfile_file), keyfile_content['address']
def _keystore_file(self): keystore_path = self._datadir.joinpath("keys") keystore_path.mkdir(exist_ok=True, parents=True) keystore_file = keystore_path.joinpath("UTC--1") if not keystore_file.exists(): log.debug("Initializing keystore", node=self._index) gevent.sleep() privkey = hashlib.sha256( f"{self._runner.scenario_name}-{self._runner.run_number}-{self._index}" .encode()).digest() keystore_file.write_text( json.dumps(create_keyfile_json(privkey, b""))) return keystore_file
def import_private_key(self, encoded_private_key: str, password: bytes) -> None: """ Parse the ``private_key`` provided as a hex-encoded ``str`` and then stores the private key and public key as a key pair in the key store on disk. """ private_key_bytes = decode_hex(encoded_private_key) public_key, private_key = _compute_key_pair_from_private_key_bytes( private_key_bytes) key_file_json = eth_keyfile.create_keyfile_json( private_key_bytes, password) key_file_json["public_key"] = encode_hex(public_key) self._key_pairs[public_key] = private_key self._key_files[key_file_json["id"]] = key_file_json
def __make_key_store_content(password): """ Make a content of key_store. :param password: Password including alphabet character, number, and special character. If the user doesn't give password with -p, then CLI will show the prompt and user need to type the password. :return: key_store_content(dict) """ signer = IcxSigner() private_key = signer.private_key key_store_contents = create_keyfile_json(private_key, bytes(password, 'utf-8'), iterations=262144) icx_address = "hx" + signer.address.hex() key_store_contents['address'] = icx_address key_store_contents['coinType'] = 'icx' return key_store_contents
def save_to_keystore(self, path, password, filename=None): """ Save an account in a Keystore/JSON format :param path: the folder where to store the keystore file :param password: the password for the keystore :param filename: an optional filename to use for the keystore (default to UTC--ISO8601Date--AccountAddress) :return: the filename that has been used for the keystore """ j = keystore.create_keyfile_json( self.signing_key.encode(encoder=RawEncoder), password.encode("utf-8")) if filename is None: filename = f"UTC--{datetime.utcnow().isoformat()}--{self.get_address()}" with open(os.path.join(path, filename), 'w') as fp: json.dump(j, fp) return filename
def make_key_store_content(password): """ Make a content of key_store. :param password: Password including alphabet character, number, and special character. :return: key_store_content(dict) """ signer = IcxSigner() private_key = signer.private_key key_store_contents = create_keyfile_json(private_key, bytes(password, 'utf-8'), iterations=262144) icx_address = "hx" + signer.address.hex() key_store_contents['address'] = icx_address key_store_contents['coinType'] = 'icx' return key_store_contents
def setup_validator_states_wallets(n_validators): # Extract keys from acct_keys accounts = [Account.create() for _ in range(n_validators)] addresses = [account.address for account in accounts] for i in range(n_validators): # private key state = os.path.join(VALIDATOR_STATES, VALIDATOR_STATE % i) wallet_dir = os.path.join(state, "wallets") os.mkdir(wallet_dir) keyfile_json = eth_keyfile.create_keyfile_json( accounts[i].key, b"pass", kdf="scrypt" ) with open(os.path.join(wallet_dir, addresses[i]), "w") as outfile: json.dump(keyfile_json, outfile) return addresses
def _keystore_file(self): keystore_path = self.datadir.joinpath("keys") keystore_path.mkdir(exist_ok=True, parents=True) keystore_file = keystore_path.joinpath("UTC--1") if not keystore_file.exists(): log.debug("Initializing keystore", node=self._index) gevent.sleep() seed = (f"{self._runner.local_seed}" f"-{self._runner.definition.name}" f"-{self._runner.run_number}" f"-{self._index}").encode() privkey = hashlib.sha256(seed).digest() keystore_file.write_text( json.dumps(create_keyfile_json(privkey, b""))) else: log.debug("Reusing keystore", node=self._index) return keystore_file
def set_password(self, password: str) -> None: keystore_path = self._datadir / self.KEYSTORE_FILENAME if keystore_path.exists(): self._privkey = extract_key_from_keyfile( str(keystore_path), password.encode('utf-8'), ) else: log.info("Generating new Ethereum private key") self._privkey = os.urandom(32) keystore = create_keyfile_json( self._privkey, password.encode('utf-8'), iterations=1024, ) with open(keystore_path, 'w') as f: json.dump(keystore, f)
def encrypt(private_key, password): ''' Creates a dictionary with an encrypted version of your private key. To import this keyfile into Ethereum clients like geth and parity: encode this dictionary with :func:`json.dumps` and save it to disk where your client keeps key files. :param private_key: The raw private key :type private_key: hex str, bytes, int or :class:`eth_keys.datatypes.PrivateKey` :param str password: The password which you will need to unlock the account in your client :returns: The data to use in your encrypted file :rtype: dict .. code-block:: python >>> import getpass >>> encrypted = Account.encrypt( 0xb25c7db31feed9122727bf0939dc769a96564b2de4c4726d035b36ecf1e5b364, getpass.getpass() ) {'address': '5ce9454909639d2d17a3f753ce7d93fa0b9ab12e', 'crypto': {'cipher': 'aes-128-ctr', 'cipherparams': {'iv': '78f214584844e0b241b433d7c3bb8d5f'}, 'ciphertext': 'd6dbb56e4f54ba6db2e8dc14df17cb7352fdce03681dd3f90ce4b6c1d5af2c4f', 'kdf': 'pbkdf2', 'kdfparams': {'c': 1000000, 'dklen': 32, 'prf': 'hmac-sha256', 'salt': '45cf943b4de2c05c2c440ef96af914a2'}, 'mac': 'f5e1af09df5ded25c96fcf075ada313fb6f79735a914adc8cb02e8ddee7813c3'}, 'id': 'b812f3f9-78cc-462a-9e89-74418aa27cb0', 'version': 3} >>> with open('my-keyfile', 'w') as f: f.write(json.dumps(encrypted)) ''' if isinstance(private_key, keys.PrivateKey): key_bytes = private_key.to_bytes() else: key_bytes = HexBytes(private_key) password_bytes = text_if_str(to_bytes, password) assert len(key_bytes) == 32 return create_keyfile_json(key_bytes, password_bytes)
def make_key_store_content(password): """ Make a content of key_store. :param password: Password including alphabet character, number, and special character. If the user doesn't give password with -p, then CLI will show the prompt and user need to type the password. :return: key_store_content (dict) """ # create PrivateKey object and using this, make public key, address private_key_obj = PrivateKey() private_key = private_key_obj.private_key public_key = private_key_obj.pubkey.serialize(compressed=False) address = f'hx{address_from_public_key(public_key).hex()}' key_store_contents = create_keyfile_json(private_key, password.encode(), iterations=16384, kdf="scrypt") key_store_contents['coinType'] = 'icx' key_store_contents['address'] = address return key_store_contents
def encrypt(private_key, password): key_bytes = HexBytes(private_key) password_bytes = text_if_str(to_bytes, password) assert len(key_bytes) == 32 return create_keyfile_json(key_bytes, password_bytes)