因此,我一直在尝试使用 python(特别是 pycryptodome)更好地熟悉加密,并且在尝试将字节字符串解码为 ascii 时遇到了一个有趣的问题。请看下面的代码:
from Crypto.Signature import PKCS1_v1_5
from Crypto.Hash import SHA
from Crypto.PublicKey import RSA
message = b'Something secret'
random_gen = Crypto.Random.new().read
print("Type of random_gen: {}".format(type(random_gen)))
private_key = RSA.generate(1024, random_gen) # private key
public_key = private_key.publickey() # public key
signer = PKCS1_v1_5.new(private_key) # signer which uses private key
verifier = PKCS1_v1_5.new(public_key) # verifier which uses public key
h = SHA.new(message) # hash of message
print("Hash: {}".format(h.hexdigest()))
signature = signer.sign(h) # sign hashed version of message
print("Signature type = {}".format(type(signature)))
print("Signature: {}".format(binascii.hexlify(signature).decode('ascii')))
在代码的最后一行,为什么我必须首先hexlify()
将签名类型<class 'bytes'>
解码为ascii,以便我可以读取签名?为什么如果我这样做:
print("Signature: {}".format(signature.decode('ascii')))
我收到以下错误:
UnicodeDecodeError: 'ascii' codec can't decode byte 0x88 in position 2: ordinal not in range(128)
谢谢您的帮助。