Try using BIO_new_mem_buf() instead.

https://www.openssl.org/docs/crypto/BIO_s_mem.html



-----Original Message-----
From: owner-openssl-us...@openssl.org [mailto:owner-openssl-us...@openssl.org] 
On Behalf Of Ico
Sent: Monday, July 07, 2014 2:17 PM
To: openssl-users
Subject: Decrypting from memory bio vs file bio


Hi all,

I've got a small snippet of code to decode some aes-128-cbc data. 
The encrypted data 16 bytes long, decoding to 7 bytes "\x02\x00hallo".

Decoding using BIO's, works ok when the input BIO is a file BIO but fails when 
the input is a memory buffer BIO. In the latter case the BIO_read from the 
cipher bio returns -1.

See the snippet below or at http://pastebin.com/raw.php?i=1fxLQkFa

Change the 'if(1)' in 'if(0)' to switch between the two input bios.

I noticed that the decrypting works ok if I write some additional data in the 
input memory buffer using BIO_write(), but I believe this should not be 
necessary.

The data decodes properly using the openssl command line:

openssl aes-128-cbc -d \
        -K 2b7e151628aed2a6abf7158809cf4f3c \
        -iv a76d933653cb191de0b5ef789727fc64

Any insight in my problem much appreciated.

Ico



#include <stdio.h>
#include <assert.h>
#include <openssl/evp.h>
#include <openssl/bio.h>

char data[] = { 0xd7, 0x40, 0x9c, 0xe9, 0x81, 0xff, 0x41, 0xf1, 0xf8, 0x61, 
0xf5, 0xa9, 0x36, 0x99, 0x5b, 0x07 }; char key[]  = { 0x2b, 0x7e, 0x15, 0x16, 
0x28, 0xae, 0xd2, 0xa6, 0xab, 0xf7, 0x15, 0x88, 0x09, 0xcf, 0x4f, 0x3c };
char iv[]   = { 0xa7, 0x6d, 0x93, 0x36, 0x53, 0xcb, 0x19, 0x1d, 0xe0, 0xb5, 
0xef, 0x78, 0x97, 0x27, 0xfc, 0x64 };


int main(int argc, char **argv)
{
        int r;

        OpenSSL_add_all_digests();
        OpenSSL_add_all_ciphers();

        BIO *bio;

        if(1) {
                bio = BIO_new(BIO_s_mem());
                r = BIO_write(bio, data, sizeof(data));
                assert(r == sizeof(data));
        } else {
                FILE *f = fopen("/tmp/flop", "w");
                fwrite(data, 1, sizeof(data), f);
                fclose(f);
                bio = BIO_new_file("/tmp/flop", "r");
        }

        BIO *bio_dec = BIO_new(BIO_f_cipher());
        BIO_set_cipher(bio_dec, EVP_aes_128_cbc(), key, iv, 0);
        BIO_push(bio_dec, bio);

        char flop[2048];

        r = BIO_read(bio_dec, flop, sizeof flop-1);
        assert(r != -1);
        flop[r] = '\0';

        printf("r=%d '%s'\n", r, flop+2);

        return 0;
}

--
:wq
^X^Cy^K^X^C^C^C^C
______________________________________________________________________
OpenSSL Project                                 http://www.openssl.org
User Support Mailing List                    openssl-users@openssl.org
Automated List Manager                           majord...@openssl.org

Reply via email to