本文介绍了如何在数据中添加填充以使其可以被pycrypto库中的AES256加密算法接受的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有人可以告诉我如何在数据中添加填充以使pycrypto库(Python)中的AES256加密算法可接受.

Can someone tell me how to add a padding to the data to make it acceptable for AES256 encryption algorithm in pycrypto library (Python).

非常感谢..:)

推荐答案

查看文档,库用户似乎要由您自己填充数据.该文档指出,AES的块大小始终为16个字节,因此您需要将数据填充为16个字节的倍数.

Looking at the documentation, it seems that it's up to you, the library user, to pad the data yourself. The documentation states that the block size for AES is always 16 bytes, so you need to pad the data to a multiple of 16 bytes.

如何完成填充取决于数据的类型.对于字符串,最好的方法可能是将字符串编码为特定的编码,然后采用该编码的长度.这样,您就不必依赖8位代码点表示的所有字符了:

How the padding is done depends on the type of the data. For strings the best approach is probably to encode the string to a specific encoding and then take the length of that encoding. That way you're not relying on all characters being represented by an 8-bit codepoint:

plaintext = data.encode('utf-8')
l = len(plaintext)
ciphertext = cipher.encrypt(plaintext + ((16 - len%16) * PADDING_BYTE))

当您的数据是字节数组时,类似的方法也可以使用.

A similar approach will work when you're data is an array of bytes.

0 应该可以与 PADDING_BYTE 正常工作,但是在解密数据时,请务必小心删除填充.最好在密文中包含数据长度,例如在加密之前将数据长度设置为纯文本格式,但是随后您需要跳过一些箍以确保正确生成填充.

0 should work fine as the PADDING_BYTE, but you need to take care to remove the padding when you're decrypting the data. It might be worth while including the length of the data in the ciphertext, e.g. prepend the length of the data to the plaintext before encryption, but then you need to jump through some hoops to make sure the padding is generated correctly.

编辑:哦,是的,就像提到的RFC GregS链接一样,处理长度问题的标准方法是使用填充的长度作为填充字节.IE.如果您需要6个填充字节,则填充字节为 0x06 .请注意,如果不需要任何填充,则可以添加整个填充字节块(16个字节的 0xa0 ),以便可以正确恢复消息.

Edit: oh yes, just like the RFC GregS links to mentions, the standard way of handling the length problem is the use the length of the padding as the padding byte. I.e. if you need 6 bytes of padding the padding byte is 0x06. Note that if you don't need any padding, you to add a whole block of padding bytes (16 bytes of 0xa0) so that you can recover the message correctly.

这篇关于如何在数据中添加填充以使其可以被pycrypto库中的AES256加密算法接受的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-21 10:36