首页 > 解决方案 > 输入字符串的长度必须是 16 的倍数(我已经完成了填充)

问题描述

import os,sys,ctypes,struct,random
from getpass import *
from Crypto.Cipher import AES
from Crypto import Random

user = getuser()
extensions = ('.png')
paths = ['C:\\Users\\' + user + '\\Desktop\\Test']
Key = Random.new().read(AES.block_size)

def encryption ( Key,in_filename , out_filename=None , chuncksize =64*1024):
    if not out_filename:
        out_filename = in_filename + '.wbi'
    IV = Random.new().read(AES.block_size)
    encryptor = AES.new(Key,AES.MODE_CBC, IV)
    filesize = os.path.getsize(in_filename)

    with open (in_filename,'r', errors='ignore') as infile:
        with open (out_filename,'wb') as outfile:
            outfile.write(struct.pack('<Q', filesize))
            outfile.write(IV)
            while True:
                chunck = infile.read(chuncksize)
                if (len(chunck)==0):
                    break
                elif (len(chunck)%16!=0):

                    chunck+= ' ' * (16-len(chunck)%16)
                    #chunck+= ' '*(16-len(chunck)%16)
                    outfile.write(encryptor.encrypt(chunck))

def file_enc ():
    for path in paths:
        for root,dirs,files in os.walk(path):
            for file in files:
                if(file.endswith(extensions)):
                    encryption(Key, os.path.join(root,file))
                    os.remove(os.path.join(root,file))


file_enc ()         
  1. 输出:返回 self._cipher.encrypt(plaintext) ValueError:输入字符串的长度必须是 16 的倍数

我已经完成了填充,你可以在这里看到:

elif (len(chunck)%16!=0):

                    chunck+= ' ' * (16-len(chunck)%16)

追溯:

Traceback (most recent call last):
  File "C:\Users\Im Root Bicthes\Desktop\aes encryption done right.py", line 41, in <module>
    file_enc ()
  File "C:\Users\Im Root Bicthes\Desktop\aes encryption done right.py", line 37, in file_enc
    encryption(Key, os.path.join(root,file))
  File "C:\Users\Im Root Bicthes\Desktop\aes encryption done right.py", line 30, in encryption
    outfile.write(encryptor.encrypt(chunck))
  File "C:\Python32\lib\site-packages\Crypto\Cipher\blockalgo.py", line 244, in encrypt
    return self._cipher.encrypt(plaintext)
ValueError: Input strings must be a multiple of 16 in length

但我仍然不知道如何解决它任何帮助将不胜感激

使用 python 3.2.5

标签: pythonaes

解决方案


推荐阅读