使用密码或令牌加密 .csv 文件,并在每次用户想要读取文件时询问该密码
Posted
技术标签:
【中文标题】使用密码或令牌加密 .csv 文件,并在每次用户想要读取文件时询问该密码【英文标题】:Encrypt a .csv file with a password or token and ask for that password everytime user wants to read in the file 【发布时间】:2021-09-06 09:19:56 【问题描述】:这篇文章might be related to this one。我想用密码或令牌加密 .csv 文件。然后,我想编写一个脚本,使用密码解密文件,将 .csv 文件作为数据框读取,并继续对内容进行数据分析。如何实现这一目标?
例子:
import pandas as pd
import csv
# 1.) Create the .csv file
super_secret_dict = 'super_secret_information':'foobar'
with open('super_secret_csv.csv','w') as f:
w = csv.DictWriter(f,super_secret_dict.keys())
w.writeheader()
w.writerow(super_secret_dict)
# 2.) Now encrypt the .csv file with a very safe encryption method and generate
# a password/token that can be shared with people that should have access to the
# encrypted .csv file
# ...
# ...
# 3.) Everytime a user wants to read in the .csv file (e.g. using pd.read_csv())
# the script should ask the user to type in the password, then read in
# the .csv file and then continue running the rest of the script
super_secret_df = pd.read_csv('./super_secret_csv.csv')
【问题讨论】:
使用 PBKDF2 密钥派生搜索 Aes。 【参考方案1】:您可以使用密码库创建加密方案。
创建密钥:
from cryptography.fernet import Fernet
key = Fernet.generate_key()
f = Fernet(key)
将该密钥保存在某处!
当你想加密时加载你的密钥!
def load_key():
return open(PATH TO SECRET KEY,"rb").read()
加密您的文件
def encrypt_it(path_csv):
"""Takes a message an encrypts it
"""
key = load_key()
encrypted = ''
# create Fernet using secret
f = Fernet(key)
with open(path_csv, 'rb') as unencrypted:
_file = unencrypted.read()
encrypted = f.encrypt(_file)
with open('encrypted_file.csv', 'wb') as encrypted_file:
encrypted_file.write(encrypted)
稍后再读:
def decrypt_it(path_encrypted):
key = load_key()
f = Fernet(key)
decrypted = ''
with open(path_encrypted, 'rb') as encrypted_file:
decrypted = f.decrypt(encrypted_file.read())
return decrypted
【讨论】:
问题是关于使用密码加密,而不是使用预先保存的密钥。 在加密过程中读取一些输入并生成密钥,解密时也这样做。以上是关于使用密码或令牌加密 .csv 文件,并在每次用户想要读取文件时询问该密码的主要内容,如果未能解决你的问题,请参考以下文章