Пример #1
0
 public static void SavePem(this X509Certificate2 @this, string certFile, string privateKeyFile = null)
 {
     try
     {
         Directory.CreateDirectory(Path.GetDirectoryName(certFile));
         if (!string.IsNullOrEmpty(privateKeyFile) && @this.HasPrivateKey)
         {
             Directory.CreateDirectory(Path.GetDirectoryName(privateKeyFile));
             var p   = @this.GetRSAPrivateKey().ExportParameters(true);
             var key = new RsaPrivateCrtKeyParameters(
                 new Org.BouncyCastle.Math.BigInteger(1, p.Modulus), new Org.BouncyCastle.Math.BigInteger(1, p.Exponent), new Org.BouncyCastle.Math.BigInteger(1, p.D),
                 new Org.BouncyCastle.Math.BigInteger(1, p.P), new Org.BouncyCastle.Math.BigInteger(1, p.Q), new Org.BouncyCastle.Math.BigInteger(1, p.DP), new Org.BouncyCastle.Math.BigInteger(1, p.DQ),
                 new Org.BouncyCastle.Math.BigInteger(1, p.InverseQ));
             using (var sw = new StreamWriter(privateKeyFile))
             {
                 var pemWriter = new Org.BouncyCastle.OpenSsl.PemWriter(sw);
                 pemWriter.WriteObject(key);
             }
         }
         File.WriteAllText(certFile, PemCertificateHelper.ExportCertificateToPEM(@this));
     }
     catch (Exception ex)
     {
         throw new Exception($"Certificate could not be saved. cert: {certFile} - key: {privateKeyFile}", ex);
     }
 }
Пример #2
0
 public static void SavePem(this X509Certificate2 @this, out string cert, out string privateKey)
 {
     cert       = string.Empty;
     privateKey = string.Empty;
     try
     {
         if (@this.HasPrivateKey)
         {
             var p   = @this.GetRSAPrivateKey().ExportParameters(true);
             var key = new RsaPrivateCrtKeyParameters(
                 new Org.BouncyCastle.Math.BigInteger(1, p.Modulus), new Org.BouncyCastle.Math.BigInteger(1, p.Exponent), new Org.BouncyCastle.Math.BigInteger(1, p.D),
                 new Org.BouncyCastle.Math.BigInteger(1, p.P), new Org.BouncyCastle.Math.BigInteger(1, p.Q), new Org.BouncyCastle.Math.BigInteger(1, p.DP), new Org.BouncyCastle.Math.BigInteger(1, p.DQ),
                 new Org.BouncyCastle.Math.BigInteger(1, p.InverseQ));
             using (var stringWriter = new StringWriter())
             {
                 var pemWriter = new Org.BouncyCastle.OpenSsl.PemWriter(stringWriter);
                 pemWriter.WriteObject(key);
                 privateKey = stringWriter.GetStringBuilder().ToString();
             }
         }
         cert = PemCertificateHelper.ExportCertificateToPEM(@this);
     }
     catch (Exception ex)
     {
         throw new Exception($"Certificate could not be saved.  ", ex);
     }
 }