How can I create a self-signed server certificate?

0 votes
asked Oct 21, 2016 by Rebex KB (8,130 points)

I would like to create a self-signed X509 certificate for my server (for testing purposes). How can I do this using Rebex API?

1 Answer

0 votes
answered Oct 21, 2016 by Lukas Pokorny (85,170 points)

All Rebex component feature the CertificateIssuer class that can be used for this purpose.

Sample code:

using Rebex.Security.Certificates;
using Rebex.Security.Cryptography.Pkcs;

// specify certificate info
var info = new CertificateInfo();
info.EffectiveDate = DateTime.Now;
info.ExpirationDate = info.EffectiveDate.AddYears(2);
info.Subject = new DistinguishedName(", O=Example");
info.Usage = KeyUses.DigitalSignature;
info.SetExtendedUsage(new string[] { ExtendedUsageOids.ServerAuthentication });

// generate private key and create certificate
PrivateKeyInfo privateKey;
Certificate cert = CertificateIssuer.Issue(KeyAlgorithm.RSA, 2048, SignatureHashAlgorithm.SHA256, info, out privateKey);

// save certificate and key
cert.Save("example.crt", CertificateFormat.Base64Der);
privateKey.Save("example.pri", "password", PrivateKeyFormat.Base64Pkcs8);

To save both the certificate and private key into a single .p12/.pfx file instead of .crt and .pri, use this code:

cert.Associate(privateKey, true);
cert.Save("example.p12", CertificateFormat.Pfx, "password");