c++ - c ++分段错误打印无符号字符
问题描述
尝试打印由函数填充的缓冲区时出现分段错误:
int ret = 0;
unsigned char plaintext;
/* ret will contain the length of the "plaintext" output buffer */
ret = gcm_decrypt( &ciphertext[0], ciphertext_len, &aad[0], aad_len, &tag[0], (unsigned char*)decoded_key.c_str(), &iv[0], iv_len, &plaintext );
/* This will segfault BUT it actually prints out the correct data */
std::string sName(reinterpret_cast<char*>(&plaintext)
cout << "ret: " << ret << endl;
cout << "plaintext: " << sName << endl;
我已经尝试了很多方法来从该纯文本缓冲区中获取 std::string ,但我无法弄清楚。
该功能需要一个unsigned char *
int gcm_decrypt(unsigned char *ciphertext, int ciphertext_len, unsigned char *aad, int aad_len, unsigned char *tag, unsigned char *key, unsigned char *iv, int iv_len, unsigned char *plaintext)
解决方案
根据@drescherjm 的建议,我将其更新为:
结束代码是
int main(void)
{
std::string key_encoded = "DgvkCrkyBNSy9yHP1Yznyc2DkHTIUXaO6NlEw4CSq0E=";
std::string decoded_key = base64_decode(key_encoded);
std::string token_encoded = "rj_ZkkZUOZMxZOfOmLpEUB3siU7u6RjZFeM9s-gb_xCR56WFKFAJiMyF2T6CBRmlh_Sy0i_lfyT9AI8sEif8MTIIszyzSl_aDnG48aO50yaHGuRSYbUbSYm9WIiQ0g==";
std::string token_decoded_tmp = base64_decode( token_encoded );
std::string token_decoded( token_decoded_tmp.begin()+32, token_decoded_tmp.end() );
int ciphertext_len = token_decoded.size();
std::string aad = "xxxxxxxxxxxxxxx";
int aad_len = aad.size();
std::string tag( token_decoded_tmp.begin()+16, token_decoded_tmp.end()+32 );
std::string iv( token_decoded_tmp.begin(), token_decoded_tmp.begin()+16 );
int iv_len = iv.size();
int ret = 0;
unsigned char plaintext[1024];
ret = gcm_decrypt(
(unsigned char*)token_decoded.c_str(),
ciphertext_len,
(unsigned char*)aad.c_str(),
aad_len,
(unsigned char*)tag.c_str(),
(unsigned char*)decoded_key.c_str(),
(unsigned char*)iv.c_str(),
iv_len,
plaintext
);
cout << "ret: " << ret << endl;
cout << "plaintext: <" << plaintext << ">" << endl;
return 0;
}
而且现在很完美。谢谢!
@drescherjm 我无法将您的答案标记为正确答案。
推荐阅读
- javascript - 我的 Bootstrap 网站需要很长时间才能加载。我使用来自 Envato 的模板 Celia 来构建它
- javascript - Braintree 中的托管字段给出错误“无法确定付款方式”PHP Laravel
- python - Python3 Odoo TypeError sys.print 不是函数
- python - 从具有特定格式的python字典中删除键
- c# - 文档上传 asp.net 站点,用户可以选择稍后重新上传更新的文档
- datatables - 如何在数据表中将文本更改为值
- ruby-on-rails - 当存在需要数据库操作的服务器发送事件 (SSE) 时,Rails 应用程序挂起
- apache-flink - 如何加入流和数据集?
- erlang - Erlang脚本分配变量
- python - 如何使用 MongoEngine 从参考字段中检索 pdf/图像?