xyfix
xyfix

Reputation: 71

OpenSSL encryption/decryption command line in C++

can you tell me what the C++ equivalent is for the command line OpenSSL commands for encrypting a file:

openssl enc -nosalt -aes-256-cbc -kfile c:\temp\key -in c:\temp\binary.png -out c:\temp\binary.enc

and decrypting that file back again :

openssl enc -nosalt -aes-256-cbc -kfile c:\temp\key -d -in c:\temp\binary.enc -out c:\tmp\binary.png

Both lines above work on the command line but not in c++, I tried this :

   FILE* ifp = fopen( "c:\\tmp\\binary.png", "r");
    FILE* ofp = fopen( "c:\\tmp\\binary.enc", "w");
    FILE* keyp = fopen( "c:\\tmp\\key", "r");

    //Get file size
    fseek(ifp, 0L, SEEK_END);
    int fsize = ftell(ifp);
    //set back to normal
    fseek(ifp, 0L, SEEK_SET);

    //Get file size
    fseek(keyp, 0L, SEEK_END);
    int ksize = ftell(keyp);
    //set back to normal
    fseek(keyp, 0L, SEEK_SET);

    int outLen1 = 0; int outLen2 = 0;
    unsigned char* indata = (unsigned char *)malloc(fsize);
    unsigned char* outdata = (unsigned char *)malloc(fsize*2);
    unsigned char* kdata = (unsigned char* )malloc( ksize );


    //Read File
    fread(indata,sizeof(char),fsize, ifp);//Read Entire File
    fread(kdata,sizeof(char),ksize, keyp);

    //Set up encryption
    EVP_CIPHER_CTX* ctx = EVP_CIPHER_CTX_new();
    EVP_EncryptInit(ctx,EVP_aes_256_cbc(),kdata, NULL ); //no IV
    EVP_EncryptUpdate(ctx,outdata,&outLen1,indata,fsize);
    EVP_EncryptFinal(ctx,outdata + outLen1,&outLen2);
    fwrite(outdata,sizeof(char),outLen1 + outLen2,ofp);


    ::fclose( ifp );
    ::fclose( ofp );
    ::fclose( keyp );

I get an encrypted file from the C++ code but when I try to decrypt it via the command line, I get:

18784:error:0606506D:digital envelope routines:EVP_DecryptFinal_ex:wrong final block length:.\crypto\evp\evp_enc.c:532:```

Upvotes: 0

Views: 395

Answers (0)

Related Questions