Python:PyCrypto RSA二进制.错误:从文件中读取密钥时填充不正确



我正在尝试使用AES加密来加密文件中的数据,然后使用RSA加密AES密钥。但当我试图从文件中读取密钥时,它会弹出错误"RSA binascii。错误:填充不正确"。

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:Python27libsite-packagesCryptoPublicKeyRSA.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()

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

相关内容

  • 没有找到相关文章

最新更新