Crypto++ and garbage at end of string after performing AES decryption

Viewed 647

I am integrating Crypto++ into my C++ app and so far it's working, almost.

The encryption works perfect. The output matches what I would expect it to. However, when I go to decrypt, it's adding square characters on the end.

Here is my Encrypt function:

string Encryption::EncryptAES(const string &text, const string &key) {
    string cipher;

    AES::Encryption aes((byte *) key.c_str(), 32);

    ECB_Mode_ExternalCipher::Encryption ecb(aes);

    StreamTransformationFilter encrypt(ecb, new StringSink(cipher), StreamTransformationFilter::ZEROS_PADDING);

    encrypt.Put(reinterpret_cast<const unsigned char *>( text.c_str()), text.length() + 1);
    encrypt.MessageEnd();
    return Base64::Encode(cipher);
}

Here is my Decrypt function:

string Encryption::DecryptAES(const string &text, const string &key) {
    string decoded;
    Base64::Decode(text, decoded);
    string decrypted;

    AES::Decryption aes((byte *) key.c_str(), 32);
    ECB_Mode_ExternalCipher::Decryption ecb(aes);

    StreamTransformationFilter decrypt(ecb, new StringSink(decrypted), StreamTransformationFilter::ZEROS_PADDING);

    decrypt.Put(reinterpret_cast<const unsigned char *>( decoded.c_str()), decoded.length());
    decrypt.MessageEnd();

    return decrypted;
}

I'm using the following for the Base64 Encode/Decode: Base64 Encode/Decode

Here is the code I call to encrypt/decrypt:

string encryptedPass = EncryptAES(value, key);
cout << "Encrypted Text: " << encryptedPass << endl;

string decryptedPass = DecryptAES(encryptedPass, key);
cout << "Decryped Text: " << decryptedPass << endl;

Here is the output: enter image description here

When I copy and past the output into Notepad++, it's a bunch of spaces. I have a feeling it deals with the ZEROS_PADDING, but I need that in there to match our other applications that we are using.

I'm not sure how to actually try to fix this. Thoughts?

1 Answers

Based on the comments I was able to figure out what was at the end of the string. I knew it had to deal with zero padding, but due to being new at C++, I didn't fully understand what was going on.

I ran this to get the ascii value of the character:

for(char& c : s){
    cout << "Char:" << (int)c << endl;
}

This resulted in the following at the end of the string:

Char:0
Char:0
Char:0
Char:0
Char:0
Char:0

And according to the ASCII table it's NUL

So, the simple solution for this is to do this:

std::string(value.c_str());
Related