AES/CFB 密码模式从字符串解密失败

AES/CFB Cipher mode decrypting from the string fail

我好像误解了 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;
}

我想通了。

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

加密字符串的长度与新分配的字符串不一样,因为加密文本在数组的第 14 个字节处包含 '\0' 字符。