How to implement CBC-ECB encryption

So firstly I want to start with stating that this is a learning exercise and I’m not rolling my own encryption system for real world use.

Specifically I am trying to learn about encryption by doing some practical challenges and this is the one I am currently working on.

This challenge involves implementing your own CBC-ECB encryption/decryption algorithms. As I understand things currently to implement CBC-ECB you would take the current block of 16 bytes and the next block of 16 bytes, XOR them and then ECB encrypt the result.

The issue I am having is that whenever I encrypt a 16 byte block with the ECB encryption function below I need to encrypt 32 bytes. No matter how long my input is, in order to get the same length input back out when I decrypt I need to add an additional 16 bytes of padding to the end of the input.

So when I have 16 byte input I will need to also provided 16 bytes of padding. So I will need to store 32 bytes of encrypted output for every 16 bytes of plain text input.

Looking at other solutions to these challenges online it doesn’t look like other people are having this problem. It looks like they are getting 16 bytes of encrypted data for 16 bytes of input data. Following that the challenge also has a file that should be decryptable with a provided key that from looking at other peoples solutions doesn’t seem to have all of the additional padding.

Encryption and Decryption functions:

#include <stdio.h>
#include <string.h>
#include <stdint.h>
#include <stdlib.h>

#include <openssl/conf.h>
#include <openssl/evp.h>
#include <openssl/err.h>

typedef enum {
    BLOCK_SIZE_128_BIT      = 128 / 8,
    BLOCK_SIZE_256_BIT      = 256 / 8,
    BLOCK_SIZE_CUSTOM_VALUE = 0 
} paddingBlockSize;

typedef struct {
    void*    dataWithPadding;
    uint64_t dataLengthWithPadding;
    uint8_t  valueOfByteForPadding;
} PKCS7_Padding;  

typedef struct {
    void*    dataWithoutPadding;
    uint64_t dataLengthWithoutPadding;
    uint8_t  valueOfRemovedByteFromData;
} PKCS7_unPadding;

PKCS7_Padding* addPadding(const void* const data, const uint64_t dataLength, const uint8_t BLOCK_SIZE)
{
    if (0 == BLOCK_SIZE)
    {
        puts("ERROR: block size value must be 0 < BLOCK_SIZE < 256");
        exit(-1);
    }
    
    PKCS7_Padding* paddingResult = (PKCS7_Padding*) malloc(sizeof(PKCS7_Padding));
    if (NULL == paddingResult)
    {
        perror("problem with PKCS7_Padding* paddingResult");
        exit(-1);
    }

    uint8_t paddingBytesAmount           = BLOCK_SIZE - (dataLength % BLOCK_SIZE);
    paddingResult->valueOfByteForPadding = paddingBytesAmount;
    paddingResult->dataLengthWithPadding = dataLength + paddingBytesAmount; 
    
    uint8_t* dataWithPadding = (uint8_t*) malloc(paddingResult->dataLengthWithPadding);
    if (NULL == paddingResult)
    {
        perror("problem with uint8_t* dataWithPadding");
        exit(-1);
    }
    
    memcpy(dataWithPadding, data, dataLength); 
    for (uint8_t i = 0; i < paddingBytesAmount; i++)
    {
        dataWithPadding[dataLength + i] = paddingResult->valueOfByteForPadding;
    }
    paddingResult->dataWithPadding = dataWithPadding;

    return paddingResult;
}

PKCS7_unPadding* removePadding(const void* const data, const uint64_t dataLength)
{
    PKCS7_unPadding* unpaddingResult = (PKCS7_unPadding*) malloc(sizeof(PKCS7_unPadding));
    if (NULL == unpaddingResult)
    {
        perror("problem with PKCS7_Padding* unpaddingResult");
        exit(-1);
    }
    
    uint8_t paddingBytesAmount                  = *((uint8_t *)data + dataLength - 1);
    unpaddingResult->valueOfRemovedByteFromData = paddingBytesAmount; 
    unpaddingResult->dataLengthWithoutPadding   = dataLength - paddingBytesAmount;

    uint8_t* dataWithoutPadding = (uint8_t*) malloc(unpaddingResult->dataLengthWithoutPadding);
    if (NULL == dataWithoutPadding)
    {
        perror("problem with uint8_t* dataWithoutPadding");
        exit(-1);
    }

    memcpy(dataWithoutPadding, data, unpaddingResult->dataLengthWithoutPadding);   
    unpaddingResult->dataWithoutPadding = dataWithoutPadding;

    return unpaddingResult;
}

void freePaddingResult(PKCS7_Padding* puddingResult)
{
    free(puddingResult->dataWithPadding);
    free(puddingResult);
}

void freeUnPaddingResult(PKCS7_unPadding* unPuddingResult)
{
    free(unPuddingResult->dataWithoutPadding);
    free(unPuddingResult);
}

int ecb_encrypt(unsigned char *plain_bytes, unsigned char *key, unsigned char *cipher_bytes, size_t plain_bytes_len, size_t *cipher_bytes_len) {
    EVP_CIPHER_CTX *ctx;
    int len = 0;

    /*size_t padded_length = 0;
    if (plain_bytes_len % 16 > 0) {
        padded_length = plain_bytes_len + (16 - (plain_bytes_len % 16));
    } else {
        padded_length = plain_bytes_len + 16;
    }

    PKCS7_Padding *padded   = addPadding(plain_bytes, plain_bytes_len, padded_length);
    unsigned char *padded_message    = padded->dataWithPadding;
    plain_bytes_len = padded->dataLengthWithPadding;*/

    if(!(ctx = EVP_CIPHER_CTX_new()))
        return 4;

    if(1 != EVP_EncryptInit_ex(ctx, EVP_aes_128_ecb(), NULL, key, NULL))
        return 5;

    if(1 != EVP_EncryptUpdate(ctx, cipher_bytes, &len, plain_bytes, plain_bytes_len))//
    //if(1 != EVP_EncryptUpdate(ctx, cipher_bytes, &len, padded_message, plain_bytes_len))
        return 6;
    *cipher_bytes_len = len;

    if(1 != EVP_EncryptFinal_ex(ctx, cipher_bytes + *cipher_bytes_len, &len))
        return 7;

    EVP_CIPHER_CTX_free(ctx);
    return 0;
}

int ecb_decrypt(unsigned char *cipher_bytes, unsigned char *key, unsigned char *plain_bytes, size_t cipher_bytes_len, size_t *plain_bytes_len) {
    EVP_CIPHER_CTX *ctx;
    int len = 0;

    if(!(ctx = EVP_CIPHER_CTX_new()))
        return 4;

    if(1 != EVP_DecryptInit_ex(ctx, EVP_aes_128_ecb(), NULL, key, NULL))
        return 5;

    if(1 != EVP_DecryptUpdate(ctx, plain_bytes, &len, cipher_bytes, cipher_bytes_len))
        return 6;
    *plain_bytes_len = len;

    if(1 != EVP_DecryptFinal_ex(ctx, plain_bytes + *plain_bytes_len, &len))
        return 7;
    
    EVP_CIPHER_CTX_free(ctx);
    return 0;
}

int main() {
    unsigned char plain_text[] = "AAAAAAAAAAAAAAAABBBBBBBBBBBBBBBBCCCCCCCCCCCCCCCC";
    unsigned char key[]        = "ABCDEFGHIJKLMNOP";
    unsigned char cipher_bytes[strlen(plain_text)];
    size_t cipher_bytes_len = strlen(plain_text);

    ecb_encrypt(plain_text, key, (unsigned char *) &cipher_bytes, cipher_bytes_len, &cipher_bytes_len);

    size_t plain_bytes_len = 0;
    unsigned char plain_bytes[cipher_bytes_len];

    ecb_decrypt(cipher_bytes, key, (unsigned char *) &plain_bytes, cipher_bytes_len, &plain_bytes_len);

    printf("plain_bytes_len = %lun", plain_bytes_len);
    for(size_t i = 0; i < plain_bytes_len; i++){
        printf("%c", plain_bytes[i]);
    }
    printf("n");
       
    return 0;
}

This should compile as is using gcc main.c -lcrypto with gcc. If you run the code as is you will not receive the C’s from the plaintext when decrypting. If you uncomment the padding section in ecb_encrypt and change plain_bytes to padded_bytes in the call to EVP_EncryptUpdate you will see that the decryption occurs as expected getting the full plaintext back AAAAAAAAAAAAAAAABBBBBBBBBBBBBBBBCCCCCCCCCCCCCCCC.

I feel like there is something about how I am handling padding that is incorrect and causing these problems but I am not sure where I should start looking to diagnose the issue.

To add some context here I did not write the padding code, it’s from a library I found online and I copied it into the code here to make it easier for anyone trying to recreate the issue.

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật