-1

Hi everyone and thanks in advance for spending your time here.

So I got this .cpp file that output the following:

Cipher = (Bunch of strange caracters)

Decryp = Allo mon coco

So everything is fine... but if I swap the third commented line on top of the first one, I get the following output:

Cipher = (Bunch of strange caracters)Allo mon coco

Decryp = Allo mon coco

//Like that everything outputs well
#include "Crypto/MainCrypto.h"

namespace Crypto
    {MainCrypto::MainCrypto()
        {const unsigned char Key[16] = "Bob";
        const unsigned char IV[16] = "Random";
        AES128CBCEncrypt m_AES128CBCEncrypt(Key, IV, 0);
        AES128CBCDecrypt m_AES128CBCDecrypt(Key, IV, 0);

        unsigned char ciptxt[16];                   //1
        unsigned char dcptxt[16];                   //2
        unsigned char Data[16] = "Allo mon coco";   //3

        m_AES128CBCEncrypt.Encrypt(Data, 16, ciptxt);
        m_AES128CBCDecrypt.Decrypt(ciptxt, 16, dcptxt);

        std::cout << "Cipher = " <<  ciptxt << std::endl;
        std::cout << "Decryp = " << dcptxt << std::endl;
        }

    MainCrypto::~MainCrypto()
        {}
    }


//Like that, I'm getting unwanted Allo mon coco
#include "Crypto/MainCrypto.h"

namespace Crypto
    {MainCrypto::MainCrypto()
        {const unsigned char Key[16] = "Bob";
        const unsigned char IV[16] = "Random";
        AES128CBCEncrypt m_AES128CBCEncrypt(Key, IV, 0);
        AES128CBCDecrypt m_AES128CBCDecrypt(Key, IV, 0);

        unsigned char Data[16] = "Allo mon coco";   //3
        unsigned char ciptxt[16];                   //1
        unsigned char dcptxt[16];                   //2

        m_AES128CBCEncrypt.Encrypt(Data, 16, ciptxt);
        m_AES128CBCDecrypt.Decrypt(ciptxt, 16, dcptxt);

        std::cout << "Cipher = " <<  ciptxt << std::endl;
        std::cout << "Decryp = " << dcptxt << std::endl;
        }

    MainCrypto::~MainCrypto()
        {}
    }

weird

not weird

I don't have a clue why it does that. Please explain to me if you understand.

2 Answers2

0

I'm not sure about the bitcoin library, but I assume it's working correctly, so the likely culprit is the char arrays.

In C and C++ character arrays should be null terminated, otherwise It will not know when the string ends so it will output characters until it finds a '\0' character. So what happens here is basically memory leakage from another character array, since it's not null terminated.

To fix this add Data[15] = '\0'.

Arrrow
  • 542
  • 5
  • 21
0

The Encrypt library call is loading all 16 memory locations in ciptxt.

The "std::cout << "Cipher = " << ciptxt << std::endl;" statement expects ciptxt to be null terminated, but Encrypt is putting a non-null value in the 16th position. the std::cout statement will then continue printing characters until it reached a null value in memory. It is finding a null terminator in the dcptxt char array.

dernst
  • 72
  • 1
  • 5