AES / CFB Шифрование в режиме шифрования строки

Похоже, я неправильно понимаю, как работает режим шифрования CFB. Это приводит к ошибке. Подходы 1 и 2 не работают, потому что я читаю зашифрованный текст из созданной строки. Но подход 3 работает, потому что он получает зашифрованный текст из только что зашифрованной строки c. Не можете понять, почему?

Код:

#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;
}

0

Решение

Я понял.

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

Длина зашифрованной строки и вновь назначенной строки не совпадают, потому что зашифрованный текст содержит символ ‘\ 0’ в 14-м байте массива.

0

Другие решения

Других решений пока нет …