Hi,

There are two main mistakes in your code:
- The output of the MD5 is 16 bytes long but you are allocating 8 bytes only. This will cause memory corruption. - AES-256 expects the key to be 32-bytes long but you want to use an MD5 digest as a key which is only 16-bytes. You should use SHA-256 instead for this purpose.

I hope this will help.

Cheers,
--
Mounir IDRASSI
IDRIX
http://www.idrix.fr

himas wrote:
Hello, I wrote a source for encrypting and decrypting some text data
with aes_256_cbc:

---------- CODE ----------

void aes256cbc_encrypt(char *text, char *hkey)
{
    int i, outlen;
    unsigned char *outbuf = (unsigned char*)malloc(1024);
    unsigned char *inbuf = (unsigned char*)text;
    int inlen = strlen(text);
    unsigned char *key = (unsigned char*)hkey;
    //unsigned char key[] = "somevalue";

    EVP_CIPHER_CTX ctx;
    const EVP_CIPHER *cipher;

    EVP_CIPHER_CTX_init(&ctx);
    cipher = EVP_aes_256_cbc();
    EVP_EncryptInit(&ctx, cipher, key, NULL);

    EVP_EncryptUpdate(&ctx, outbuf, &outlen, inbuf, inlen);
    EVP_EncryptFinal(&ctx, outbuf + outlen, &outlen);

    for(i = 0; i < outlen; i++) printf("%02x", outbuf[i]);

    EVP_CIPHER_CTX_cleanup(&ctx);
    free(outbuf);
}

int aes256cbc_decrypt(char *ctext, char *hkey)
{
    int i, outlen;
    unsigned char *outbuf = (unsigned char*)malloc(1024);
    unsigned char *inbuf = (unsigned char*)ctext;
    int inlen = strlen(ctext);
    unsigned char *key = (unsigned char*)hkey;

    printf("cyphered text = %s\nhashed key = %s\n", ctext, hkey);

    EVP_CIPHER_CTX ctx;
    const EVP_CIPHER *cipher;

    EVP_CIPHER_CTX_init(&ctx);
    cipher = EVP_aes_256_cbc();
    EVP_DecryptInit(&ctx, cipher, key, NULL);

    EVP_DecryptUpdate(&ctx, outbuf, &outlen, inbuf, inlen);
    EVP_DecryptFinal(&ctx, outbuf + outlen, &outlen);

    printf("\n[*] decryption result\n");
    //for(i = 0; i < outlen; i++) printf("%02x", outbuf[i]);
    for(i = 0; i < 16; i++) printf("%02x", outbuf[i]);
    printf("\n%s \n", outbuf);

    EVP_CIPHER_CTX_cleanup(&ctx);
    free(outbuf);
}

main ()
{
    char *pass = "testtesttesttest";
    char *text = "testtesttesttest";
    char *ctext = "fdfb4ca253caf79c683b85787de8d094";

    // generating MD5 hash
    char *chash = (char*)malloc(8);
    MD5_Hash(pass, chash);
    //aes256cbc_crypt(text, chash);
    aes256cbc_decrypt(ctext, chash);
}

---------- CODE ----------

My questions concerning decryption are:
1. why don't I get outlen value?
2. why don't I get plaintext value after decryption (must be
"testtesttesttest")

______________________________________________________________________
OpenSSL Project                                 http://www.openssl.org
User Support Mailing List                    openssl-users@openssl.org
Automated List Manager                           majord...@openssl.org

Reply via email to