簡體   English   中英

使用加密在python中讀寫txt

[英]Read and write txt in python with encryption

我有以下文件test.txt:

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

我需要使用Crypto.Cipher庫的功能DES3對campo2,campo3和campo4進行加密。 我寫了以下代碼:

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)

我的問題是我不知道如何正確遍歷文件的行並將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)

我不得不稍微修改一下您的代碼才能使其重現。 但是一旦成功,我可以使用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'\xe2\x9ee\xb4\xf1\xc4o\xa4'   b'w\xc0:\\Cn\xc7\x9f\xc4A\x93\x1e\x8c\xde\xa0\...   b'm>\xc2\xb3\xe3\xeb\xe6\\('
1   b'\x95\xea\xac\xed'     b'\xa6;\xfd\xb2\x98e\xd0\x8d'   b'01sVHg2j\xd0\x8f\xee\x90\x1a&\xd0\xae\xeb\xb3'    b'\xdb\x06\xcdh\x01\xce\xfdv\xca'
2   b'[\xfd\xf5A'           b'|\x85W\xe4\x19\x83(X'         b'\xb9E+\x00\xcf\\\xa2\r,\xa6\x9a\xf9\x0b[g\xe...   b'\xa4\xd2\x14&\x8c:\xf8N\xdc'

您可以使用python csv.reader讀取csv,使用csv.writer寫入

這是代碼:

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)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM