如何使用pyCrypto来加密和解密文件

时间:2016-02-24 14:41:57

标签: python python-2.7 encryption aes pycrypto

我有以下用python编写的代码和底部的几行来调试和执行代码:

class encoder:
    encryptor = False
    IV = 16 * '\x00'
    def __init__(self, password):
            self.encryptor = AES.new(sha256(password).digest(), AES.MODE_CBC, self.IV)

    def encode_file(self, path):
        filesize = os.path.getsize(path)

        with open(path, 'rb') as infile:
            with open((path+"1"), 'wb') as outfile:
                outfile.write(struct.pack('<Q', filesize))
                outfile.write(self.IV)

                while True:
                    chunk = infile.read(64*1024)
                    if len(chunk) == 0:
                        break
                    elif len(chunk) % 16 != 0:
                        chunk += ' ' * (16 - len(chunk) % 16)

                    outfile.write(self.encryptor.encrypt(chunk))
    def decrypt_file(self, in_filename,chunksize=24*1024):
        out_filename = "E:\\digested.txt"

        with open(in_filename, 'rb') as infile:
            origsize = struct.unpack('<Q', infile.read(struct.calcsize('Q')))[0]
            iv = infile.read(16)
            with open(out_filename, 'wb') as outfile:
                chunk = infile.read(chunksize)
                outfile.write(self.encryptor.decrypt(chunk))
                outfile.truncate(origsize)

enc = encoder("password")
enc.encode_file("E:\\txt.txt")
enc.decrypt_file("E:\\txt.txt1")

代码是尝试加密整个文件夹的一部分,但我目前正在测试单个文件的加密和解密。为了舒适的原因,我把IV简单地留了下来并且没有使用哈希。 由于某种原因,此代码不能正确地消化和解密加密文件。

另外,由于我在这个领域很新,我有一个非常基本的问题,为什么IV如此重要?

编辑: 我错误地写了解密而不是加密,现在我修复了它似乎设法解密除了前16个字节以外的文件,这是否与IV有关(我的猜测是因为IV是16字节长) ?

编辑2: 通过使IV成为文件的前16个字节而不是用于编码的相同IV来解决它,对不起麻烦。如果可能的话,我很乐意回答IV的原因和重要性。谢谢。

0 个答案:

没有答案