Generate self-signed Certificates from an Azure App Service

Dealing with certificates, especially with d.net, can be quite challenging.

I you are reading this, you probably experienced it you way already, having some CryptographicExceptions all over the place as you are running some code that used to work on your on-premise server, that you move to an Azure App.

Well… if you had it run under a VM the problem would have been gone; this is because you are the owner of ¬†you execution environment & therefore you are the only one doing things on it.

When it comes to Azure Apps, you are potentially not the only one on an instance first, and second the isolation level provided by Azure App service prohibits from running certain tasks (ever went pass a SecurityCritical attribute?)

Using the BouncyCastle framework (opensource crypto framework for .NET), you can actually generate those type of keys AND do that inside of an Azure App Service.

Here is the prebuilt method I use for building such self signed keys:


private AppCertKeyPairBase GenerateSelfSignedCertificate(string usageName, string password)
{
    var kpgen = new RsaKeyPairGenerator();
    kpgen.Init(new KeyGenerationParameters(new SecureRandom(new CryptoApiRandomGenerator()), 2048));

    var kp = kpgen.GenerateKeyPair();
    var gen = new X509V3CertificateGenerator();
    var certName = new X509Name($"cn={usageName}");
    var serialNo = BigInteger.ProbablePrime(120, new Random());

    gen.SetSerialNumber(serialNo);
    gen.SetSubjectDN(certName);
    gen.SetIssuerDN(certName);
    gen.SetNotAfter(DateTime.Now.AddYears(2));
    gen.SetNotBefore(DateTime.Now.AddDays(-1));
    gen.SetSignatureAlgorithm("SHA1withRSA");
    gen.SetPublicKey(kp.Public);

    gen.AddExtension(
        X509Extensions.AuthorityKeyIdentifier.Id,
        false,
        new AuthorityKeyIdentifier(
            SubjectPublicKeyInfoFactory.CreateSubjectPublicKeyInfo(kp.Public),
            new GeneralNames(new GeneralName(certName)),
            serialNo));

    gen.AddExtension(
        X509Extensions.ExtendedKeyUsage.Id,
        false,
        new ExtendedKeyUsage(new ArrayList() { new DerObjectIdentifier("1.3.6.1.5.5.7.3.1") }));

    var newCert = gen.Generate(kp.Private);
    var publicKey = DotNetUtilities.ToX509Certificate(newCert).Export(X509ContentType.Cert);
    var privateKey = ConvertBouncyToMicrosoft(newCert, kp, password);

    return new AppCertKeyPairBase { PublicKey = publicKey, PrivateKey = privateKey };
}

Now you can spawn as many certificates as you need!

Happy coding,

Leave a Reply

Your email address will not be published. Required fields are marked *