python - 使用密码或令牌加密 .csv 文件,并在每次用户想要读取文件时询问该密码
问题描述
这篇文章可能与这篇文章有关。我想用密码或令牌加密 .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')
解决方案
您可以使用密码库来创建加密方案。
创建密钥:
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
推荐阅读
- python - 按不同行拆分/读取 CSV 文件
- python - 错误:尝试使用 beautifulsoup 遍历列表时,str' 对象不可调用
- google-cloud-platform - 用于 n2d 标准机器类型的 min-cpu-platform 未显示可从 api 获得
- c# - 如何在 Layout.cshtml 中引用我的包
- javascript - 如何从存储在我的 PC 上的文件中获取 XML 数据并使用 javascript 填充 HTML 表格?
- javascript - 即使是短字符串消息,Javascript Webworker postmessage 也很慢
- r - 如何在R中生成具有偏态正态分布的随机数?
- java - Liquibase 格式化的 sql 自动生成的 id
- javascript - Axios:在单独的文件中使用 baseUrl 会导致在 axios 请求标头中设置身份验证令牌时出现问题
- typescript - 将自定义本地类型添加到由 TypeScript 编译器生成的输出声明