为什么这段代码:
s = "\x00\x00\x00\x00\x03\x00\x00\x00id\x00\x00"
from Crypto.PublicKey import RSA
from Crypto.Util import randpool
key = RSA.generate(1024, randpool.RandomPool().get_bytes)
d = key.encrypt(s, None)
dec = key.decrypt(d)
print ''.join( [ "%02X " % ord( x ) for x in dec ] ).strip()
输出:
03 00 00 00 69 64 00 00
而不是
00 00 00 00 03 00 00 00 69 64 00 00
最佳答案
发生这种情况是因为默认加密算法向消息中添加了一些前导空字节,而解密算法会删除所有前导空字节,即使它们位于原始消息中也是如此。
解决方案是使用Crypto.Cipher.PKCS1_OAEP进行加密/解密。
from Crypto.PublicKey import RSA
from Crypto.Util import randpool
from Crypto.Cipher import PKCS1_OAEP as PKCS
s = "\x00\x00\x00\x00\x03\x00\x00\x00id\x00\x00"
key = RSA.generate(1024, randpool.RandomPool().get_bytes)
cipher = PKCS.new(key)
encr = cipher.encrypt(s)
decr = cipher.decrypt(encr)
关于python - RSA 解密去除前导空字节,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17555855/