【问题标题】:Padding is incorrect. AES Python encryption填充不正确。 AES Python 加密
【发布时间】:2018-06-12 11:07:30
【问题描述】:

我正在尝试使用 python 进行简单的加密。

这是加密:

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

def encrypt(message):
    obj = AES.new(b'This is a key123', AES.MODE_CBC, b'This is an IV456')
    return obj.encrypt(pad(message, BLOCK_SIZE))

加密似乎有效,因为它返回:

b'V=\t7I\x99\xa5\x06*\xa1={\x95+\xc1h\xfeY\xc2\xb5\xcf3F:\x88\xa6g\x94d\x87\xd7U'

但是我使用解密:

def decrypt(ciphertext):
    obj2 = AES.new(b'This is a key123', AES.MODE_CFB, b'This is an IV456')
    return obj2.decrypt(unpad(ciphertext, BLOCK_SIZE))

但它显示:

填充不正确

这是我要整理的整个文件:

import sys
from Crypto.Cipher import AES
import importlib
try:
    importlib.import_module('psutil')
except ImportError:
    import pip
    pip.main(['install', 'psutil'])
finally:
    globals()['psutil'] = importlib.import_module('psutil')

def collect_stats():
    try:
        cpu = psutil.cpu_percent(interval=1)
        memory = psutil.virtual_memory().percent
        disk = psutil.disk_usage('/').percent
        str_to_send_back = "{} {} {}".format(cpu, memory, disk)
        str_to_send_back = str_to_send_back.encode()
        str_to_send_back = encrypt(str_to_send_back)

    except Exception as e:
        print('Oops this error happened in collect_stats() inside client.py: ' + str(e))


def encrypt(message):
    obj = AES.new(b'This is a key123', AES.MODE_CBC, b'This is an IV456')
    return obj.encrypt(message)


def decrypt(ciphertext):
    obj2 = AES.new(b'This is a key123', AES.MODE_CFB, iv)
    return obj2.decrypt(ciphertext)

if __name__ == '__main__':
    collect_stats()

【问题讨论】:

  • 嗯...你用CBC模式加密,用CFB模式解密。即使您没有弄乱填充,这也会被破坏。此外,CFB 模式使AES 可用作流密码(因此它适用于任意数量的字节,而不仅仅是 16 块),因此如果您一直使用它,则无需填充或取消填充完全没有。
  • BLOCK_SIZE 32 不能是 AES 的情况(所以必须是 16)。

标签: python encryption aes padding pycryptodome


【解决方案1】:

加密时,先进行填充,然后再加密:

obj.encrypt(pad(message, BLOCK_SIZE))

这会让我相信在解密时,你应该先解密,然后再取消填充。所以:

obj2.decrypt(unpad(ciphertext, BLOCK_SIZE))

会变成:

unpad(obj2.decrypt(ciphertext), BLOCK_SIZE)

【讨论】:

  • BLOCK_SIZE 似乎是unpad() 的参数,而不是decrypt()。否则,这与我得到的印象相同。
  • @glibdud 哎呀!现已修复
猜你喜欢
  • 1970-01-01
  • 2015-05-22
  • 2018-02-15
  • 2013-09-25
  • 1970-01-01
  • 2011-10-16
  • 1970-01-01
  • 2021-05-11
  • 1970-01-01
相关资源
最近更新 更多