I'm compiling an app in C++Builder 10 Seattle, and trying to use OpenSSL for RSA work.
I followed this tutorial:
How to Use OpenSSL to Generate RSA Keys in C/C++
Here is the code:
#include <stdio.h>
#include <openssl/rsa.h>
#include <openssl/pem.h>
bool generate_key()
{
int ret = 0;
RSA *r = NULL;
BIGNUM *bne = NULL;
BIO *bp_public = NULL, *bp_private = NULL;
int bits = 2048;
unsigned long e = RSA_F4;
// 1. generate rsa key
bne = BN_new();
ret = BN_set_word(bne,e);
if(ret != 1){
goto free_all;
}
r = RSA_new();
ret = RSA_generate_key_ex(r, bits, bne, NULL);
if(ret != 1){
goto free_all;
}
// 2. save public key
bp_public = BIO_new_file("public.pem", "w+");
ret = PEM_write_bio_RSAPublicKey(bp_public, r);
if(ret != 1){
goto free_all;
}
// 3. save private key
bp_private = BIO_new_file("private.pem", "w+");
ret = PEM_write_bio_RSAPrivateKey(bp_private, r, NULL, NULL, 0, NULL, NULL);
// 4. free
free_all:
BIO_free_all(bp_public);
BIO_free_all(bp_private);
RSA_free(r);
BN_free(bne);
return (ret == 1);
}
int main(int argc, char* argv[])
{
generate_key();
return 0;
}
When I added libeay32.lib and ssleay32.lib to my project, I got an error message:
[ilink32 Error] Error: 'C:\USERS\ERICWANG\DESKTOP\TESTOPENSSL2\LIB\LIBEAY32.LIB' contains invalid OMF record, type 0x21 (possibly COFF)
I've seen some tips like using coff2omf and implib tools, but both didn't work.
I used
coff2omf.exeto convertlibeay32.lib. I putcoff2omf.exeandlibeay32.libin the same folder, and entered this command:coff2omf libeay32.lib Blibeay32.libIt said:
ERROR: COFF error: libeay32.lib : invalid machine type detected
I tried to convert
libeay32.libto a.dllfile usingimplib.exe. I entered this command:implib libeay32.lib Blibeay32.dllIt said:
Error : unable to open file
And my
libeay32.libchange its size to 1KB file. Which means the file was wrong.
OpenSSL works just fine in C++Builder. I use it in my own C++Builder apps.
You cannot use the
.libfiles that are included with the pre-compiled OpenSSL DLLs. Those.libfiles are meant for Visual Studio.In C++Builder, you need to use C++Builder's
implibormkexpcommand-line utility to create C++Builder-compatible import libs from the DLLs. Useimplibfor 32bit DLLs andmkexpfor 64bit DLLs.It works fine, I have been using this technique for years when new OpenSSL versions are released.
Your
implibcommand is wrong. You cannot "convertlibeay32.libto a.dllfile". The first parameter is an output parameter, the second parameter is an input parameter. You need to create a.libfile for an existing DLL. There is noBlibeay32.dllfile, which is why you are getting the "unable to open file" error. Drop theBand use the correct DLL filenames:This will create
.libor.afiles containing references for importing the functions fromlibeay32.dllandssleay32.dll, respectively.