0 votes
by (8.4k 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?

Applies to: Rebex TLS

1 Answer

0 votes
by (145k 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("CN=example.org, 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");