I'm trying to encrypt something with RSA.
But my rsa libary doesn't seam to be able to use x509 keys. So i tried to convert it to a DER key using openssl.
but i don't really understand how it works. i spotted two classes that seemed ok but i can't figure out how to use them.
the function are :
-i2d_X509
-X509
I did find a piece of code, but i can't understand it :
int len;
unsigned char *buf, *p;
len = i2d_X509(x, NULL);
buf = OPENSSL_malloc(len);
if (buf == NULL)
/* error */
p = buf;
i2d_X509(x, &p);
If you could help me out it would be great.
i2d_X509
means convert X509
object from internal representation (which is X509
structure) to DER encoded representation (which is copied over a buffer or in file).
So, in this code in line
len = i2d_X509(x, NULL);
you are determining the length of buffer or number of bytes required to represent the given certificate in DER from.
Then, you are allocating that much memory and final statement
len = i2d_X509(x, &p);
copies the X509 *
certificate into this buffer in DER format.
This buffer you can persist in the file and save it as a certificate file say .cer, .crt and can open with any certificate tool.
Coming back to your problem, you can use this buffer into your program which accepts DER certificate.
But you mentioned key, did you?
If you need RSA
public key, then you can do the following.
You may need to extract the key first by using X509_get_pubkey
which will give key in EVP_PKEY
structure.
EVP_PKEY * pkey;
pkey = X509_get_pubkey(x);
RSA * rsa;
rsa = EVP_PKEY_get1_RSA(pkey);
Now, output this RSA
structure into DER.
int len;
unsigned char *buf, *p;
len = i2d_RSAPublicKey(rsa, buffer, buffer_length);
Allocate buffer
to sufficient large length say 4000 depending on the key.
I think this would help you.