【问题标题】:Python: PyCrypto RSA binascii.Error: Incorrect padding while reading keys from a filePython:PyCrypto RSA binascii.Error:从文件中读取密钥时填充不正确
【发布时间】:2016-03-11 03:11:06
【问题描述】:

我正在尝试使用 AES 加密对文件中的数据进行加密,然后使用 RSA 加密 AES 密钥。但是,当我尝试从文件中读取密钥时,会出现错误“RSA binascii.Error: Incorrect padding”。

Traceback (most recent call last):
  File "C:/Users/dbane_000/PycharmProjects/RSE/RSA.py", line 33, in <module>
    key=RSA.importKey(f.read())
  File "C:\Python27\lib\site-packages\Crypto\PublicKey\RSA.py", line 660, in importKey
    der = binascii.a2b_base64(b('').join(lines[1:-1]))
binascii.Error: Incorrect padding

错误并不总是出现,但可能每运行此代码五次就会出现一次。可能是什么原因?

from Crypto.Cipher import AES
from Crypto.PublicKey import RSA
from Crypto.Cipher import PKCS1_OAEP
from Crypto import Random
import rsa
import base64
import os

BLOCK_SIZE = 32
PADDING = '{'

pad = lambda s: s + (BLOCK_SIZE - len(s) % BLOCK_SIZE) * PADDING

EncodeAES = lambda c, s: base64.b64encode(c.encrypt(pad(s)))
DecodeAES = lambda c, e: c.decrypt(base64.b64decode(e)).rstrip(PADDING)

random_generator = Random.new().read
rsakey = RSA.generate(1024, random_generator)
f=open('key.pem','w')
cipher = PKCS1_OAEP.new(rsakey.publickey())
f.write(rsakey.exportKey("PEM"))
f.write(rsakey.publickey().exportKey("PEM"))
f.close()
f=open('key.pem','r')
key=RSA.importKey(f.read())
pubkey=key.publickey()
f.close()
secret = os.urandom(BLOCK_SIZE)
print secret
crypto =pubkey.encrypt(secret, 32)
secret =key.decrypt(crypto)

print crypto
print secret

cipher = AES.new(secret)


# encode a string
f=open('plaintext.txt','r')
plaintext=f.read()
f.close()
encoded = EncodeAES(cipher, plaintext)
print 'Encrypted string:', encoded
f=open('cipher_data.txt','w')
f.write(encoded)
f.close()

# decode the encoded string
decoded = DecodeAES(cipher, encoded)
print 'Decrypted string:', decoded
f=open('plaintext.txt','r')
plaintext=f.read()
f.close()
f=open('decrypted.txt','w')
f.write(decoded)
f.close()

【问题讨论】:

  • 您没有以二进制模式打开文件...
  • @MaartenBodewes 以二进制模式打开文件这应该是代码吧? f=open('key.pem','rb') 。我试过了,但还是没有区别。
  • 嗯。通常公钥部分包含在私钥中。您是否尝试不明确导出公钥?对于 PEM 文本模式可能还可以,但对于密文肯定不行。

标签: python encryption cryptography rsa pycrypto


【解决方案1】:

请尝试检查您从中获取密钥或数据以进行加密或解密的输入文件的内容。如果来自 f.read() 的数据是执行解密所需的格式,则可能会发生这种类型的错误。请尝试在开始或所需索引处写入这些密钥或数据并从该索引中获取..

# please check at this statements
f=open('key.pem','w')
cipher = PKCS1_OAEP.new(rsakey.publickey())
f.write(rsakey.exportKey("PEM"))
f.write(rsakey.publickey().exportKey("PEM"))
f.close()
f=open('key.pem','r')
key=RSA.importKey(f.read())
pubkey=key.publickey()
f.close()

I hope this may help you..

【讨论】:

    猜你喜欢
    • 2020-05-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-09-16
    相关资源
    最近更新 更多