gpt4 book ai didi

c++ - 转换 QString/QChar 以被 Crypto++ 接受

转载 作者:塔克拉玛干 更新时间:2023-11-03 07:36:28 25 4
gpt4 key购买 nike

我想制作加密(稍后解密)用户输入的字符串的程序。这是加密的开始:

QString getData = ui->text->toPlainText(); //Data to process
std::string output; //Result will be Base32 encoded string, so std::string is fine.

现在,我必须将 QString 转换为 char*std::string 以便它可以被 Crypto++ 接受。我认为 QByteArray 会很好,因为它有 .data() 函数,返回 char *。 (getData 总是 17 个或更多字节长:CryptoPP 需要至少 17 个字节用于 AES 加密)。所以,我使用了以下代码:

QByteArray data;
data.append(getData);

//Creating key and iv:

//Creating AES encryptor:

//Encrypting AES and Base32:
CryptoPP::StringSource ss((const byte*)data.data(), data.size() , true,
new CryptoPP::StreamTransformationFilter( Encryptor,
new CryptoPP::Base32Encoder(
new CryptoPP::StringSink(output)
) // Base32Encoder
) // StreamTransformationFilter
); // StringSource

ui->text->clear();
getData = output.c_str();
ui->text->setText(getData);

一切似乎都很好。但我希望它支持非 ASCII 字符(我的意思是俄语、立陶宛语等)。解密后,它们变为 ?。我该如何解决这个问题?我明白,std::string 不支持它们。


编辑:这是更新的代码:

加密:

QString getData = ui->text->toPlainText(); //Data to process
std::string output;

QByteArray data = getData.toUtf8();

//Creating key and iv: <..>

//Creating AES encryptor: <..>

//Encrypting AES and Base32:
CryptoPP::StringSource ss((const byte*) data.data(),getData.size()*2, true,
new CryptoPP::StreamTransformationFilter( Encryptor,
new CryptoPP::Base32Encoder(
new CryptoPP::StringSink(output)
) // Base32Encoder
) // StreamTransformationFilter
); // StringSource

ui->text->clear();
getData = output.c_str();
ui->text->setText(getData);

和解密:

QString getData = ui->text->toPlainText();
QByteArray data;
data.append(getData);
std::string output;

//Creating key and iv:
byte key[ CryptoPP::AES::DEFAULT_KEYLENGTH ],
iv[ CryptoPP::AES::BLOCKSIZE ];

//Memsetting them: (randomization needed)
::memset( key, 0x01, CryptoPP::AES::DEFAULT_KEYLENGTH );
::memset( iv, 0x01, CryptoPP::AES::BLOCKSIZE );

//Creating AES decryptor:
CryptoPP::CBC_Mode<CryptoPP::AES>::Decryption decryptor( key, sizeof(key), iv );

//Decrypting Base32 and AES
CryptoPP::StringSource ss((const byte*) data.data(), data.size(), true,
new CryptoPP::Base32Decoder(
new CryptoPP::StreamTransformationFilter( Decryptor,
new CryptoPP::StringSink(output)
) // StreamTransformationFilter
) // Base32Encoder
); // StringSource

ui->text->clear();
getData = QString::fromUtf8(output.c_str());
ui->text->setText(getData);

它是否有任何我遗漏的错误?

最佳答案

我认为您在从 QString 转换为 QByteArray 时会丢失数据。试试这个:

QByteArray data = getData.toUtf8();

...

getData = QString::fromUtf8( output.c_str() );

关于c++ - 转换 QString/QChar 以被 Crypto++ 接受,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3398304/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com