概述我正在尝试做的事情。我有需要读入 pandas 的文件的加密版本。由于多种原因,解密到流而不是文件要好得多,所以这是我下面的兴趣,尽管我也尝试解密到文件只是作为中间步骤(但这也不起作用)。
我可以让它适用于 csv,但不适用于 hdf 或 stata(我接受适用于 hdf 或 stata 的答案,尽管两者的答案可能相同,这就是为什么我合并为一个问题)。
加密/解密文件的代码取自另一个stackoverflow问题(我目前找不到)。
import pandas as pd
import io
from Crypto import Random
from Crypto.Cipher import AES
def pad(s):
return s + b"\0" * (AES.block_size - len(s) % AES.block_size)
def encrypt(message, key, key_size=256):
message = pad(message)
iv = Random.new().read(AES.block_size)
cipher = AES.new(key, AES.MODE_CBC, iv)
return iv + cipher.encrypt(message)
def decrypt(ciphertext, key):
iv = ciphertext[:AES.block_size]
cipher = AES.new(key, AES.MODE_CBC, iv)
plaintext = cipher.decrypt(ciphertext[AES.block_size:])
return plaintext.rstrip(b"\0")
def encrypt_file(file_name, key):
with open(file_name, 'rb') as fo:
plaintext = fo.read()
enc = encrypt(plaintext, key)
with open(file_name + ".enc", 'wb') as fo:
fo.write(enc)
def decrypt_file(file_name, key):
with open(file_name, 'rb') as fo:
ciphertext = fo.read()
dec = decrypt(ciphertext, key)
with open(file_name[:-4], 'wb') as fo:
fo.write(dec)
这是我尝试扩展代码以解密为流而不是文件。
def decrypt_stream(file_name, key):
with open(file_name, 'rb') as fo:
ciphertext = fo.read()
dec = decrypt(ciphertext, key)
cipherbyte = io.BytesIO()
cipherbyte.write(dec)
cipherbyte.seek(0)
return cipherbyte
最后,这是包含示例数据的示例程序,试图使其工作:
key = 'this is an example key'[:16]
df = pd.DataFrame({ 'x':[1,2], 'y':[3,4] })
df.to_csv('test.csv',index=False)
df.to_hdf('test.h5','test',mode='w')
df.to_stata('test.dta')
encrypt_file('test.csv',key)
encrypt_file('test.h5',key)
encrypt_file('test.dta',key)
decrypt_file('test.csv.enc',key)
decrypt_file('test.h5.enc',key)
decrypt_file('test.dta.enc',key)
# csv works here but hdf and stata don't
# I'm less interested in this part but include it for completeness
df_from_file = pd.read_csv('test.csv')
df_from_file = pd.read_hdf('test.h5','test')
df_from_file = pd.read_stata('test.dta')
# csv works here but hdf and stata don't
# the hdf and stata lines below are what I really need to get working
df_from_stream = pd.read_csv( decrypt_stream('test.csv.enc',key) )
df_from_stream = pd.read_hdf( decrypt_stream('test.h5.enc',key), 'test' )
df_from_stream = pd.read_stata( decrypt_stream('test.dta.enc',key) )
不幸的是,我认为我不能再缩小这段代码并且仍然有一个完整的示例。
再次,我希望所有 4 个非工作行都能正常工作(hdf 和 stata 的文件和流),但我很高兴接受仅适用于 hdf 流或仅适用于 stata 流的答案。
另外,我对其他加密替代方案持开放态度,我只是使用了一些现有的基于 pycrypto 的代码,这些代码是我在 SO 上找到的。我的工作明确需要 256 位 AES,但除此之外我是开放的,因此该解决方案不需要专门基于 pycrypto 库或上面的特定代码示例。
有关我的设置的信息:
python: 3.4.3
pandas: 0.17.0 (anaconda 2.3.0 distribution)
mac os: 10.11.3