def ExportNEP2(self, passphrase):
"""
Export the encrypted private key in NEP-2 format.
Args:
passphrase (str): The password to encrypt the private key with, as unicode string
Returns:
str: The NEP-2 encrypted private key
"""
if len(passphrase) < 2:
raise ValueError("Passphrase must have a minimum of 2 characters")
# Hash address twice, then only use the first 4 bytes
address_hash_tmp = hashlib.sha256(self.GetAddress().encode('utf-8')).digest()
address_hash_tmp2 = hashlib.sha256(address_hash_tmp).digest()
address_hash = address_hash_tmp2[:4]
# Normalize password and run scrypt over it with the address_hash
pwd_normalized = bytes(unicodedata.normalize('NFC', passphrase), 'utf-8')
derived = scrypt.hash(pwd_normalized, address_hash,
N=SCRYPT_ITERATIONS,
r=SCRYPT_BLOCKSIZE,
p=SCRYPT_PARALLEL_FACTOR,
buflen=SCRYPT_KEY_LEN_BYTES)
# Split the scrypt-result into two parts
derived1 = derived[:32]
derived2 = derived[32:]
# Run XOR and encrypt the derived parts with AES
xor_ed = xor_bytes(bytes(self.PrivateKey), derived1)
cipher = AES.new(derived2, AES.MODE_ECB)
encrypted = cipher.encrypt(xor_ed)
# Assemble the final result
assembled = bytearray()
assembled.extend(NEP_HEADER)
assembled.extend(NEP_FLAG)
assembled.extend(address_hash)
assembled.extend(encrypted)
# Finally, encode with Base58Check
encrypted_key_nep2 = base58.b58encode_check(bytes(assembled))
return encrypted_key_nep2
评论列表
文章目录