3

I'm trying to complete this challenge online which asks to implement ourselves the AES CBC mode without using any library function that will do the job for me (ofc xD). I'm using python3.7 and PyCrypto for the AES modules (I'm a python beginner btw)

I'm at a point where I feel like I found the solution but it's not the case, I don't see what I'm doing wrong. I'm entering this text: `

In september 2017 In september 2017 In september 2017 In september 2017

` with this key:

YELLOW SUBMARINE

and with an 16 bytes long IV full of 0 (\x00)

but my ouput differs from the different websites I can find online or when using the AES CBC mode from the PyCrypto module

here's the small program that I made so far in order to generate my aes cbc encryption with comments:

#!/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)

here's my output:

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

meanwhile the output should be:

IS4p7kpY9g0a68AUzpKzazbtbP0h3nYZvhptuxNajBS3KIUHGI3fu79e4fw+E34miyn5dMBle8Tqn2DvHsromy7AupMy0zbtlqPwU5uHoyY=

Do you have any advice for me please?

Cjdcoy
  • 317
  • 1
  • 2
  • 12

0 Answers0