PyCrypto库加密与解密速度

时间:2018-04-25 05:55:40

标签: encryption aes pycrypto

我使用Pycrypto加密器和解密器与AES 256对称密钥算法。与解密时间相比,我的加密部分花费了更多的时间。这有什么好理由吗?

  

我尝试了16 MB文件:

     

加密时间= 3.31秒   解密时间= 0.18秒

有人可以帮我说明这可能是什么原因吗?

加密逻辑如下所示:

def encrypt_file(key, infile, chunksize=64 * 1024):
    """ 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.

        infile:
            input file

        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.
    """
    iv = os.urandom(16)
    encryptor = AES.new(key, AES.MODE_CBC, iv)
    infile.seek(0, os.SEEK_END)
    filesize = infile.tell()
    infile.seek(0, os.SEEK_SET)

    encrypted = b'';
    encrypted += struct.pack('<Q', filesize)
    encrypted += iv

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

    return encrypted

解密逻辑如下所示:

def decrypt_file(key, infile, out_filename, chunksize=24*1024):
    """ Decrypts a file using AES (CBC mode) with the
        given key.
    """
    if key == '':
        with open(out_filename, 'wb') as outfile:
            for line in infile:
                outfile.write(line)
        return outfile.name

    origsize = struct.unpack('<Q', infile.read(struct.calcsize('Q')))[0]
    iv = infile.read(16)
    decryptor = AES.new(key, AES.MODE_CBC, iv)

    # for line in infile:
    #     print(line)
    with open(out_filename, 'wb+') as outfile:
        while True:
            chunk = infile.read(chunksize)
            if len(chunk) == 0:
                break
            outfile.write(decryptor.decrypt(chunk))
        outfile.truncate(origsize)

        return outfile.name

0 个答案:

没有答案