Search code examples
c++encryptionaescrypto++cfb-mode

AES/CFB Cipher mode decrypting from the string fail


Seems like I misunderstand how is CFB cipher mode works. This leads to an error. Approaches 1 and 2 do not work because I am reading encrypted text from a created string. But approach 3 works because it gets crypted text from c string just encrypted. Can't figure it out why?

Code:

#include <string>
#include <iostream>
#include <fstream>
#include <vector>

#include "modes.h"
#include "aes.h"
#include "filters.h"

using namespace std;
using namespace CryptoPP;

int main()
{
    byte key[AES::DEFAULT_KEYLENGTH] = { '1', '2', '3', '4', '5', '6', '7', '8', '9', '0', '1', '2', '3', '4', '5', '6' };
    byte iv[AES::BLOCKSIZE] = { '3', '4', '5', '6', '7', '8', '9', '0', '1', '2', '3', '4', '5', '6', '7', '8' };

    string data = "fur fur fur fur fur";

    cout << "1: Original text: " << data << endl;

    CFB_Mode<AES>::Encryption cfbEncryption(key, sizeof(key), iv);
    const char* data_c_str = data.c_str();
    cfbEncryption.ProcessData((byte*)data_c_str, (byte*)data_c_str, data.length() + 1);

    cout << "2: Encrypted text: " << data_c_str << endl;

    string d(data_c_str); // after assigning c str to a string. Can get it to work!
    const char* data_c_str2 = d.c_str(); // get c str. Now the value of it the same as data_c_str. 

    // Approach 1 Failure

    string decr;

    CFB_Mode<AES>::Decryption cfbDecryption(key, sizeof(key), iv);

    StreamTransformationFilter stfDecryptor(cfbDecryption, new StringSink(decr));
    stfDecryptor.Put(reinterpret_cast<const unsigned char*>(data_c_str2), d.size() + 1);
    stfDecryptor.MessageEnd();

    cout << "3. Approach 1.: Decrypted text: " << decr << endl; // output "fur fur fur fur"

    // Approach 2 Failure

    CFB_Mode<AES>::Decryption cfbDecryption2(key, sizeof(key), iv);
    cfbDecryption2.ProcessData((byte*)data_c_str2, (byte*)data_c_str2, data.length() + 1);

    cout << "4. Approach 2.: Decrypted text: " << data_c_str2 << endl; // output "fur fur fur furЂuФX"


    // Approach 3 Success. Note that below code works properly because of usage data_c_str taken from data after encryption.

    CFB_Mode<AES>::Decryption cfbDecryption3(key, sizeof(key), iv);
    cfbDecryption3.ProcessData((byte*)data_c_str, (byte*)data_c_str, data.length() + 1);

    cout << "5. Approach 3.: Decrypted text: " << data_c_str << endl; // output "fur fur fur fur fur"

    cin.get();

    return 0;
}

Solution

  • I figured it out.

    auto dl = data.length();
    auto dl2 = d.length();
    
    cout << "Encrypted data length: " << dl << endl; // output: 19
    cout << "Encrypted data length at assigned string: " << dl2 << endl; // output: 14
    

    The length of encrypted string and newly assigned string are not the same because the encrypted text contains '\0' char at 14th byte of an array.