I am trying to generate a new self-signed X509 certificate (instance of X509Certificate2
) with private key using Bouncy Castle. I googled some examples for RSA and I created this code based on these examples. I use Bouncy Castle for certificate generation and then I am trying to convert it to X509Certificate2
, but I do not know how to convert Bouncy Castle DSA private key (DSAPrivateKeyParameters
) to System.Security.Cryptography.DSAParameters
var keypairgen = new DsaKeyPairGenerator();
DsaParametersGenerator paramgen = new DsaParametersGenerator();
paramgen.Init(1024, 100, new SecureRandom());
DsaKeyGenerationParameters param = new DsaKeyGenerationParameters(new SecureRandom(), paramgen.GenerateParameters());
keypairgen.Init(param);
var keypair = keypairgen.GenerateKeyPair();
var gen = new X509V3CertificateGenerator();
var CN = new X509Name("CN=" + "TEST");
var SN = BigInteger.ProbablePrime(120, new Random());
gen.SetSerialNumber(SN);
gen.SetSubjectDN(CN);
gen.SetIssuerDN(CN);
gen.SetNotAfter(DateTime.MaxValue);
gen.SetNotBefore(DateTime.Now.Subtract(new TimeSpan(7, 0, 0, 0)));
gen.SetSignatureAlgorithm("sha1WithDSA");
gen.SetPublicKey(keypair.Public);
var newCert = gen.Generate(keypair.Private);
certificateDSA = new X509Certificate2(DotNetUtilities.ToX509Certificate((Org.BouncyCastle.X509.X509Certificate)newCert));
certificateDSA.PrivateKey = ToDotNetKey(keypair.Private); //!!!! this line !!!!
The problematic line is the last one. How should I implement this ToDotNetKey()
? I thought it would be some easy mapping of properties, but it was not. In DSAParameters
there is this property called J
(or Y
), which is not among Bouncy Castle parameters, for example, so I do not know what value I should put inside.
Please, help.
Finally I solved it by myself as a side result of another question. starting from the different direction: I generate the key pair in .NET and then I convert it using DotNetUtilities to Bouncy Castle.
The final working code is here, I hope it will help you: