首页 > 解决方案 > Python以CBC加密方式实现AES

问题描述

我正在尝试在线完成这个挑战,它要求自己实现 AES CBC 模式,而不使用任何可以为我完成工作的库函数(ofc xD)。我正在使用AES 模块(顺便说一句python3.7PyCrypto我是 python 初学者)

我觉得我找到了解决方案,但事实并非如此,我看不出我做错了什么。我正在输入这个文本:`

2017 年 9 月 2017 年 9 月 2017 年 9 月 2017 年 9 月

` 用这个键:

黄色潜水艇

并且有一个 16 字节长的 IV 充满 0 (\x00)

但我的输出与我可以在网上找到的不同网站或使用PyCrypto模块中的 AES CBC 模式时不同

这是我到目前为止为了生成带有注释的 aes cbc 加密而制作的小程序:

#!/usr/bin/env python
from sys import argv
from Crypto.Cipher import AES
import codecs


def pad(plaintext):
    padding_len = 16 - (len(plaintext) % 16)
    print(padding_len)
    if padding_len == 16:
         return plaintext
padding = bytes([padding_len] * padding_len)
return plaintext + padding


def xor_for_char(input_bytes, key_input):
    index = 0
    output_bytes = b''
    for byte in input_bytes:
        if index >= len(key_input):
            index = 0
        output_bytes += bytes([byte ^ key_input[index]])
        index += 1
    return output_bytes


class AESCBCTool:
    def __init__(self):
        self.best_occurence = 0
        self.best_line = 0

def encrypt_CBC(self, enc, key):
    enc = pad(enc) # here I pad the text (PCKS#7 way)
    nb_blocks = (int)(len(enc) / 16) #calculate the number of blocks I've to iter through
    IV = bytearray(16)
    cipher = AES.new(key, AES.MODE_ECB)
    for i in range(nb_blocks):
            enc2 = xor_for_char(enc[i * 16:(i + 1) * 16], IV) #xor a block with IV
            IV = cipher.encrypt(enc2) # set the the IV based on the encryption of the xored text
            print(codecs.decode(codecs.encode(IV, 'base64')).replace("\n", ""), end='') #print the encrypted text in base 64


def main(filepath):
    f = open(filepath, "r")
    if f.mode == 'r':
        content = f.readlines()
        tool = AESCBCTool()
        for line_content in content:
            tool.encrypt_CBC(bytes(line_content, "utf-8"), bytes("YELLOW SUBMARINE", "utf-8"))
    f.close()


if __name__== "__main__":
    try:
        main(argv[1]) #this is the path to the file that contains the text
    except Exception as e:
        print(e)
        exit(84)
    exit(0)

这是我的输出:

0TKm+DjGff6fB/l0Z+M5TQ==8do1FSVvjbN2+MhAULmjHA==w5vZtuiL2SrtSLi2CkMBzQ==nvKLm7C7QDmSxk2PqV3NHQ==2+DSu4BqXskn8/znFCUCcQ==

同时输出应该是:

IS4p7kpY9g0a68AUzpKzazbtbP0h3nYZvhptuxNajBS3KIUHGI3fu79e4fw+E34miyn5dMBle8Tqn2DvHsromy7AupMy0zbtlqPwU5uHoyY=

你对我有什么建议吗?

标签: pythonencryptionaespycryptocbc-mode

解决方案


推荐阅读