python(128 位密钥)中使用 CBC 模式的 AES 加密

AES encryption with CBC mode in python (128-Bit keys)

我用下面的代码在AES中加密了一个文本,并用在线解密网站解密了密文(Website 1, Website 2). But, the decrypted text from all websites contains some unwanted strings in front as shown in this图片。

import base64
import hashlib
from Crypto import Random
from Crypto.Cipher import AES

key = b'asdfghjklqwertyu'

class AESCipher(object):

    def __init__(self, key): 
        self.bs = AES.block_size
        self.key = key

    def encrypt(self, raw):
        raw = self._pad(raw)
        iv = Random.new().read(AES.block_size)
        cipher = AES.new(self.key, AES.MODE_CBC, iv)
        return base64.b64encode(iv + cipher.encrypt(raw.encode()))

    def _pad(self, s):
        return s + (self.bs - len(s) % self.bs) * chr(self.bs - len(s) % self.bs)

a = AESCipher(key)
print(a.encrypt('Hey There!'))

devlan 站点说明

CBC mode is highly recommended and it requires IV to make each message unique. If no IV is entered then default will be used here for CBC mode and that defaults to a zero based byte[16].

因此您的前置 IV 被视为密文块。现在,那里有两个街区。在 CBC 模式下,解密执行为 ( blocks are counted form 1);

Pi = Dec(key, Ci) + Ci
C0 = IV
  • 你的 P1 = Dec(key, C1) + C0 这是垃圾,因为 IV = 0
  • 您的 P2 = Dec(key, C2) + C1 这是您的原始消息。

这要归功于 CBC 模式的 属性,下图显示了这种情况;

很高兴你在那里和那里进行了测试。使用前应阅读程序的所有文档,这在密码应用程序中更为关键。

你在 IV 前面加上的是正确的,没有任何问题,你只需要向站点提供你的 IV 和密文块。

如果您需要在没有IV的情况下解密文本,请在加密时将iv设置为默认值。

class AESCipher(object):

    def __init__(self, key): 
        self.bs = AES.block_size
        self.key = key

    def encrypt(self, raw):
        raw = self._pad(raw)
        iv = b'[=11=]'*16 #Default zero based bytes[16]
        cipher = AES.new(self.key, AES.MODE_CBC, iv)
        return base64.b64encode(cipher.encrypt(raw.encode()))

    def _pad(self, s):
        return s + (self.bs - len(s) % self.bs) * chr(self.bs - len(s) % self.bs)