/// <summary> /// Generate with the default key size /// </summary> public void GenerateCertificate() { CertificateGenerationParameters param = new CertificateGenerationParameters(); param.keyParam = null; param.keyStrength = RSAKeyPair.defaultKeyStrength; param.passphrase = RSAKeyPair.defaultPassphrase; GenerateCertificate(param); }
/// <summary> /// Used to generate the certificate with specific params which affect signing /// </summary> /// <param name="paramCertificate"></param> public void GenerateCertificate(CertificateGenerationParameters paramCertificate) { // set defaults or otherwise int keyStrength = (paramCertificate.keyStrength == 0) ? RSAKeyPair.defaultKeyStrength : paramCertificate.keyStrength; string keyPhrase = (paramCertificate.passphrase == null) ? RSAKeyPair.defaultPassphrase : paramCertificate.passphrase; // generate the RSA key pair RSAKeyPair pair = new RSAKeyPair(); pair.GenerateKeys(keyStrength); //set defaults or otherwise AsymmetricKeyParameter localKeyParam = (paramCertificate.keyParam == null) ? pair.KeyPair.Private : paramCertificate.keyParam; // set the public key which will be the newly generated one generator.SetPublicKey(pair.KeyPair.Public); // set the private key for the current certificate X509Certificate cert = generator.Generate(localKeyParam); // create the file name string filename = Path.GetFileNameWithoutExtension(Path.GetRandomFileName()); certificateFileName = String.Concat(filename, ".cer"); privateKeyFilename = String.Concat(filename, ".pvk"); string pathCertificate = Path.Combine(CertificateStore<CodeSigningCertificate>.CurrentInstance.CertificateStorePath, certificateFileName); string pathPrivateKey = Path.Combine(CertificateStore<CodeSigningCertificate>.CurrentInstance.CertificateStorePath, privateKeyFilename); // persist the DER encoded version of the certificate FileStream fileStream = File.Open(pathCertificate, FileMode.Create, FileAccess.Write); fileStream.Write(cert.GetEncoded(), 0, cert.GetEncoded().Length); fileStream.Close(); // persist the DER encoded version of the private key fileStream = File.Open(pathPrivateKey, FileMode.Create, FileAccess.Write); byte[] pvk = pair.ExportPrivateKey(keyPhrase); fileStream.Write(pvk, 0, pvk.Length); fileStream.Close(); }