在Python中使用sha256屏蔽CSV文件中的信息

ffx8fchx  于 2022-12-15  发布在  Python
关注(0)|答案(1)|浏览(115)

我有一个包含NameAddressPassword的CSV文件,我想在Python中使用sha256来屏蔽Addresspassword
以下是我到目前为止所做的尝试:

import hashlib
import csv

def hash_pw(input_file_name, output_file_name): 
    hash_lookup = {} 

    with open(input_file_name, newline='') as f_input, open(output_file_name, 'w', newline='') as f_output: 
        csv_input = csv.reader(f_input)
        csv_output = csv.writer(f_output) 

        for user, hash in csv_input: 
            csv_output.writerow([user, hash_lookup[hash]]) 

hash_pw('input.csv', 'output.csv')

我不知道如何指定只屏蔽地址和密码列?
任何帮助都将不胜感激。谢谢

iqih9akk

iqih9akk1#

首先,由于input.csv文件包含三个元素,因此循环需要读取三个元素,然后可以使用一个函数获取文本并返回散列值,然后使用该函数对地址和密码字段进行散列。
我建议返回十六进制摘要,以便可以轻松地将其写入output.csv文件:

import hashlib
import csv

def hash(text):
    return hashlib.sha256(text.encode('utf-8')).hexdigest()

def hash_file(input_file_name, output_file_name): 
    hash_lookup = {} 

    with open(input_file_name, newline='') as f_input, open(output_file_name, 'w', newline='') as f_output: 
        csv_input = csv.reader(f_input)
        csv_output = csv.writer(f_output) 
        csv_output.writerow(next(csv_input))    # Copy the header row to the output

        for user, address, password in csv_input: 
            csv_output.writerow([user, hash(address), hash(password)]) 

hash_file('input.csv', 'output.csv')

因此,如果input.csv包含以下内容:

Name,Address,Password
Fred,1 Rock Close,MyPassword
Wilma,1 Rock Close,Password1234

output.csv将如下所示:

Name,Address,Password
Fred,fc3b252cf37b3d247a38068a5f58cc8fc6b9ea3e938831c6d90f8eb9e923d782,dc1e7c03e162397b355b6f1c895dfdf3790d98c10b920c55e91272b8eecada2a
Wilma,fc3b252cf37b3d247a38068a5f58cc8fc6b9ea3e938831c6d90f8eb9e923d782,a0f3285b07c26c0dcd2191447f391170d06035e8d57e31a048ba87074f3a9a15

正如您所看到的,地址的值是相同的。可以先复制标题行,然后再散列其余行。

相关问题