python - RSA 解密去除前导空字节

标签 python rsa pycrypto

为什么这段代码:

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/

相关文章:

c# - 加密 App.Config 部分并部署到多台机器

c# - 仅使用公钥验证签名 (C#)

python - 如何在 PyCrypto AES CTR 模式下设置 block 大小

python - 如何将元组内的字典列表转换为 pandas DataFrame?

python - 在 zip 对象列表上执行 len 会清除 zip

RSA_public_decrypt() 的 Python3 OpenSSL 绑定(bind)

python - 在 pycrypto 中为 RSA 使用致盲因子

python - Firebase python admin sdk isNewUser ()

python - 我是否正确安装了 pip?

python - 使用 py2exe 编译时 passlib.hash import sha256_crypt 给出错误