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

Mask information in CSV file using sha256 in Python

我有一个包含 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')

我不知道如何指定只屏蔽地址和密码列?

如有任何帮助,我们将不胜感激。谢谢

首先,由于您的 input.csv 文件包含三项,因此您的循环需要读取三项。然后你可以有一个函数,它接受文本和 returns 散列值。然后您可以使用此函数对地址和密码字段进行哈希处理。

我建议返回十六进制摘要,以便可以轻松将其写入您的 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

如您所见,地址的值是相同的。 header 行可以先复制,然后再散列其余行。