SergeyBel/AES

Inconsistent encrypted Hex for Integers as string

saumyashah7 opened this issue · 1 comments

I have been trying to encrypt numbers as string. While trying to encrypt number "1" and "01" I get different encrypted Hex when I ran the program multiple times. For larger numbers like "456789" I do not encounter the same issue. Is there a requirement from minimum length for the string. Following is the code snippet I am using:


#include <iostream>
#include "AES.h"
const unsigned int BLOCK_BYTES_LENGTH = 16 * sizeof(unsigned char);

int main()
{

    AES* pAES=new AES(128);
    //string message = "Action123\0";
    string message = "01";
    //string message = "456789";
    cout << "String: "<< message << "\n";
    
    unsigned char vSecretAESKey[] =   { 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f };
    char* pRawMessage = new char[message.length()*2+1];
    memset(pRawMessage, 0, message.length()*2+1);
    std::memcpy(pRawMessage, message.c_str(), message.length()*2+1);

    unsigned int iEncryptedMessageSize = 0;
    unsigned char* pEncryptedMessageBytes = pAES->EncryptECB(reinterpret_cast<unsigned char*>(pRawMessage),
        static_cast<unsigned int>(message.length() * BLOCK_BYTES_LENGTH),
        reinterpret_cast<unsigned char*>(vSecretAESKey),
        iEncryptedMessageSize);
    cout << "Encrypted Hex: "; pAES->printHexArray(pEncryptedMessageBytes, message.length());
    cout << "\n";
    cout << "Encrypted String: "; pAES->printCharArray(pEncryptedMessageBytes, message.length());
    


    unsigned char* pDecryptedMessageBytes = pAES->DecryptECB(reinterpret_cast<unsigned char*>(pEncryptedMessageBytes),
        static_cast<unsigned int>(message.length() * BLOCK_BYTES_LENGTH),
        reinterpret_cast<unsigned char*>(vSecretAESKey));
    cout << "\n";
    cout << "Decrypted Hex: "; pAES->printHexArray(pDecryptedMessageBytes, message.length());
    cout << "\n";
    cout << "Decrypted String: "; pAES->printCharArray(pDecryptedMessageBytes, message.length());
    
    delete pAES;
    delete[] pRawMessage;
    delete[] pEncryptedMessageBytes;    
    delete[] pDecryptedMessageBytes;

    
    return 0;

}

Also I am using the same key each time.

In EncryptECB(unsigned char in[], unsigned int inLen, function parameter inLen means in char array length in bytes

In your example
"01" consists of 2 chars
But in inLen parameter you pass message.length() * BLOCK_BYTES_LENGTH = 2 * 16 * sizeof(unsigned char) = 32 * sizeof(unsigned char)

Since you didn't initialize 32 bytes in pRawMessage but only 5 bytes you can get unpredictable results after encrypt

Just write const unsigned int BLOCK_BYTES_LENGTH = sizeof(unsigned char); or inizialize 32 bytes in pRawMessage