Skip to content

Instantly share code, notes, and snippets.

@clasense4
Last active October 12, 2018 08:32
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save clasense4/6ccf76e723cc553d46845ca76623ceaf to your computer and use it in GitHub Desktop.
Save clasense4/6ccf76e723cc553d46845ca76623ceaf to your computer and use it in GitHub Desktop.
C# .Net 4.7.2 Create cert
using System;
using System.IO;
using System.Security.Cryptography;
using System.Security.Cryptography.X509Certificates;
namespace ConsoleApp
{
class Program
{
static string Domain = "serverless.id";
static string CommonName = Domain;
static string Country = "ID";
static string State = "Jawa Barat";
static string Locality = "Bandung";
static string Organization = "Serverless Indonesia";
static string OrganizationalUnit = "Serverless Engineer";
static string Email = "fajri@" + Domain;
static int ValidYear = 5;
static string CertOutPath = "c:\\temp\\";
static string PrivateKeyName = Domain + "-private_key.xml";
static string PfxKeyName = Domain + ".pfx";
static string PemKeyName = Domain + ".pem";
static void Main(string[] args)
{
GeneratePrivateKey(CertOutPath + PrivateKeyName);
string thumbprint = GenerateKeyFromXML(PrivateKeyName);
Console.WriteLine(thumbprint);
}
static void GeneratePrivateKey(string outPath)
{
var rsa = RSA.Create(2048);
File.WriteAllText(outPath, rsa.ToXmlString(true));
}
static string GenerateKeyFromXML(string privateKeyName)
{
// Read from xml file
var rsa_file = File.ReadAllText(CertOutPath + PrivateKeyName);
var rsa = RSA.Create();
rsa.FromXmlString(rsa_file.ToString());
// Generate New Certificate
var padding = RSASignaturePadding.Pkcs1;
//
string subject = "CN=" + CommonName + "/C=" + Country + "/ST=" + State + "/L=" + Locality + "/O=" + Organization + "/OU=" + OrganizationalUnit + "/emailAddress=" + Email;
var req = new CertificateRequest(subject, rsa, HashAlgorithmName.SHA256, padding);
var cert = req.CreateSelfSigned(DateTimeOffset.Now, DateTimeOffset.Now.AddYears(ValidYear));
// Create PFX (PKCS #12) with private key
File.WriteAllBytes(CertOutPath + PfxKeyName, cert.Export(X509ContentType.Pfx));
// Create Base 64 encoded CER (public key only)
File.WriteAllText(CertOutPath + PemKeyName,
"-----BEGIN CERTIFICATE-----\r\n"
+ Convert.ToBase64String(cert.Export(X509ContentType.Cert), Base64FormattingOptions.InsertLineBreaks)
+ "\r\n-----END CERTIFICATE-----");
return cert.Thumbprint;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment