首页 > 解决方案 > 在 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;
}

标签: c++encryptionopenssl

解决方案


推荐阅读