3

好的,让我们再试一次。

我正在尝试使用 PyCrypto 加密动画 gif 以发送给某人。接收者得到它后,他们应该能够运行我的 pycrypto 脚本并查看动画图像 - 无需将未加密的文件存储到硬盘驱动器。本质上,我试图将未加密的文件保存在内存中,以便另一个库可以访问它而无需将其保存到磁盘。

对于我一直在使用的加密

import os, random, struct
from Crypto.Cipher import AES

def encrypt_file(key='8c57d066796428d5a8f4b012155dad90', in_filename='tile.png', out_filename=None, chunksize=8192):
    """ Encrypts a file using AES (CBC mode) with the
        given key.

        key:
            The encryption key - a string that must be
            either 16, 24 or 32 bytes long. Longer keys
            are more secure.

        in_filename:
            Name of the input file

        out_filename:
            If None, '<in_filename>.enc' will be used.

        chunksize:
            Sets the size of the chunk which the function
            uses to read and encrypt the file. Larger chunk
            sizes can be faster for some files and machines.
            chunksize must be divisible by 16.
    """
    if not out_filename:
        out_filename = in_filename + '.enc'

    iv = ''.join(chr(random.randint(0, 0xFF)) for i in range(16))
    encryptor = AES.new(key, AES.MODE_CBC, iv)
    filesize = os.path.getsize(in_filename)

    with open(in_filename, 'r') as infile:
        with open(out_filename, 'w') as outfile:
            outfile.write(struct.pack('<Q', filesize))
            outfile.write(iv)

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

                outfile.write(encryptor.encrypt(chunk))

,但这似乎根本没有做任何事情。我什至不知道从哪里开始解密部分,因为我需要能够访问解密文件而不将其存储到硬盘驱动器。

多谢你们。

4

1 回答 1

3

使用StringIO而不是一个名为 的实际磁盘文件out_filename怎么样?

只需使用具有相同结构的虚拟光盘即可。

例子:

import StringIO

f=StringIO.StringIO()

for line in ['line {}\n'.format(i) for i in range(25)]:
    f.write(line)

f.seek(0)

for line in f:
    print line.strip() 

所以你需要with open(out_filename, 'w') as outfile: ...用一个电话替换,outfile=StringIO.StringIO()其余的应该是一样的。

像这样:

with open(in_filename, 'r') as infile:
    outfile=StringIO.StringIO()
    outfile.write(struct.pack('<Q', filesize))
    outfile.write(iv)

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

        outfile.write(encryptor.encrypt(chunk)) 
于 2013-03-25T19:52:33.653 回答