コード例 #1
0
        /// <summary>
        /// Validates the certificate using OCSP server
        /// </summary>
        /// <param name="eecert">End entity certificate to be validated</param>
        /// <param name="issuerCert">Issuer of the end entity certificate to be used in validating</param>
        /// <param name="proxy">Optional if a web proxy is required</param>
        /// <returns>Validation status of the end entity certificate</returns>
        /// <exception cref="OCSPExpection">Thrown when there is no OCSP URL in certificate or the OCSP URL in unreachable<exception>
        public static bool ValidateCertificateWithOCSP(X509Certificate2 eecert, X509Certificate2 issuerCert, WebProxy proxy = null)
        {
            Org.BouncyCastle.X509.X509Certificate bouncyeecert     = Org.BouncyCastle.Security.DotNetUtilities.FromX509Certificate(eecert);
            Org.BouncyCastle.X509.X509Certificate bouncyissuercert = Org.BouncyCastle.Security.DotNetUtilities.FromX509Certificate(issuerCert);

            if (!bouncyeecert.IssuerDN.Equivalent(bouncyissuercert.SubjectDN))
            {
                return(false); //Not the same issuer.
            }
            try
            {
                bouncyeecert.CheckValidity();
                bouncyeecert.Verify(bouncyissuercert.GetPublicKey());
                OCSPVerifier crypto = new OCSPVerifier();

                return(crypto.Query(bouncyeecert, bouncyissuercert, proxy) == OCSPVerifier.CertificateStatus.Good);
            }
            catch (OCSPExpection ocspe)
            {
                throw ocspe;//send to API user.
            }
            catch (WebException webx)
            {
                throw new OCSPExpection("Exception in accessing OCSP web server. Error: " + webx.Message);
            }
            catch (Exception)
            {
                //If any general exception is raised then there is a problem in validation, so return false.
                return(false);
            }
        }
コード例 #2
0
        public static void CreateSignature(System.Security.Cryptography.X509Certificates.X509Certificate2 mycert)
        {
            // https://www.programcreek.com/java-api-examples/?api=org.bouncycastle.x509.X509V3CertificateGenerator
            // https://forums.asp.net/t/2154987.aspx?Create+Self+Signed+Certificate+programatically+uisng+C+

            // System.Security.Cryptography.X509Certificates.X509Certificate2.CreateFromCertFile()


            // https://overcoder.net/q/429916/bouncycastle-privatekey-to-x509%D1%81%D0%B5%D1%80%D1%82%D0%B8%D1%84%D0%B8%D0%BA%D0%B0%D1%822-privatekey
            // https://www.csharpcodi.com/csharp-examples/Org.BouncyCastle.X509.X509Certificate.GetPublicKey()/

            Org.BouncyCastle.Crypto.AsymmetricKeyParameter Akp = Org.BouncyCastle.Security.DotNetUtilities.GetKeyPair(mycert.PrivateKey).Private;


            // if(mycert.HasPrivateKey)
            Org.BouncyCastle.Crypto.AsymmetricKeyParameter bouncyCastlePrivateKey = TransformRSAPrivateKey(mycert.PrivateKey);



            Org.BouncyCastle.X509.X509CertificateParser    certParser        = new Org.BouncyCastle.X509.X509CertificateParser();
            Org.BouncyCastle.X509.X509Certificate          bouncyCertificate = certParser.ReadCertificate(mycert.GetRawCertData());
            Org.BouncyCastle.Crypto.AsymmetricKeyParameter pubKey            = bouncyCertificate.GetPublicKey();

            Org.BouncyCastle.Crypto.IDigest algorithm = Org.BouncyCastle.Security.DigestUtilities.GetDigest(bouncyCertificate.SigAlgOid);
            // X509Certificate2Signature signature = new X509Certificate2Signature(mycert, algorithm);
            // https://github.com/kusl/itextsharp/blob/master/tags/iTextSharp_5_4_5/src/core/iTextSharp/text/pdf/security/X509Certificate2Signature.cs
            // Sign

            // PemReader pem = new PemReader();
            // pem.ReadPemObject().Headers
            // RSACryptoServiceProvider rsa = pem.ReadPrivateKeyFromFile("PrivateKey.pem");
        }
コード例 #3
0
        public static byte[] CreateSelfSignedCertificate(string[] alternativeNames, string password)
        {
            string pemKey  = SecretManager.GetSecret <string>("skynet_key");
            string pemCert = SecretManager.GetSecret <string>("skynet_cert");

            Org.BouncyCastle.Crypto.AsymmetricCipherKeyPair rootKey  = ReadAsymmetricKeyParameter(pemKey);
            Org.BouncyCastle.X509.X509Certificate           rootCert = PemStringToX509(pemCert);

            Org.BouncyCastle.Security.SecureRandom          random      = new Org.BouncyCastle.Security.SecureRandom(NonBackdooredPrng.Create());
            Org.BouncyCastle.Crypto.AsymmetricCipherKeyPair certKeyPair = KeyGenerator.GenerateRsaKeyPair(2048, random);

            Org.BouncyCastle.X509.X509Certificate sslCertificate = SelfSignSslCertificate(
                random
                , rootCert
                , certKeyPair.Public
                , rootKey.Private
                , alternativeNames
                );

            bool val = CerGenerator.ValidateSelfSignedCert(sslCertificate, rootCert.GetPublicKey());

            if (val == false)
            {
                throw new System.InvalidOperationException("SSL certificate does NOT validate successfully.");
            }

            byte[] pfx = CreatePfxBytes(sslCertificate, certKeyPair.Private, password);
            return(pfx);
        } // End Function CreateSelfSignedCertificate
コード例 #4
0
        // https://www.csharpcodi.com/csharp-examples/Org.BouncyCastle.X509.X509Certificate.GetPublicKey()/
        public static bool CheckRequestSignature(
            byte[] serializedSpeechletRequest
            , string expectedSignature
            , Org.BouncyCastle.X509.X509Certificate cert)
        {
            byte[] expectedSig = null;
            try
            {
                expectedSig = System.Convert.FromBase64String(expectedSignature);
            }
            catch (System.FormatException)
            {
                return(false);
            }

            Org.BouncyCastle.Crypto.Parameters.RsaKeyParameters publicKey =
                (Org.BouncyCastle.Crypto.Parameters.RsaKeyParameters)cert.GetPublicKey();

            Org.BouncyCastle.Crypto.ISigner signer =
                Org.BouncyCastle.Security.SignerUtilities.GetSigner("Sdk.SIGNATURE_ALGORITHM");

            signer.Init(false, publicKey);
            signer.BlockUpdate(serializedSpeechletRequest, 0, serializedSpeechletRequest.Length);

            return(signer.VerifySignature(expectedSig));
        }
コード例 #5
0
        public static (AsymmetricKeyParameter PubKey, AsymmetricKeyParameter PrivKey, X509Certificate Certificate) PEMToAsymmetricCipherKeyPairAndCert(string pemKey)
        {
            if (string.IsNullOrEmpty(pemKey))
            {
                throw new CryptoException("private key cannot be null");
            }
            AsymmetricKeyParameter privkey = null;
            AsymmetricKeyParameter pubkey  = null;
            X509Certificate        cert    = null;

            using (StringReader ms = new StringReader(pemKey))
            {
                PemReader pemReader = new PemReader(ms);
                object    o;
                while ((o = pemReader.ReadObject()) != null)
                {
                    if (o is AsymmetricKeyParameter)
                    {
                        AsymmetricKeyParameter par = (AsymmetricKeyParameter)o;
                        if (par.IsPrivate)
                        {
                            privkey = par;
                        }
                        else
                        {
                            pubkey = par;
                        }
                    }

                    if (o is AsymmetricCipherKeyPair)
                    {
                        privkey = ((AsymmetricCipherKeyPair)o).Private;
                        pubkey  = ((AsymmetricCipherKeyPair)o).Public;
                    }

                    if (o is X509Certificate)
                    {
                        X509Certificate cc = (X509Certificate)o;
                        pubkey = cc.GetPublicKey();
                        cert   = cc;
                    }
                }
            }

            if (pubkey != null || privkey != null)
            {
                if (privkey != null && pubkey == null)
                {
                    pubkey = DerivePublicKey(privkey);
                }
            }

            if (pubkey == null && privkey == null && cert == null)
            {
                throw new CryptoException("Invalid Certificate");
            }
            return(pubkey, privkey, cert);
        }
コード例 #6
0
        /// <summary>
        /// Validates the certificate using CRL
        /// </summary>
        /// <param name="eeCert">End entity certificate to be validated</param>
        /// <param name="issuerCert">Issuer of the end entity certificate to be used in validating</param>
        /// <param name="online">CRL validation should be on-line or by using a file</param>
        /// <param name="CRLfilepath">Optional CRL file path required if the on-line parameters is false</param>
        /// <param name="proxy">Optional if a web proxy is required</param>
        /// <returns>Validation status of the end entity certificate</returns>
        /// <exception cref="CRLExpection">Thrown when there problem with the CRL</exception>
        public static bool ValidateCertificateWithCRL(X509Certificate2 eeCert, X509Certificate2 issuerCert, bool online, string CRLfilepath = null, WebProxy proxy = null)
        {
            Org.BouncyCastle.X509.X509Certificate bouncyeecert     = Org.BouncyCastle.Security.DotNetUtilities.FromX509Certificate(eeCert);
            Org.BouncyCastle.X509.X509Certificate bouncyissuercert = Org.BouncyCastle.Security.DotNetUtilities.FromX509Certificate(issuerCert);

            if (!bouncyeecert.IssuerDN.Equivalent(bouncyissuercert.SubjectDN))
            {
                return(false); //Not the same issuer.
            }
            try
            {
                bouncyeecert.CheckValidity();
                bouncyeecert.Verify(bouncyissuercert.GetPublicKey());
            }
            catch (Exception)
            {
                return(false); /*The issuer public key does not match the signature in the certificate.*/
            }

            try
            {
                CRLVerifier crl = null;
                crlDictionary.TryGetValue(issuerCert.GetCertHashString(), out crl);
                if (crl == null)
                {
                    crl = new CRLVerifier(issuerCert);
                    crlDictionary.Add(issuerCert.GetCertHashString(), crl);
                }

                bool IsInCRL = false;
                if (online)
                {
                    IsInCRL = crl.IsCertificateInOnlineCRL(eeCert, crl.GetBaseCrlUrl(eeCert), proxy);
                }
                else
                {
                    IsInCRL = crl.IsCertificateInCrlFile(eeCert, CRLfilepath);
                }
                return(!IsInCRL);
            }
            catch (CRLExpection crle)
            {
                throw crle;//send to API user.
            }
            catch (WebException webx)
            {
                throw new CRLExpection("Exception in accessing CRL web server. Error: " + webx.Message);
            }
            catch (IOException iox)
            {
                throw new CRLExpection("Exception in accessing CRL file. Error: " + iox.Message);
            }
            catch (Exception)
            {
                return(false);
            }
        }
コード例 #7
0
        public static void Test()
        {
            string pfxLocation = @"D:\lol\certificate.pfx";

            pfxLocation = @"D:\username\Desktop\DesktopArchiv\20180329_Desktop\CORMailService\CORMailService\CORMailService\CORMailService_TemporaryKey.pfx";


            Org.BouncyCastle.Pkcs.Pkcs12Store store = null;

            using (System.IO.Stream pfxStream = System.IO.File.OpenRead(pfxLocation))
            {
                store = new Org.BouncyCastle.Pkcs.Pkcs12Store(pfxStream, "".ToCharArray());
            }

            System.Console.WriteLine(store);

            foreach (string alias in store.Aliases)
            {
                System.Console.WriteLine(alias);

                // https://7thzero.com/blog/bouncy-castle-convert-a-bouncycastle-asymmetrickeyentry-to-a-.ne
                if (store.IsKeyEntry((string)alias))
                {
                    Org.BouncyCastle.Pkcs.AsymmetricKeyEntry keyEntry = store.GetKey(alias);
                    System.Console.WriteLine(keyEntry);
                    Org.BouncyCastle.Crypto.AsymmetricKeyParameter privateKey = keyEntry.Key;
                    System.Console.WriteLine(privateKey.IsPrivate);
                } // End if (store.IsKeyEntry((string)alias))


                Org.BouncyCastle.Pkcs.X509CertificateEntry certEntry = store.GetCertificate(alias);
                Org.BouncyCastle.X509.X509Certificate      cert      = certEntry.Certificate;
                System.Console.WriteLine(cert);

                Org.BouncyCastle.Crypto.AsymmetricKeyParameter publicKey = cert.GetPublicKey();
                System.Console.WriteLine(publicKey);

                // Org.BouncyCastle.Pkcs.X509CertificateEntry[] chain = store.GetCertificateChain(alias);

                // System.Security.Cryptography.X509Certificates.X509Certificate2 cert2 = new System.Security.Cryptography.X509Certificates.X509Certificate2(cert.GetEncoded());
                // Org.BouncyCastle.Security.DotNetUtilities.ToX509Certificate(cert);

                System.Security.Cryptography.X509Certificates.X509Certificate2 cert2 = new System.Security.Cryptography.X509Certificates.X509Certificate2(pfxLocation);
                // cert2.PrivateKey = null;

                if (cert2.HasPrivateKey)
                {
                    System.Console.WriteLine(cert2.PrivateKey);
                }
            }
        }
コード例 #8
0
        /// <summary>
        /// Checks whether certificate is self-signed
        /// </summary>
        /// <param name="certificate">Certificate to be checked</param>
        /// <returns>True if certificate is self-signed; false otherwise</returns>
        public static bool IsSelfSigned(Org.BouncyCastle.X509.X509Certificate certificate)
        {
            if (certificate == null)
            {
                throw new ArgumentNullException("certificate");
            }

            try
            {
                certificate.Verify(certificate.GetPublicKey());
                return(true);
            }
            catch (Org.BouncyCastle.Security.InvalidKeyException)
            {
                return(false);
            }
        }
コード例 #9
0
        public string Encrypt(string plainText)
        {
            byte[] plainBytes            = Encoding.UTF8.GetBytes(plainText);
            CmsProcessableByteArray cpba = new CmsProcessableByteArray(plainBytes);

            CmsEnvelopedDataGenerator envelopedGen = new CmsEnvelopedDataGenerator();

            foreach (X509Certificate2 cert in publicCerts)
            {
                Org.BouncyCastle.X509.X509Certificate bouncyCert = DotNetUtilities.FromX509Certificate(cert);
                AsymmetricKeyParameter keyParameter = bouncyCert.GetPublicKey();
                envelopedGen.AddKeyTransRecipient(bouncyCert);
            }

            CmsEnvelopedData envelopedData = envelopedGen.Generate(cpba, CmsEnvelopedGenerator.Aes256Cbc);
            string           cipherString  = Convert.ToBase64String(envelopedData.GetEncoded());

            return(cipherString);
        }
コード例 #10
0
        // https://twitter.com/HackerNewsOnion/status/740228588520247296?lang=en
        // Announcing Let’s Decrypt, A SSL Certificate Authority Backed By The NSA

        // Talk about throwing a skunk in the jury pool! I feel like now we need proof this is fiction!
        // ok this activated my paranoia.
        // Announcing Let’s Decrypt, A SSL Certificate Authority Backed By The NSA < It’s totes secure. Promise.
        public static async System.Threading.Tasks.Task Main(string[] args)
        {
            // CreateSslCertificate();
            // SetRegistry();
            // SelfSignedCertificateGenerator.Test.MonitoringTest.TestMonitorChanges();

            string pemKey  = SecretManager.GetSecret <string>("skynet_key");
            string pemCert = SecretManager.GetSecret <string>("skynet_cert");


            Org.BouncyCastle.Crypto.AsymmetricCipherKeyPair rootKey = ReadAsymmetricKeyParameter(pemKey);
            System.Console.WriteLine(rootKey.Private);

            Org.BouncyCastle.X509.X509Certificate rootCert = PemStringToX509(pemCert);
            System.Console.WriteLine(rootCert);

            Org.BouncyCastle.Security.SecureRandom          random      = new Org.BouncyCastle.Security.SecureRandom(NonBackdooredPrng.Create());
            Org.BouncyCastle.Crypto.AsymmetricCipherKeyPair certKeyPair = KeyGenerator.GenerateRsaKeyPair(2048, random);

            Org.BouncyCastle.X509.X509Certificate sslCertificate = SelfSignSslCertificate(
                random
                , rootCert
                , certKeyPair.Public
                , rootKey.Private
                );

            bool val = CerGenerator.ValidateSelfSignedCert(sslCertificate, rootCert.GetPublicKey());

            if (val == false)
            {
                throw new System.InvalidOperationException("SSL certificate does NOT validate successfully.");
            }


            CreatePfxBytes(sslCertificate, certKeyPair.Private, "");

            System.Console.WriteLine(" --- Press any key to continue --- ");
            System.Console.ReadKey();

            await System.Threading.Tasks.Task.CompletedTask;
        }
コード例 #11
0
ファイル: Certificate.cs プロジェクト: gerardofb/IFTFirma
 public void ReadPublic()
 {
     try
     {
         System.IO.StringWriter stWrite = new System.IO.StringWriter();
         Certificado = new X509Certificate2(CertificateBytes);
         Org.BouncyCastle.X509.X509Certificate cert = DotNetUtilities.FromX509Certificate(Certificado);
         PubliceyParameter = cert.GetPublicKey();
         MemoryStream ms     = new MemoryStream();
         TextWriter   writer = new StreamWriter(ms);
         Org.BouncyCastle.OpenSsl.PemWriter pmw = new Org.BouncyCastle.OpenSsl.PemWriter(stWrite);
         pmw.WriteObject(PubliceyParameter);
         stWrite.Close();
         PublicKeyRSA = stWrite.ToString();
         Datos        = DatosCert.GetDatosCert(CertificateBytes);
     }
     catch (Exception exe)
     {
         throw new Exception(Resource.ErrorCertificado);
     }
 }
コード例 #12
0
        public static void RootVerifyUserCA()
        {
            try
            {
                X509Certificate2 userCert2 = new X509Certificate2(CAUserPfx, PIN, X509KeyStorageFlags.Exportable);
                X509Certificate  userCert  = DotNetUtilities.FromX509Certificate(userCert2);
                userCert2.p
                var userKeyPair = userCert.GetPublicKey();
                //var publicKey = userCert2.PublicKey;
                X509Certificate2 rootCert2 = new X509Certificate2(CARootPfx, PIN, X509KeyStorageFlags.Exportable);
                //var rootKeyPair = Cert2.ReadPrivateKey(rootCert2);
                var add         = Cert2.AddCertToStore(rootCert2, StoreName.Root, StoreLocation.LocalMachine);
                var rootCert    = DotNetUtilities.FromX509Certificate(userCert2);
                var rootKeyPair = rootCert.GetPublicKey();

                //rootCert.Verify(userKeyPair);
                var a = Cert2.VerifySha2(rootCert2, userCert.GetEncoded(), userCert.GetSignature());
            }
            catch (Exception ex)
            {
                //throw;
            }
        }
コード例 #13
0
ファイル: Program.cs プロジェクト: triozillion/MyBlog
        } // End Sub Test

        public static void SelfSignSslCertificate(Org.BouncyCastle.Security.SecureRandom random, Org.BouncyCastle.X509.X509Certificate caRoot, Org.BouncyCastle.Crypto.AsymmetricKeyParameter rootCertPrivateKey) // PrivatePublicPemKeyPair subjectKeyPair)
        {
            Org.BouncyCastle.X509.X509Certificate caSsl = null;

            string countryIso2Characters = "GA";
            string stateOrProvince       = "Aremorica";
            string localityOrCity        = "Erquy, Bretagne";
            string companyName           = "Coopérative Ménhir Obelix Gmbh & Co. KGaA";
            string division   = "NT (Neanderthal Technology)";
            string domainName = "localhost";

            domainName = "*.sql.guru";
            domainName = "localhost";
            string email = "webmaster@localhost";


            CertificateInfo ci = new CertificateInfo(
                countryIso2Characters, stateOrProvince
                , localityOrCity, companyName
                , division, domainName, email
                , System.DateTime.UtcNow
                , System.DateTime.UtcNow.AddYears(5)
                );

            ci.AddAlternativeNames("localhost", System.Environment.MachineName, "127.0.0.1",
                                   "sql.guru", "*.sql.guru");

            // Org.BouncyCastle.Crypto.AsymmetricCipherKeyPair kp1 = KeyGenerator.GenerateEcKeyPair(curveName, random);
            Org.BouncyCastle.Crypto.AsymmetricCipherKeyPair kp1 = KeyGenerator.GenerateRsaKeyPair(2048, random);
            // Org.BouncyCastle.Crypto.AsymmetricCipherKeyPair kp1 = KeyGenerator.GenerateDsaKeyPair(1024, random);
            // Org.BouncyCastle.Crypto.AsymmetricCipherKeyPair kp1 = KeyGenerator.GenerateDHKeyPair(1024, random);



            ci.SubjectKeyPair = KeyImportExport.GetPemKeyPair(kp1);
            // ci.IssuerKeyPair.PrivateKey = rootCert.PrivateKey;

            // caSsl = CerGenerator.GenerateSslCertificate(ci, random, caRoot);

            Org.BouncyCastle.Crypto.AsymmetricKeyParameter subjectPublicKey = null;
            // This is the private key of the root certificate
            Org.BouncyCastle.Crypto.AsymmetricKeyParameter issuerPrivateKey = null;

            caSsl = CerGenerator.GenerateSslCertificate(
                ci
                , subjectPublicKey
                , issuerPrivateKey
                , caRoot
                , random
                );


            CertificateToDerPem(caSsl);



            // Just to clarify, an X.509 certificate does not contain the private key
            // The whole point of using certificates is to send them more or less openly,
            // without sending the private key, which must be kept secret.
            // An X509Certificate2 object may have a private key associated with it (via its PrivateKey property),
            // but that's only a convenience as part of the design of this class.
            // System.Security.Cryptography.X509Certificates.X509Certificate2 = new System.Security.Cryptography.X509Certificates.X509Certificate2(caRoot.GetEncoded());
            // System.Console.WriteLine(cc.PublicKey);
            // System.Console.WriteLine(cc.PrivateKey);

            bool val = CerGenerator.ValidateSelfSignedCert(caSsl, caRoot.GetPublicKey());

            System.Console.WriteLine(val);

            PfxGenerator.CreatePfxFile(@"obelix.pfx", caSsl, kp1.Private, "");
            CerGenerator.WritePrivatePublicKey("obelix", ci.SubjectKeyPair);


            CerGenerator.WriteCerAndCrt(@"ca", caRoot);
            CerGenerator.WriteCerAndCrt(@"obelix", caSsl);
        } // End Sub SelfSignSslCertificate
コード例 #14
0
        } // End Function ReadPrivateKey

        public static void TestSignature()
        {
            System.Console.WriteLine("Attempting to load cert...");
            System.Security.Cryptography.X509Certificates.X509Certificate2 thisCert = null; // LoadCertificate();

            System.Console.WriteLine(thisCert.IssuerName.Name);
            System.Console.WriteLine("Signing the text - Mary had a nuclear bomb");

            byte[] pkcs12Bytes = thisCert.Export(System.Security.Cryptography.X509Certificates.X509ContentType.Pkcs12, "dummy");
            Org.BouncyCastle.Pkcs.Pkcs12Store pkcs12 = new Org.BouncyCastle.Pkcs.Pkcs12StoreBuilder().Build();

            pkcs12.Load(new System.IO.MemoryStream(pkcs12Bytes, false), "dummy".ToCharArray());

            Org.BouncyCastle.Crypto.Parameters.ECPrivateKeyParameters privKey = null;
            foreach (string alias in pkcs12.Aliases)
            {
                if (pkcs12.IsKeyEntry(alias))
                {
                    privKey = (Org.BouncyCastle.Crypto.Parameters.ECPrivateKeyParameters)pkcs12.GetKey(alias).Key;
                    break;
                } // End if (pkcs12.IsKeyEntry(alias))
            }     // Next alias

            string signature = SignData("Mary had a nuclear bomb", privKey);

            System.Console.WriteLine("Signature: " + signature);

            System.Console.WriteLine("Verifying Signature");

            Org.BouncyCastle.X509.X509Certificate bcCert = Org.BouncyCastle.Security.DotNetUtilities.FromX509Certificate(thisCert);
            if (VerifySignature((Org.BouncyCastle.Crypto.Parameters.ECPublicKeyParameters)bcCert.GetPublicKey(), signature, "Mary had a nuclear bomb."))
            {
                System.Console.WriteLine("Valid Signature!");
            }
            else
            {
                System.Console.WriteLine("Signature NOT valid!");
            }
        } // End Sub TestSignature
コード例 #15
0
        } // End Function ValidateSelfSignedCert

        // https://stackoverflow.com/questions/51703109/nginx-the-ssl-directive-is-deprecated-use-the-listen-ssl
        public static void Test2()
        {
            Org.BouncyCastle.X509.X509Certificate caRoot = null;
            Org.BouncyCastle.X509.X509Certificate caSsl  = null;
            CertificateInfo caCertInfo = null;
            string          curveName  = "curve25519";

            curveName = "secp256k1";


            {
                string countryIso2Characters = "EA";
                string stateOrProvince       = "Europe";
                string localityOrCity        = "NeutralZone";
                string companyName           = "Skynet Earth Inc.";
                string division   = "Skynet mbH";
                string domainName = "Skynet";
                string email      = "*****@*****.**";


                caCertInfo = new CertificateInfo(
                    countryIso2Characters, stateOrProvince
                    , localityOrCity, companyName
                    , division, domainName, email
                    , System.DateTime.UtcNow
                    , System.DateTime.UtcNow.AddYears(5)
                    );

                // Org.BouncyCastle.Crypto.AsymmetricCipherKeyPair kp1 = KeyGenerator.GenerateEcKeyPair(curveName, s_secureRandom.Value);
                Org.BouncyCastle.Crypto.AsymmetricCipherKeyPair kp1 = KeyGenerator.GenerateRsaKeyPair(2048, s_secureRandom.Value);
                // Org.BouncyCastle.Crypto.AsymmetricCipherKeyPair kp1 = KeyGenerator.GenerateDsaKeyPair(1024, s_secureRandom.Value);
                // Org.BouncyCastle.Crypto.AsymmetricCipherKeyPair kp1 = KeyGenerator.GenerateDHKeyPair(1024, s_secureRandom.Value);

                // kp1 = KeyGenerator.GenerateGhostKeyPair(4096, s_secureRandom.Value);

                caCertInfo.SubjectKeyPair = KeyImportExport.GetPemKeyPair(kp1);
                caCertInfo.IssuerKeyPair  = KeyImportExport.GetPemKeyPair(kp1);

                caRoot = GenerateRootCertificate(caCertInfo, s_secureRandom.Value);

                PfxGenerator.CreatePfxFile(@"ca.pfx", caRoot, kp1.Private, null);
                WritePrivatePublicKey("issuer", caCertInfo.IssuerKeyPair);
            }


            {
                string countryIso2Characters = "GA";
                string stateOrProvince       = "Aremorica";
                string localityOrCity        = "Erquy, Bretagne";
                string companyName           = "Coopérative Ménhir Obelix Gmbh & Co. KGaA";
                string division   = "NT (Neanderthal Technology)";
                string domainName = "localhost";
                domainName = "*.sql.guru";
                domainName = "localhost";
                string email = "webmaster@localhost";


                CertificateInfo ci = new CertificateInfo(
                    countryIso2Characters, stateOrProvince
                    , localityOrCity, companyName
                    , division, domainName, email
                    , System.DateTime.UtcNow
                    , System.DateTime.UtcNow.AddYears(5)
                    );

                ci.AddAlternativeNames("localhost", System.Environment.MachineName, "127.0.0.1",
                                       "sql.guru", "*.sql.guru");

                // Org.BouncyCastle.Crypto.AsymmetricCipherKeyPair kp1 = KeyGenerator.GenerateEcKeyPair(curveName, s_secureRandom.Value);
                Org.BouncyCastle.Crypto.AsymmetricCipherKeyPair kp1 = KeyGenerator.GenerateRsaKeyPair(2048, s_secureRandom.Value);
                // Org.BouncyCastle.Crypto.AsymmetricCipherKeyPair kp1 = KeyGenerator.GenerateDsaKeyPair(1024, s_secureRandom.Value);
                // Org.BouncyCastle.Crypto.AsymmetricCipherKeyPair kp1 = KeyGenerator.GenerateDHKeyPair(1024, s_secureRandom.Value);



                ci.SubjectKeyPair = KeyImportExport.GetPemKeyPair(kp1);
                ci.IssuerKeyPair  = caCertInfo.SubjectKeyPair;

                caSsl = GenerateSslCertificate(ci, s_secureRandom.Value, caRoot);

                // Just to clarify, an X.509 certificate does not contain the private key
                // The whole point of using certificates is to send them more or less openly,
                // without sending the private key, which must be kept secret.
                // An X509Certificate2 object may have a private key associated with it (via its PrivateKey property),
                // but that's only a convenience as part of the design of this class.
                // var cc = new System.Security.Cryptography.X509Certificates.X509Certificate2(caRoot.GetEncoded());
                // System.Console.WriteLine(cc.PublicKey);
                // System.Console.WriteLine(cc.PrivateKey);

                bool val = ValidateSelfSignedCert(caSsl, caRoot.GetPublicKey());
                System.Console.WriteLine(val);

                PfxGenerator.CreatePfxFile(@"obelix.pfx", caSsl, kp1.Private, "");
                WritePrivatePublicKey("obelix", ci.SubjectKeyPair);
            }

            WriteCerAndCrt(@"ca", caRoot);
            WriteCerAndCrt(@"obelix", caSsl);
        } // End Sub Test2
コード例 #16
0
 internal void ValidateResponse(BasicOcspResp or, X509Certificate issuerCert)
 {
     ValidateResponseSignature(or, issuerCert.GetPublicKey());
     ValidateSignerAuthorization(issuerCert, or.GetCerts()[0]);
 }