Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I create a self-signed certificate in OpenSSL programatically (i.e., not with the 'openssl' CLI command)?

My program uses OpenSSL, and needs to create a self-signed certificate on demand. The system it is running on does not have access to the 'openssl' CLI command, so I can't use that. Instead, I need to achieve this by using the OpenSSL X509 APIs.

Note that I do not need to create a certificate FILE, just a certificate; what OpenSSL calls an "X509" structure.

I can't find any documentation on how to do this.

How can I do this?

Thanks.

like image 208
Martin Del Vecchio Avatar asked Dec 21 '22 06:12

Martin Del Vecchio


1 Answers

here is a sample code which can be helpful

X509 *certificate = NULL;
EVP_PKEY *pkey = NULL;
int   ASN1_INTEGER *serialNumber = NULL;
int i = 0;
RSA *rsaKeyPair = NULL;
BIGNUM *e = NULL;
X509_NAME *name = NULL;
time_t currentTime;

certificate = X509_new();


rsaKeyPair = RSA_new();
e = BN_new();

BN_set_word(e, 65537);


if (!RSA_generate_key_ex(rsaKeyPair, 1024, e, NULL))
{
  ret = error;
}

/* the big number is no longer used */
BN_free(e);
e = NULL;



 EVP_PKEY_assign_RSA(pkey,rsaKeyPair))


  /* no more use for rsaKeyPair */
  rsaKeyPair = NULL;


  (void)X509_set_version(certificate,2);

  /*Allocate and create serial number*/
  serialNumber = M_ASN1_INTEGER_new();

  /*implement serial number algorithm here*/
  CreateSerialNumber(serialNumber);

  /* set the serial number */
  (void)X509_set_serialNumber(certificate,serialNumber);

  /*Serial number set to certificate, free it now*/
  M_ASN1_INTEGER_free(serialNumber); 
  serialNumber = NULL;

  /* set the validity */
  currentTime = time(0);

  X509_gmtime_adj(X509_get_notBefore(certificate), 0);

  X509_gmtime_adj(X509_get_notAfter(certificate), 1000);

  /* set the public key from the privateKey structure into the certificate structure */
  X509_set_pubkey(certificate,pkey);

  /* get the subject name pointer */
  name = X509_get_subject_name(certificate);}


/* country */
 X509_NAME_add_entry_by_txt(
  name,"C",MBSTRING_ASC, (unsigned char *)creationParams->Country, -1, -1, 0);

 !X509_NAME_add_entry_by_txt(name,"O", MBSTRING_ASC, (unsigned char*) "sample", -1, -1, 0);


X509_NAME_add_entry_by_txt(
  name,"CN",MBSTRING_ASC, (unsigned char*) creationParams->CommonName, -1, -1, 0);

 /* its self signed: set issuer name = subject  */
 X509_set_issuer_name(certificate,name);

 /* sign the certificate using sha-1 */
X509_sign(certificate,pkey,EVP_sha1());
like image 121
Sreekanth Avatar answered Jan 05 '23 00:01

Sreekanth