2

I'm trying to update this article's code to allow me to create (and use) an ECC based self signed certificate, and do basic signing and verification with it (ECDSA).

  • Is there any way to accomplish this with cross platform .NET Core APIs, or is Win32 P/Invoke required?

According to this post, I need to use the more standard id-ecctype

Ran Dom
  • 315
  • 5
  • 13
  • Do you really need to create certificate with C# code? It will be much simpler to do this with openssl command line API – Zergatul Dec 17 '18 at 17:32
  • @Zergatul OpenSSL isn't approved for use in the highly controlled environment I'm working with (neither is Bouncy Castle) – Ran Dom Dec 17 '18 at 17:46
  • Do you need to generate a lot of certificates on the fly? If not, you can generate certificate once with openssl and then use it in C#. – Zergatul Dec 17 '18 at 19:22
  • openssl (and bouncy castle) are not permitted in the restricted environment I'm working in. @Zergatul – Ran Dom Dec 17 '18 at 19:59
  • Well, if you cannot use libraries then you may have to program it yourself, don't you? I'd ask for a exception to that rule, because programming certificates - with all the ASN.1 involved - just isn't any fun. BC has a permissive license, so you could just copy the relevant parts (with proper contribution statement towards BC, of course). Warning: that may take some time to extract, it would be a lot of code. You might also want to look into the .NET code itself, it is also O/S licensed nowadays (I think, IANAL). – Maarten Bodewes Dec 18 '18 at 08:54
  • The answer says you can do ECDSA /unless/ you use id-ecDH. – bartonjs Dec 19 '18 at 15:57
  • @bartonjs Thank you for clarifying this. I updated the question – Ran Dom Dec 19 '18 at 16:03

1 Answers1

6

Is there any way to accomplish this with cross platform .NET Core APIs

Yep!

X509Certificate2 cert;

using (ECDsa key = ECDsa.Create(ECCurve.NamedCurves.nistP256))
{
    CertificateRequest request = new CertificateRequest(
        "CN=Self-Signed ECDSA",
        key,
        HashAlgorithmName.SHA256);

    request.CertificateExtensions.Add(
        new X509KeyUsageExtension(X509KeyUsageFlags.DigitalSignature, critical: false));

    request.CertificateExtensions.Add(
        new X509BasicConstraintsExtension(false, false, 0, false));

    // If it was for TLS, then Subject Alternative Names and
    // Extended (Enhanced) Key Usages would also be useful.

    DateTimeOffset start = DateTimeOffset.UtcNow;

    cert = request.CreateSelfSigned(notBefore: start, notAfter: start.AddMonths(3));
}

// If you want to save a PFX or something, you can do so now.
bartonjs
  • 30,352
  • 2
  • 71
  • 111