bcgit / bc-csharp

BouncyCastle.NET Cryptography Library (Mirror)
https://www.bouncycastle.org/csharp
MIT License
1.64k stars 551 forks source link

How to add Custom Alternative Names in Bouncy Castle #363

Closed smartkodian closed 1 year ago

smartkodian commented 2 years ago

I have this code to generate CSR ECDSA and it works fine, but I want to add these Alternative names to the CSR but don't know how to do it:

This is the code I am using in C# which can generate CSR and it works:

static  AsymmetricCipherKeyPair GeneratePkcs8Pkcs10(string countryIso2Characters, string state, string city, string companyName, string division, string domainName, string email, RootLenght rootLength)
{
    string csr = null;

    var curve = ECNamedCurveTable.GetByName("secp256k1");
    var domainParams = new ECDomainParameters(curve.Curve, curve.G, curve.N, curve.H, curve.GetSeed());

    var secureRandom = new SecureRandom();
    var keyParams = new ECKeyGenerationParameters(domainParams, secureRandom);

    var generator = new ECKeyPairGenerator("ECDSA");

    generator.Init(keyParams);
    AsymmetricCipherKeyPair Pair = generator.GenerateKeyPair();
    var cGenerator = new X509V3CertificateGenerator();
    IDictionary attrs = new Hashtable();

    attrs.Add(X509Name.C, countryIso2Characters);
    attrs.Add(X509Name.L, city);
    attrs.Add(X509Name.ST, state);
    attrs.Add(X509Name.O, companyName);
    if (division != null)
    {
        attrs.Add(X509Name.OU, division);
    }
    attrs.Add(X509Name.CN, domainName);
    if (email != null)
    {
        attrs.Add(X509Name.EmailAddress, email);
    }

    var subject = new X509Name(new ArrayList(attrs.Keys), attrs);

    var pkcs10CertificationRequest = new Pkcs10CertificationRequest(X9ObjectIdentifiers.ECDsaWithSha256.Id, subject, Pair.Public, null, Pair.Private);
    csr = Convert.ToBase64String(pkcs10CertificationRequest.GetEncoded());

    var privateKey = Pair.Private as ECPrivateKeyParameters;

    var pkInfo = PrivateKeyInfoFactory.CreatePrivateKeyInfo(Pair.Private);

    string privateKeyB64 = Convert.ToBase64String(pkInfo.GetDerEncoded());

    Console.WriteLine($"Private key: {privateKeyB64}");

    Console.WriteLine("-----BEGIN CERTIFICATE REQUEST-----");
    Console.WriteLine(SpliceText(csr, 64));
    Console.WriteLine("-----END CERTIFICATE REQUEST-----");
    ertificate Signing Request succesfully generated.");

    Console.ReadKey();
    return Pair;
}

the Alternate Names want to add SN=334623324234325, UID=310122393500003, title=0000, registeredAddress=Sample E, businessCategory=Sample Bussiness and also add extension: [req_ext] certificateTemplateName = ASN1:PRINTABLESTRING:ZATCA-Code-Signing subjectAltName = dirName:alt_names

peterdettman commented 1 year ago

This appears to essentially duplicate https://github.com/bcgit/bc-csharp/issues/364 .