-1

I am need to encrypt a string in AES CBC 128 bit mode through code only.I am done this with openssl library but i could not get correct output.

So far i have completed.

#include <cstring>
#include <iostream>
#include <openssl/evp.h>
#include <openssl/aes.h>

using namespace std;

int main(){
    string in = "abcdefgh";
    unsigned char input[in.length()];
    strcpy((char*) input, in.c_str());
    string key ="123456781234456678";
    unsigned char key_aes[key.length()];
    strcpy((char*) key_aes, key.c_str());
    cout<<input<<endl;
    cout<<key_aes<<endl;
    unsigned char iv[key.length()];
    strcpy((char*) iv, key.c_str());
    cout<<iv<<endl;
    const size_t encslength = ((in.length()/AES_BLOCK_SIZE)) * AES_BLOCK_SIZE;
    unsigned char out[encslength];
    memset(out, 0, sizeof(out));
    AES_KEY enc_key;
    AES_set_encrypt_key(key_aes,128, &enc_key);
    AES_cbc_encrypt(input,out,in.length(),&enc_key,iv,1);

    for(int i=0;out[i]!='\0';i++){

    printf("%X ",out[i]);

    }

    return 0;
}

And my hex output is : B0 15 75 1B 50 80 D4 FF 81 68 14 6B B7 1B 95 99 37 38

But the correct output is : 73 5C 04 F9 57 18 43 7C EE 68 27 59 2B 41 A8 DA ( verified with online site and through c# code).

Help me.. This question is already answered here but it is also not work for me. Thanks in advances.

Dhanasekaran Don
  • 294
  • 1
  • 14

1 Answers1

0
string in = "abcdefgh";
unsigned char input[in.length()];
strcpy((char*) input, in.c_str());

The strcpy function is for C-style strings. That means you need to make input large eonugh to hold "abcefgh" as a C-style string. However, you made it one byte too small because a C-style string has a nul terminator at the end.

string key ="123456781234456678";
unsigned char key_aes[key.length()];
strcpy((char*) key_aes, key.c_str());

Same thing again. Why are you constructing C++ string's from C-style strings only to convert them back to C-style strings?!

Then, you pass the C-style string to AES_set_encrypt. But the AES_set_encrypt function doesn't take a C-style string as input. So why are you creating these C-style strings?

David Schwartz
  • 179,497
  • 17
  • 214
  • 278