<p>听起来你需要一个密码库。这将帮助您使用密钥加密或解密文件。好在现在已经有一个叫PyCrypto的了。你可以下载它<a href="http://www.voidspace.org.uk/python/modules.shtml#pycrypto" rel="nofollow">here</a>。在</p>
<p>要使用它,请在下载后<a href="http://pythonhosted.org/pycrypto/Crypto.Cipher.AES-module.html#new" rel="nofollow">It is documented here</a>:</p>
<pre><code>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))
</code></pre>
<p>它使用AES作为对称密钥密码。首先,我从32个随机选择的ascii字母中生成一个随机键。然后创建一个初始化向量(iv)。这在加密文件的<em>开始</em>时是必需的,以便正确初始化。然后是密码本身,它需要一个密钥、一个操作模式和一个初始化向量。CFB模式(密码反馈模式)只是意味着AES将以某种方式使用,下一个块在某种程度上依赖于上一个块。Udacity在<a href="http://www.youtube.com/watch?v=u5soSzzXy8Q" rel="nofollow">Symmetric ciphers</a>,<a href="http://www.youtube.com/watch?v=_ujdCbh7dvA" rel="nofollow">AES</a>,和{a5}上有几段很棒的视频。在</p>