c++ - 在 C++ 中使用 OpenSSL 加密 AES 中的字符串
问题描述
我有这个带有OpenSSL库的AES加密函数,它接收3个值作为参数,第一个是密钥(16个ASCII字符),第二个是要加密的消息(也是ASCII),第三个是大小消息,函数以string
格式返回加密字符串。
#include <stdlib.h>
#include <stdio.h>
#include <unistd.h>
#include <string.h>
#include <stdarg.h>
#include "openSSL/aes.h"
using namespace std;
string encAES(char* Key, char* Msg, int size)
{
static char* Res;
string output;
AES_KEY enc_key;
static const char* const lut = "0123456789ABCDEF";
Res = (char *)malloc(size);
AES_set_encrypt_key((unsigned char *)Key, 128, &enc_key);
for(int aux = 0; aux <= size; aux += 16)
{
AES_ecb_encrypt((unsigned char *)Msg + aux, (unsigned char *)Res + aux, &enc_key, AES_ENCRYPT);
}
output.reserve(2 * size);
for (size_t i = 0; i < size; ++i)
{
const unsigned char c = Res[i];
output.push_back(lut[c >> 4]);
output.push_back(lut[c & 15]);
}
free(Res);
return output;
}
这就是我调用和使用该函数的方式:
int main(int argc, char const *argv[])
{
char charKey[16 + 1] = {0};
char charMes[800 + 1] = {0};
//16 KEY ASCII
string str_key = "ABCDEFGHIJKLMNOP";
memset(charKey, 0, sizeof(charKey));
strcpy(charKey, str_key.c_str());
//Variable MESSAGE ASCII
string str_mes = "Hello World! This is a test chain.";
memset(charMes, 0, sizeof(charMes));
strcpy(charMes, str_mes.c_str());
string enc_mes = encAES(charKey, charMes, sizeof(charMes));
return 0;
}
我想要的是该函数encAES()
现在接收两个值: 中的键和消息string
,尝试以下但它会产生错误(我不知道,因为程序意外关闭):
string encAES2(string enc_key, string enc_message)
{
int enc_message_len = (enc_message.length() / 2);
unsigned char key1[16] = {0};
unsigned char in[800] = {0};
unsigned char out[800] = {0};
AES_KEY aes_key;
memset(key1, 0, sizeof(key1));
memset(in, 0, sizeof(in));
memset(out, 0, sizeof(out));
for(int aux = 0, str_len = enc_key.length(); aux != str_len; aux += 2)
{
int valor;
stringstream ss;
ss << std::hex << enc_key.substr(aux, 2);
ss >> valor;
key1[aux/2] = valor;
}
for(int aux = 0, str_len = enc_message.length(); aux != str_len; aux += 2)
{
int valor;
stringstream ss;
ss << std::hex << enc_message.substr(aux, 2);
ss >> valor;
in[aux/2] = valor;
}
AES_set_encrypt_key((unsigned char *)key1, 128, &aes_key);
for(int aux = 0; aux <= 320; aux += 16)
{
AES_ecb_encrypt((unsigned char *)(in + aux), (unsigned char *)(out + aux), &aes_key, AES_ENCRYPT);
}
string encrypt_str = unsignedcharHex_to_stringHex(out, 320);
return encrypt_str;
}
解决方案
推荐阅读
- gremlin - 在 AWS Neptune 上的 50M 边缘响应时间较短的 Gremlin
- javascript - 我怎样才能只允许单击我的图像?
- r - 官员::slip_in_footnote 无法让光标向前移动
- java - java.lang.IncompatibleClassChangeError:类型 com.google.gwt.dom.client.Style$Float$1 不是 com.google.gwt.dom.client.Style 的嵌套成员
- c++ - 如何从文本文件中读取 if 语句条件
- objective-c - 使用 requestDownloadFile 下载后 ICCameraDevice 删除:... 不起作用
- javascript - 从 Next JS 的公共文件夹中提供静态 JSON 文件
- java - Gradle 包装器用户名和密码在命令行中不起作用
- wordpress - 我对 Wordpress 上的 JWT 身份验证有疑问
- google-sheets - 删除行时防止索引格式错误