import string
from Crypto.Cipher import AES
from Crypto import Random
from Crypto.Random import random
def gen_cipher():
# generates 32 letter long key
key = ''.join(random.sample(string.ascii_letters, 32))
iv = Random.new().read(AES.block_size)
cipher = AES.new(key, AES.MODE_CFB, iv)
return cipher, iv
def write_data(data, rfile, cipher, iv):
with open(rfile, 'w') as f:
msg = iv + cipher.encrypt(b'Users cant edit this')
f.write(msg)
def read_data(rfile, cipher):
with open(rfile, 'r') as f:
data = f.read()
# first 16 bytes are IV
return cipher.decrypt(data)[16:]
def encrypt_existing_file(infile, outfile, cipher, iv):
with open(infile, 'r') as if:
data = if.read()
write_data(data, outfile, cipher, iv)
def decrypt_existing_file(infile, outfile, cipher, iv):
with open(outfile, 'r') as of:
data = read_data(infile)
of.write(data)
if __name__ == '__main__':
cipher, iv = gen_cipher()
write_data(b"You didn't see anything...", 'file.txt', cipher, iv)
# ...
# outputs: You didn't see anything...
print (read_data('file.txt', cipher))
听起来你需要一个密码库。这将帮助您使用密钥加密或解密文件。好在现在已经有一个叫PyCrypto的了。你可以下载它here。在
要使用它,请在下载后It is documented here:
它使用AES作为对称密钥密码。首先,我从32个随机选择的ascii字母中生成一个随机键。然后创建一个初始化向量(iv)。这在加密文件的开始时是必需的,以便正确初始化。然后是密码本身,它需要一个密钥、一个操作模式和一个初始化向量。CFB模式(密码反馈模式)只是意味着AES将以某种方式使用,下一个块在某种程度上依赖于上一个块。Udacity在Symmetric ciphers,AES,和{a5}上有几段很棒的视频。在
可以使用zlib压缩数据。在
只要
pickle
或cpickle
一个压缩设置为max的配置对象是一个快速而简单的选择。在相关问题 更多 >
编程相关推荐