Search code examples
c#cryptographybouncycastle.net-7.0

How to generate CSR with existing private and public key via .net7?


I’ll say right away that before writing I tried different options from this site. However, none of them came up. Initial data: there is a private and public key, for example and not for real case (suppose they are in a txt file or even in a line, it does not matter). If you need a different format for the public key (der, pem, crt), tell me, I can convert them.

-----BEGIN RSA PRIVATE KEY-----
MIIBOgIBAAJBAKj34GkxFhD90vcNLYLInFEX6Ppy1tPf9Cnzj4p4WGeKLs1Pt8Qu
KUpRKfFLfRYC9AIKjbJTWit+CqvjWYzvQwECAwEAAQJAIJLixBy2qpFoS4DSmoEm
o3qGy0t6z09AIJtH+5OeRV1be+N4cDYJKffGzDa88vQENZiRm0GRq6a+HPGQMd2k
TQIhAKMSvzIBnni7ot/OSie2TmJLY4SwTQAevXysE2RbFDYdAiEBCUEaRQnMnbp7
9mxDXDf6AU0cN/RPBjb9qSHDcWZHGzUCIG2Es59z8ugGrDY+pxLQnwfotadxd+Uy
v/Ow5T0q5gIJAiEAyS4RaI9YG8EWx/2w0T67ZUVAw8eOMB6BIUg0Xcu+3okCIBOs
/5OiPgoTdSy7bcF9IGpSE8ZgGKzgYQVZeN97YE00
-----END RSA PRIVATE KEY-----
-----BEGIN RSA PUBLIC KEY-----
MEgCQQCo9+BpMRYQ/dL3DS2CyJxRF+j6ctbT3/Qp84+KeFhnii7NT7fELilKUSnx
S30WAvQCCo2yU1orfgqr41mM70MBAgMBAAE=
-----END RSA PUBLIC KEY-----

There is a requirement: this code (and CSR generation) must work equally on both Linux and Windows. Purpose: csr saved on disk as a file.

The main problem is that I am not particularly strong in cryptography and it is still difficult to choose a tool. I watched both BouncyCastle and System.Security.Cryptography. It seems like a simple task for an experienced. Please, help.

I tried something like this (BouncyCastle):

byte[] derKeyBytes = File.ReadAllBytes("key.der");
AsymmetricKeyParameter publicKey = PublicKeyFactory.CreateKey(derKeyBytes);

and this

var rsaPublicKey = RSA.Create();
rsaPublicKey.ImportFromPem(publicKeyString);

in the first case there was an error, in the second it was not possible to reach the final result


Solution

  • I did it. Use.

    publicParameter and privateParameter are strings just like in the question above. With headers.

    private static string GenerateCsrPem(string hostname, string publicParameter, string privateParameter)
        {
            AsymmetricKeyParameter publicKeyParameter;
            AsymmetricKeyParameter privateKeyParameter;
            using (TextReader publicPem = new StringReader(publicParameter))
            {
                var publicPemReader = new PemReader(publicPem);
                var publicPemObject = publicPemReader.ReadObject();
                publicKeyParameter = (AsymmetricKeyParameter)publicPemObject;
            }
            using (TextReader privatePem = new StringReader(privateParameter))
            {
                var privatePemReader = new PemReader(privatePem);
                var privatePemObject = privatePemReader.ReadObject();
                privateKeyParameter = ((AsymmetricCipherKeyPair)privatePemObject).Private;
            }
            
            var asymmetricCipherKeyPair = new AsymmetricCipherKeyPair(publicKeyParameter, privateKeyParameter);
            var values = new Dictionary<DerObjectIdentifier, string> {
                {X509Name.CN, hostname}, //domain name
                {X509Name.O, "SS"},
                {X509Name.C, "JP"},
            };
            var subject = new X509Name(values.Keys.Reverse().ToList(), values);
            var csr = new Pkcs10CertificationRequest(
                "SHA256withRSA",
                subject,
                asymmetricCipherKeyPair.Public,
                null,
                asymmetricCipherKeyPair.Private); 
             
            var csrPem = new StringBuilder();
    
            var csrPemToWrite = csrPem.ToString();
            return csrPemToWrite;   
        }