简体   繁体   English

UnicodeDecodeError:将以太坊私钥的 python 字节串转换为字符串?

[英]UnicodeDecodeError: Converting python bytestring of ethereum private key to string?

I'm using eth-keyfile to extract a private key from an ethereum keyfile.我正在使用eth-keyfile从以太坊密钥文件中提取私钥。

# https://github.com/ethereum/eth-keyfile
from eth_keyfile import extract_key_from_keyfile

password = b'secretpassword'
extracted = extract_key_from_keyfile('testkey.json', password)
print(extracted.decode('utf-8'))

I get a UnicodeDecodeError: 'utf-8' codec can't decode byte 0xd4 in position 0: invalid continuation byte .我得到一个UnicodeDecodeError: 'utf-8' codec can't decode byte 0xd4 in position 0: invalid continuation byte I've tried other encodings as well (utf-16, latin-1).我也尝试过其他编码(utf-16、latin-1)。

How do I find out what encoding to use?如何找出要使用的编码?

I don't know much about ethereum, but as far as I can tell from a quick Google search you probably want the bytestring represented in the form of a hex string.我对以太坊了解不多,但据我快速谷歌搜索得知,您可能希望字节串以十六进制字符串的形式表示。

Assuming you're using Python 3+;假设您使用的是 Python 3+; This should probably do the trick:这应该可以解决问题:

from eth_keyfile import extract_key_from_keyfile

password = b'secretpassword'
extracted = extract_key_from_keyfile('testkey.json', password)
print(extracted.hex())

To better understand whats going on I've made this little demo:为了更好地理解发生了什么,我做了这个小演示:

>> # Python bytestring filled with the byte 0x41
>> bytes = b"\x41\x41\x41\x41"

>> # 0x41 is the ascii representation of the character 'a' so:
>> print(bytes.decode('utf-8'))
>> "aaaa"

>> # Now we have a regular string with the characters '4' '1':
>> print(bytes.hex())
>> "41414141"

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM