Python:PyCrypto RSA binascii.Error:从文件中读取键时填充不正确

时间:2015-12-06 13:28:44

标签: python encryption cryptography rsa pycrypto

我尝试使用AES加密对文件中的数据进行加密,然后使用RSA加密AES密钥。但是当我尝试从文件中读取密钥时,它会出现错误" RSA binascii.Error:填充错误"。

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()

1 个答案:

答案 0 :(得分:0)

请尝试检查输入文件的内容,以便从中获取密钥或数据进行加密或解密。如果来自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..