Encrypt string data using AES in OpenSSL with C

0

I have this example of Encryption using the OpenSSL library and the AES encryption method:

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;
}

As a result, this function gives me a string of characters string but I am having problems trying to accept the function as parameters only the key and the message to be encrypted as string and not as a char* in this way :

string encAES(string Key, string Msg)

This is what I have but it has errors (I can not find the error)

string encAES(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 vuelta = 0; vuelta <= 320; vuelta += 16)
    {
        AES_ecb_encrypt((unsigned char *)(in + vuelta), (unsigned char *)(out + vuelta), &aes_key, AES_ENCRYPT);
    }

    string encrypt_str = unsignedcharHex_to_stringHex(out, 320); //Esta función no es tan importante

    return encrypt_str;
}
    
asked by Noe Cano 15.11.2018 в 00:48
source

0 answers