Pycrypto - 在Linux上加密/在Windows上解密

0 投票
2 回答
651 浏览
提问于 2025-04-18 09:40

我有一个加密和解密的类,正在跨平台使用。这个类在服务器和客户端上都是一样的。我在Linux服务器上加密一个文件,然后在Linux或Windows客户端上解密。在Linux上解密没有问题,但当我把文件转到Windows上解密时,出现了以下错误:

ValueError: 输入字符串的长度必须是16的倍数

我首先想到这可能是因为不同的文件系统,以及用于填充的字符造成的。以下是我的类代码:

class FileSec:
    def __init__(self):

        # File chunk size
        self.chunk_size = 64*1024

    # Encrypt file with OpenSSL
    def encrypt(self, infile, outfile, key):
        if not infile or not os.path.isfile(infile):
            return False
        if not outfile or os.path.isfile(outfile):
            return False
        if not key:
            return False

        # Encrypt the file
        iv        = ''.join(chr(random.randint(0, 0xFF)) for i in range(16))
        encryptor = AES.new(key, AES.MODE_CBC, iv)
        filesize  = os.path.getsize(infile)
        with open(infile, 'rb') as ifh:
            with open(outfile, 'wb') as ofh:
                ofh.write(struct.pack('<Q', filesize))
                ofh.write(iv)
                while True:
                    chunk = ifh.read(self.chunk_size)
                    if len(chunk) == 0:
                        break
                    elif len(chunk) % 16 != 0:
                        chunk += ' ' * (16 - len(chunk) % 16)
                    ofh.write(encryptor.encrypt(chunk))
        return True

    # Decrypt file with OpenSSL
    def decrypt(self, infile, outfile, key):
        if not infile or not os.path.isfile(infile):
            return False
        if not outfile or os.path.isfile(outfile):
            return False
        if not key:
            return False

        # Decrypt the file
        with open(infile, 'rb') as ifh:
            origsize  = struct.unpack('<Q', ifh.read(struct.calcsize('Q')))[0]
            iv        = ifh.read(16)
            decryptor = AES.new(key, AES.MODE_CBC, iv)
            with open(outfile, 'wb') as ofh:
                while True:
                    chunk = ifh.read(self.chunk_size)
                    if len(chunk) == 0:
                        break
                    ofh.write(decryptor.decrypt(chunk))
                ofh.truncate(origsize)
        return True

我使用的代码是从这里改编的:http://eli.thegreenplace.net/2010/06/25/aes-encryption-of-files-in-python-with-pycrypto/

有没有人有什么建议,可以让我修改这个类,使其在不同平台上都能正常工作?

2 个回答

0

关闭这个问题了。结果发现,问题跟加密/解密功能没有关系,而是因为我把加密文件传到Windows机器时,多加了一个字节,这导致了异常。

0

myfile.read(x) 这个命令可以读取最多 x 字节的数据,但并不能保证一定会读取到所有的 x 字节。

需要注意的是,只要文件还没读完,它至少会返回一个字节的数据,所以你可以把这个命令放在一个循环里,然后把返回的字符串连接起来。

撰写回答