首页 > 解决方案 > 使用密码或令牌加密 .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')

标签: pythonpandasencryptionpassword-protectionpassword-encryption

解决方案


您可以使用密码库来创建加密方案。

创建密钥:

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

推荐阅读