我想加密/解密包含在 .csv 文件中的一组数据。我使用以下代码生成我的 RSA 公钥/私钥:
import Crypto
from Crypto.PublicKey import RSA
key = RSA.generate(2048)
k = key.exportKey('PEM')
p = key.publickey().exportKey('PEM')
with open('private.pem', 'w') as kf:
kf.write(k.decode())
kf.close()
with open('public.pem', 'w') as pf:
pf.write(p.decode())
pf.close()
with open('private.pem','r') as fk:
priv = fk.read()
fk.close()
with open('public.pem','r') as fp:
pub = fp.read()
fp.close()
privat = RSA.importKey(priv)
public = RSA.importKey(pub)
if key == privat:
print('Private key has been successfuly write')
if key.publickey() == public:
print('Public key has been successfuly write')
然后我用这段代码加密没有任何问题:
import Crypto
from Crypto.PublicKey import RSA
from Crypto.Cipher import PKCS1_OAEP
with open('public.pem','r') as fp:
pub = fp.read()
fp.close()
public = RSA.importKey(pub)
#stockage du fichier dans une variable rep
fichier = open('test.csv', 'r')
rep = fichier.read()
fichier.close()
#eliminations des spaces
rep = rep.replace(' ', '')
#encodage pour type bytes
rep = rep.encode()
#decoupage en mot de 10 chars
rep = [rep[i:i+10] for i in range(0, len(rep), 10)]
cipher = PKCS1_OAEP.new(public)
fichier2 = open('encrypted.csv', 'a')
for i in rep:
encrypted_line = cipher.encrypt(i)
fichier2.write(str(encrypted_line))
fichier2.write('\n')
fichier2.close()
我可以通过修改这一行来修改我的数据是如何分开的:
rep = [rep[i:i+n] for i in range(0, len(rep), n)]
此行按 n 个字符组分隔我的数据
这是我解密数据的代码,它提出:
ValueError:长度不正确的密文。
import Crypto
from Crypto.PublicKey import RSA
from Crypto.Cipher import PKCS1_OAEP
with open('private.pem','r') as fk:
priv = fk.read()
fk.close()
private = RSA.importKey(priv)
fichier = open('encrypted.csv', 'r')
rep = fichier.read().splitlines()
fichier.close()
cipher = PKCS1_OAEP.new(private)
fichier2 = open('decrypted.csv', 'a')
for i in rep:
decrypted_line = cipher.decrypt(i)
decrypted_line = decrypted_line.decode('utf-8')
fichier2.write(str(encrypted_line))
fichier2.close()
我试图编码一个示例文件,它引发了这个 ValueError 。然后我尝试直接在 Python 解释器上使用一个只包含一个字符的文件。加密运行良好,但解密因与上述相同的错误而中断。