0
votes

I am trying to create an openssl aes encryption/decryption using php and c. I am able to encrypt text using php and openssl and this will output the encrypted string in a base64 string. I am trying to pass this base64 encoded string to a c program to decode it using openssl in c.

int decrypt(unsigned char *ciphertext,
            int ciphertext_len,
            unsigned char  *key,
            unsigned char *iv,
            unsigned char *plaintext)
{
    EVP_CIPHER_CTX *ctx;

    int len;

    int plaintext_len;

    /* Create and initialise the context */
    if(!(ctx = EVP_CIPHER_CTX_new())) handleErrors();

    if(1 != EVP_DecryptInit_ex(ctx, EVP_aes_256_cbc(), NULL, key, iv))
        handleErrors();

    if(1 != EVP_DecryptUpdate(ctx, plaintext, &len, ciphertext, ciphertext_len))
        handleErrors();
    plaintext_len = len;


    if(1 != EVP_DecryptFinal_ex(ctx, plaintext + len, &len)) handleErrors();
    plaintext_len += len;

    /* Clean up */
    EVP_CIPHER_CTX_free(ctx);

    return plaintext_len;
}

Is there any method to decrypt the base64 string using openssl in c ? i am able to decrypt it using the command line something like

openssl enc -aes-256-cbc -d -in file.encrypted -nosalt -nopad -K 31323334353637383132333435363738 -iv 31323334353637383132333435363738

Thanks in advance

1
klutt, Thanks for your reply, i also want to decrypt it using openssl after decodeDevelopers Staff
here is an example using cbc(not recommended to use) wiki.openssl.org/index.php/…Minory

1 Answers

1
votes

You are directly working on base64 encoded data. First you need to base64 decode the data to get the actual encrypted data. Then you will apply AES decryption to get the decrypted data

BIO *b64, *bmem;
buffer = (char *)malloc(datalength);
b64 = BIO_new(BIO_f_base64());
if(b64 == NULL)
{

    return NULL;
}
BIO_set_flags(b64, BIO_FLAGS_BASE64_NO_NL);  
bmem = BIO_new_mem_buf(input, length);
if(bmem == NULL)
{
    return NULL;
}
bmem = BIO_push(b64, bmem);
if(bmem == NULL)
{
    return NULL;
}

ret = BIO_read(bmem, buffer, length);
if(ret == 0)
{
    return NULL;
}
BIO_free_all(bmem);
return buffer;