使用加密读取和写入txt



我有以下文件test.txt:

'campo1','campo2','campo3','campo4'    
'2222','34563434','547348568765756556','78967756K      '
'2222','34564232','343575876567567584','65876566W      '
'2222','54754456','234223144675987666','43453534A      '

我需要将Campo2,Campo3和Campo4加密使用Crypto.Cipher库的功能3。我编写了以下代码:

import pandas as pd
from Crypto.Cipher import DES3
infile = mainpath + "/" + "Prueba Encriptacion.txt"
outfile = mainpath + "/" + "Prueba Encriptacion out.txt"
cipher = DES3.new("4QGdtHLBSKmAJaOJY5BW")
df = pd.read_csv(infile, ',')
for row in df.iterrows():
    campo2_out= cipher.encrypt(campo2)
    campo3_out=cipher.encrypt(campo3)
    campo4_out=cipher.encrypt(campo4)

我的问题是我不知道如何正确地遍历文件的行并在outfile中写入cipher.encrypt函数的结果。

在熊猫中,您通常不会穿过行。您将功能应用于所需的单元格,然后保存结果框架。

因此您的代码应为:

#... read frame as normal...
df["campo2"] = df["campo2"].apply(cipher.encrypt)
df["campo3"] = df["campo3"].apply(cipher.encrypt)
df["campo4"] = df["campo4"].apply(cipher.encrypt)
df.to_csv("outputfile)

您可以使用python csv.reader使用csv.writer

读取CSV

这是代码:

import csv
from Crypto.Cipher import DES3
cipher = DES3.new("4QGdtHLBSKmAJaOJY5BW")
infile = mainpath + "/" + "Prueba Encriptacion.txt"
outfile = mainpath + "/" + "Prueba Encriptacion out.txt"

def encrypt_csv(file_name):
    with open(file_name, 'r') as csv_file:
        with open(outfile, 'w') as out_file:
            reader = csv.reader(csv_file, delimiter=",")
            writer = csv.writer(out_file, delimiter=",")
            for row in reader:
                encrypted_data = [cipher.encrypt(data) for data in row]
                writer.writerow(encrypted_data)

if __name__ == '__main__':
    encrypt_csv(infile)

我必须修改您的代码以使其复制。但是一旦工作,我可以使用applymap,这样:

from Crypto.Cipher import DES3
from Crypto.Random import get_random_bytes
key = DES3.adjust_key_parity(get_random_bytes(24))
cipher = DES3.new(key, DES3.MODE_CFB)
df = pd.read_csv('test.txt', ',')
df = df.astype(str)
df = df.applymap(lambda x: cipher.encrypt(x.encode('UTF-8')))

给你:

campo1               campo2                                 campo3                                              campo4
0   b'xe1#[xd3'           b'xe2x9eexb4xf1xc4oxa4'   b'wxc0:\Cnxc7x9fxc4Ax93x1ex8cxdexa0...   b'm>xc2xb3xe3xebxe6\('
1   b'x95xeaxacxed'     b'xa6;xfdxb2x98exd0x8d'   b'01sVHg2jxd0x8fxeex90x1a&xd0xaexebxb3'    b'xdbx06xcdhx01xcexfdvxca'
2   b'[xfdxf5A'           b'|x85Wxe4x19x83(X'         b'xb9E+x00xcf\xa2r,xa6x9axf9x0b[gxe...   b'xa4xd2x14&x8c:xf8Nxdc'

最新更新