ValueError:数据必须与 ECB 模式下的块边界对齐 [英] ValueError: Data must be aligned to block boundary in ECB mode

查看:23
本文介绍了ValueError:数据必须与 ECB 模式下的块边界对齐的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用以下代码在 ECB 模式下进行 aes 128 加密.

I am trying aes 128 encryption in ECB mode with the following code.

from Crypto.Cipher import AES
key = 'abcdefghijklmnop'
cipher = AES.new(key.encode('utf8'), AES.MODE_ECB)
msg = cipher.encrypt(b'hello')
print(msg.hex())
decipher = AES.new(key.encode('utf8'), AES.MODE_ECB)
msg_dec = decipher.decrypt(msg)
print(msg_dec)

但我收到ValueError:数据必须与 ECB 模式下的块边界对齐".如果 string 是 16 的倍数,它工作正常.我不知道如何进行填充和取消填充.我们如何解决这个问题?请帮忙

but I'm getting "ValueError: Data must be aligned to block boundary in ECB mode". It works fine if string is a multiple of 16. I don't know how to do padding, unpadding. How can we solve this ? Please help

推荐答案

对于paddingun-padding,你可以使用Crypto的内置函数code> 库,下面是您问题的有效解决方案.

For padding and un-padding, you may use inbuilt functions of Crypto library, below is a working solution to your problem.

from Crypto.Util.Padding import pad, unpad
from Crypto.Cipher import AES
BLOCK_SIZE = 32 # Bytes

key = 'abcdefghijklmnop'
cipher = AES.new(key.encode('utf8'), AES.MODE_ECB)
msg = cipher.encrypt(pad(b'hello', BLOCK_SIZE))
print(msg.hex())
decipher = AES.new(key.encode('utf8'), AES.MODE_ECB)
msg_dec = decipher.decrypt(msg)
print(unpad(msg_dec, BLOCK_SIZE))

这篇关于ValueError:数据必须与 ECB 模式下的块边界对齐的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆