Exemplo n.º 1
0
        private Pkcs10CertificationRequest GeneratePkcs10()
        {
            var x509 = new X509Name(attributes.Select(p => p.Item1).ToArray(), attributes.Select(p => p.Item2).ToArray());

            if (this.SubjectAlternativeNames.Count == 0)
            {
                this.SubjectAlternativeNames.Add(commonName);
            }

            var altNames = this.SubjectAlternativeNames
                           .Distinct()
                           .Select(n => new GeneralName(GeneralName.DnsName, n))
                           .ToArray();

            var extensions = new X509Extensions(new Dictionary <DerObjectIdentifier, X509Extension>
            {
                { X509Extensions.BasicConstraints, new X509Extension(false, new DerOctetString(new BasicConstraints(false))) },
                { X509Extensions.KeyUsage, new X509Extension(false, new DerOctetString(new KeyUsage(KeyUsage.DigitalSignature | KeyUsage.KeyEncipherment | KeyUsage.NonRepudiation))) },
                { X509Extensions.SubjectAlternativeName, new X509Extension(false, new DerOctetString(new GeneralNames(altNames))) }
            });

            var attribute = new AttributePkcs(PkcsObjectIdentifiers.Pkcs9AtExtensionRequest, new DerSet(extensions));

            var signatureFactory = new Asn1SignatureFactory(this.Algorithm.ToPkcsObjectId(), this.KeyPair.Private);
            var csr = new Pkcs10CertificationRequest(signatureFactory, x509, KeyPair.Public, new DerSet(attribute), KeyPair.Private);

            var valid = csr.Verify();

            if (!valid)
            {
                throw new Exception();
            }

            return(csr);
        }
Exemplo n.º 2
0
        private void createPssTest(
            string algorithm)
        {
//			RSAPublicKeySpec pubKeySpec = new RSAPublicKeySpec(
            RsaKeyParameters pubKey = new RsaKeyParameters(false,
                                                           new BigInteger("a56e4a0e701017589a5187dc7ea841d156f2ec0e36ad52a44dfeb1e61f7ad991d8c51056ffedb162b4c0f283a12a88a394dff526ab7291cbb307ceabfce0b1dfd5cd9508096d5b2b8b6df5d671ef6377c0921cb23c270a70e2598e6ff89d19f105acc2d3f0cb35f29280e1386b6f64c4ef22e1e1f20d0ce8cffb2249bd9a2137", 16),
                                                           new BigInteger("010001", 16));

//			RSAPrivateCrtKeySpec privKeySpec = new RSAPrivateCrtKeySpec(
            RsaPrivateCrtKeyParameters privKey = new RsaPrivateCrtKeyParameters(
                new BigInteger("a56e4a0e701017589a5187dc7ea841d156f2ec0e36ad52a44dfeb1e61f7ad991d8c51056ffedb162b4c0f283a12a88a394dff526ab7291cbb307ceabfce0b1dfd5cd9508096d5b2b8b6df5d671ef6377c0921cb23c270a70e2598e6ff89d19f105acc2d3f0cb35f29280e1386b6f64c4ef22e1e1f20d0ce8cffb2249bd9a2137", 16),
                new BigInteger("010001", 16),
                new BigInteger("33a5042a90b27d4f5451ca9bbbd0b44771a101af884340aef9885f2a4bbe92e894a724ac3c568c8f97853ad07c0266c8c6a3ca0929f1e8f11231884429fc4d9ae55fee896a10ce707c3ed7e734e44727a39574501a532683109c2abacaba283c31b4bd2f53c3ee37e352cee34f9e503bd80c0622ad79c6dcee883547c6a3b325", 16),
                new BigInteger("e7e8942720a877517273a356053ea2a1bc0c94aa72d55c6e86296b2dfc967948c0a72cbccca7eacb35706e09a1df55a1535bd9b3cc34160b3b6dcd3eda8e6443", 16),
                new BigInteger("b69dca1cf7d4d7ec81e75b90fcca874abcde123fd2700180aa90479b6e48de8d67ed24f9f19d85ba275874f542cd20dc723e6963364a1f9425452b269a6799fd", 16),
                new BigInteger("28fa13938655be1f8a159cbaca5a72ea190c30089e19cd274a556f36c4f6e19f554b34c077790427bbdd8dd3ede2448328f385d81b30e8e43b2fffa027861979", 16),
                new BigInteger("1a8b38f398fa712049898d7fb79ee0a77668791299cdfa09efc0e507acb21ed74301ef5bfd48be455eaeb6e1678255827580a8e4e8e14151d1510a82a3f2e729", 16),
                new BigInteger("27156aba4126d24a81f3a528cbfb27f56886f840a9f6e86e17a44b94fe9319584b8e22fdde1e5a2e3bd8aa5ba8d8584194eb2190acf832b847f13a3d24a79f4d", 16));

//			KeyFactory  fact = KeyFactory.getInstance("RSA", "BC");
//
//			PrivateKey privKey = fact.generatePrivate(privKeySpec);
//			PublicKey pubKey = fact.generatePublic(pubKeySpec);

            Pkcs10CertificationRequest req = new Pkcs10CertificationRequest(
                algorithm, new X509Name("CN=XXX"), pubKey, null, privKey);

            if (!req.Verify())
            {
                Fail("Failed verify check PSS.");
            }

            req = new Pkcs10CertificationRequest(req.GetEncoded());
            if (!req.Verify())
            {
                Fail("Failed verify check PSS encoded.");
            }

            if (!req.SignatureAlgorithm.ObjectID.Equals(PkcsObjectIdentifiers.IdRsassaPss))
            {
                Fail("PSS oid incorrect.");
            }

            if (req.SignatureAlgorithm.Parameters == null)
            {
                Fail("PSS parameters incorrect.");
            }

            ISigner sig = SignerUtilities.GetSigner(algorithm);

            sig.Init(false, pubKey);

            byte[] encoded = req.GetCertificationRequestInfo().GetEncoded();
            sig.BlockUpdate(encoded, 0, encoded.Length);

            if (!sig.VerifySignature(req.Signature.GetBytes()))
            {
                Fail("signature not mapped correctly.");
            }
        }
Exemplo n.º 3
0
        /// <summary>
        /// Creates a KeyVault signed certficate from signing request.
        /// </summary>
        internal async Task <X509Certificate2> SigningRequestAsync(byte[] certificateRequest, string issuerCertificateName)
        {
            var pkcs10CertificationRequest = new Pkcs10CertificationRequest(certificateRequest);

            if (!pkcs10CertificationRequest.Verify())
            {
                throw new ArgumentException("CSR signature invalid.");
            }

            var info      = pkcs10CertificationRequest.GetCertificationRequestInfo();
            var notBefore = DateTime.UtcNow.AddDays(-1);

            var certBundle = await _keyVaultServiceClient.GetCertificateAsync(issuerCertificateName).ConfigureAwait(false);

            var signingCert = new X509Certificate2(certBundle.Cer);
            var publicKey   = KeyVaultCertFactory.GetRSAPublicKey(info.SubjectPublicKeyInfo);

            return(await KeyVaultCertFactory.CreateSignedCertificate(
                       info.Subject.ToString(),
                       2048,
                       notBefore,
                       notBefore.AddMonths(12),
                       256,
                       signingCert,
                       publicKey,
                       new KeyVaultSignatureGenerator(_keyVaultServiceClient, certBundle.KeyIdentifier.Identifier, signingCert)
                       ));
        }
Exemplo n.º 4
0
        /// <summary>
        /// Does basic validity checks for a CSR (is it properly self-signed)
        /// </summary>
        /// <param name="csrPEM"></param>
        /// <returns>CSR is properly signed</returns>
        internal static bool CheckCSR(string csrPEM)
        {
            Pkcs10CertificationRequest csr = null;

            try
            {
                using (var reader = File.OpenText(csrPEM))
                {
                    csr = (Pkcs10CertificationRequest) new Org.BouncyCastle.OpenSsl.PemReader(reader).ReadObject();
                }
            }
            catch (Exception e)
            {
                Program.Print($"Failed to parse the csr: {csrPEM}", NotifyType.Error);
                Program.Print($"Error is : {e.ToString()}", NotifyType.Error);
                return(false);
            }

            bool sigOk = csr.Verify();

            if (!sigOk)
            {
                Error("CSR signature did not verify");
                return(false);
            }
            return(true);
        }
        /// <summary>
        /// Verify signature using self verification of Pkcs10CertificationRequest
        /// </summary>
        /// <param name="csrSigned"></param>
        private void Verify(byte[] csrSigned)
        {
            Assert.IsNotNull(csrSigned);

            var csr = new Pkcs10CertificationRequest(csrSigned);

            bool isValid = csr.Verify();

            Assert.IsTrue(isValid, "Verification failed");
        }
Exemplo n.º 6
0
        private void createECGostRequest()
        {
            string algorithm = "GOST3411withECGOST3410";
            IAsymmetricCipherKeyPairGenerator ecGostKpg = GeneratorUtilities.GetKeyPairGenerator("ECGOST3410");

            ecGostKpg.Init(
                new ECKeyGenerationParameters(
                    CryptoProObjectIdentifiers.GostR3410x2001CryptoProA,
                    new SecureRandom()));

            //
            // set up the keys
            //
            AsymmetricCipherKeyPair pair    = ecGostKpg.GenerateKeyPair();
            AsymmetricKeyParameter  privKey = pair.Private;
            AsymmetricKeyParameter  pubKey  = pair.Public;

            Pkcs10CertificationRequest req = new Pkcs10CertificationRequest(
                algorithm, new X509Name("CN=XXX"), pubKey, null, privKey);

            if (!req.Verify())
            {
                Fail("Failed Verify check EC.");
            }

            req = new Pkcs10CertificationRequest(req.GetEncoded());
            if (!req.Verify())
            {
                Fail("Failed Verify check EC encoded.");
            }

            if (!req.SignatureAlgorithm.ObjectID.Equals(CryptoProObjectIdentifiers.GostR3411x94WithGostR3410x2001))
            {
                Fail("ECGOST oid incorrect.");
            }

            if (req.SignatureAlgorithm.Parameters != null)
            {
                Fail("ECGOST parameters incorrect.");
            }

            ISigner sig = SignerUtilities.GetSigner(algorithm);

            sig.Init(false, pubKey);

            byte[] b = req.GetCertificationRequestInfo().GetEncoded();
            sig.BlockUpdate(b, 0, b.Length);

            if (!sig.VerifySignature(req.Signature.GetBytes()))
            {
                Fail("signature not mapped correctly.");
            }
        }
Exemplo n.º 7
0
        private void generationTest(
            int keySize,
            string keyName,
            string sigName)
        {
            IAsymmetricCipherKeyPairGenerator kpg = GeneratorUtilities.GetKeyPairGenerator(keyName);

//			kpg.initialize(keySize);
            kpg.Init(new KeyGenerationParameters(new SecureRandom(), keySize));

            AsymmetricCipherKeyPair kp = kpg.GenerateKeyPair();

            IDictionary attrs = new Hashtable();

            attrs.Add(X509Name.C, "AU");
            attrs.Add(X509Name.O, "The Legion of the Bouncy Castle");
            attrs.Add(X509Name.L, "Melbourne");
            attrs.Add(X509Name.ST, "Victoria");
            attrs.Add(X509Name.EmailAddress, "*****@*****.**");

            IList order = new ArrayList();

            order.Add(X509Name.C);
            order.Add(X509Name.O);
            order.Add(X509Name.L);
            order.Add(X509Name.ST);
            order.Add(X509Name.EmailAddress);

            X509Name subject = new X509Name(order, attrs);

            Pkcs10CertificationRequest req1 = new Pkcs10CertificationRequest(
                sigName,
                subject,
                kp.Public,
                null,
                kp.Private);

            byte[] bytes = req1.GetEncoded();

            Pkcs10CertificationRequest req2 = new Pkcs10CertificationRequest(bytes);

            if (!req2.Verify())
            {
                Fail(sigName + ": Failed Verify check.");
            }

            if (!req2.GetPublicKey().Equals(req1.GetPublicKey()))
            {
                Fail(keyName + ": Failed public key check.");
            }
        }
        /// <summary>
        /// Convert buffer to request info
        /// </summary>
        /// <param name="certificateRequest"></param>
        /// <returns></returns>
        internal static Pkcs10CertificationRequest ToPkcs10CertificationRequest(
            this byte[] certificateRequest)
        {
            if (certificateRequest == null)
            {
                throw new ArgumentNullException(nameof(certificateRequest));
            }
            var pkcs10CertificationRequest = new Pkcs10CertificationRequest(
                certificateRequest);

            if (!pkcs10CertificationRequest.Verify())
            {
                throw new FormatException("CSR signature invalid.");
            }
            return(pkcs10CertificationRequest);
        }
Exemplo n.º 9
0
        private byte[] gen()
        {
            TextReader textReader = new StreamReader("certificaterequest.pkcs10");
            PemReader  pemReader  = new PemReader(textReader);

            Pkcs10CertificationRequest certificationRequest     = (Pkcs10CertificationRequest)pemReader.ReadObject();
            CertificationRequestInfo   certificationRequestInfo = certificationRequest.GetCertificationRequestInfo();
            SubjectPublicKeyInfo       publicKeyInfo            = certificationRequestInfo.SubjectPublicKeyInfo;

            RsaPublicKeyStructure publicKeyStructure = RsaPublicKeyStructure.GetInstance(publicKeyInfo.GetPublicKey());

            RsaKeyParameters publicKey = new RsaKeyParameters(false, publicKeyStructure.Modulus, publicKeyStructure.PublicExponent);

            bool certIsOK = certificationRequest.Verify(publicKey);

            // public key is OK here...

            // get the server certificate
            Org.BouncyCastle.X509.X509Certificate serverCertificate = DotNetUtilities.FromX509Certificate(System.Security.Cryptography.X509Certificates.X509Certificate.CreateFromCertFile("servermastercertificate.cer"));

            // get the server private key
            byte[] privateKeyBytes = File.ReadAllBytes("serverprivate.key");

            AsymmetricKeyParameter serverPrivateKey = PrivateKeyFactory.CreateKey(privateKeyBytes);

            // generate the client certificate
            X509V3CertificateGenerator generator = new X509V3CertificateGenerator();

            generator.SetSerialNumber(BigInteger.ProbablePrime(120, new Random()));
            generator.SetIssuerDN(serverCertificate.SubjectDN);
            generator.SetNotBefore(DateTime.Now);
            generator.SetNotAfter(DateTime.Now.AddYears(5));
            generator.SetSubjectDN(certificationRequestInfo.Subject);
            generator.SetPublicKey(publicKey);
            generator.SetSignatureAlgorithm("SHA512withRSA");
            generator.AddExtension(X509Extensions.AuthorityKeyIdentifier, false, new AuthorityKeyIdentifierStructure(serverCertificate));
            generator.AddExtension(X509Extensions.SubjectKeyIdentifier, false, new SubjectKeyIdentifierStructure(publicKey));

            var newClientCert = generator.Generate(serverPrivateKey);

            newClientCert.Verify(publicKey); // <-- this blows up

            return(DotNetUtilities.ToX509Certificate(newClientCert).Export(System.Security.Cryptography.X509Certificates.X509ContentType.Pkcs12, "user password"));
        }
Exemplo n.º 10
0
        public override void PerformTest()
        {
            IAsymmetricCipherKeyPairGenerator pGen     = GeneratorUtilities.GetKeyPairGenerator("RSA");
            RsaKeyGenerationParameters        genParam = new RsaKeyGenerationParameters(
                BigInteger.ValueOf(0x10001), new SecureRandom(), 512, 25);

            pGen.Init(genParam);

            AsymmetricCipherKeyPair pair = pGen.GenerateKeyPair();

            IDictionary attrs = new Hashtable();

            attrs.Add(X509Name.C, "AU");
            attrs.Add(X509Name.O, "The Legion of the Bouncy Castle");
            attrs.Add(X509Name.L, "Melbourne");
            attrs.Add(X509Name.ST, "Victoria");
            attrs.Add(X509Name.EmailAddress, "*****@*****.**");

            X509Name subject = new X509Name(new ArrayList(attrs.Keys), attrs);

            Pkcs10CertificationRequest req1 = new Pkcs10CertificationRequest(
                "SHA1withRSA",
                subject,
                pair.Public,
                null,
                pair.Private);

            byte[] bytes = req1.GetEncoded();

            Pkcs10CertificationRequest req2 = new Pkcs10CertificationRequest(bytes);

            if (!req2.Verify())
            {
                Fail("Failed verify check.");
            }

            if (!req2.GetPublicKey().Equals(req1.GetPublicKey()))
            {
                Fail("Failed public key check.");
            }
        }
        public override void PerformTest()
        {
            IAsymmetricCipherKeyPairGenerator pGen = GeneratorUtilities.GetKeyPairGenerator("RSA");
            RsaKeyGenerationParameters genParam = new RsaKeyGenerationParameters(
                BigInteger.ValueOf(0x10001), new SecureRandom(), 512, 25);

            pGen.Init(genParam);

            IAsymmetricCipherKeyPair pair = pGen.GenerateKeyPair();

            IDictionary attrs = new Hashtable();

            attrs.Add(X509Name.C, "AU");
            attrs.Add(X509Name.O, "The Legion of the Bouncy Castle");
            attrs.Add(X509Name.L, "Melbourne");
            attrs.Add(X509Name.ST, "Victoria");
            attrs.Add(X509Name.EmailAddress, "*****@*****.**");

            X509Name subject = new X509Name(new ArrayList(attrs.Keys), attrs);

            Pkcs10CertificationRequest req1 = new Pkcs10CertificationRequest(
                "SHA1withRSA",
                subject,
                pair.Public,
                null,
                pair.Private);

            byte[] bytes = req1.GetEncoded();

            Pkcs10CertificationRequest req2 = new Pkcs10CertificationRequest(bytes);

            if (!req2.Verify())
            {
                Fail("Failed verify check.");
            }

            if (!req2.GetPublicKey().Equals(req1.GetPublicKey()))
            {
                Fail("Failed public key check.");
            }
        }
Exemplo n.º 12
0
        public MSX509.X509Certificate2 SignRequest(string csrFile, Usage usage, int validity, MSX509.StoreName storeName)
        {
            Pkcs10CertificationRequest request = ReadPkcs10(csrFile);
            var info = request.GetCertificationRequestInfo();
            SubjectPublicKeyInfo publicKeyInfo = info.SubjectPublicKeyInfo;

            RsaPublicKeyStructure publicKeyStructure = RsaPublicKeyStructure.GetInstance(publicKeyInfo.GetPublicKey());
            RsaKeyParameters      publicKey          = new RsaKeyParameters(false, publicKeyStructure.Modulus, publicKeyStructure.PublicExponent);

            if (!request.Verify(publicKey))
            {
                throw new ApplicationException("The CSR is not valid: verification failed");
            }

            MSX509.X509Certificate2 root = GetRootCertificate();
            if (root == null)
            {
                throw new ApplicationException("Root certificate not found");
            }

            return(InternalGenerateCertificate(info.Subject, usage, validity, storeName, publicKey, null, DotNetUtilities.GetKeyPair(root.PrivateKey).Private));
        }
        /// <summary>
        /// Sign a certificate
        /// </summary>
        /// <param name="signingCert">Issuer X509Certificate2</param>
        /// <param name="csrData">CSR Data</param>
        /// <returns>X509Certificate2 Certificate</returns>
        private X509Certificate2 SignCertificate(X509Certificate2 signingCert, byte[] csrData)
        {
            //Get CSR and retrieve public key
            Pkcs10CertificationRequest certRequest       = new Pkcs10CertificationRequest(csrData);
            CertificationRequestInfo   certInfo          = certRequest.GetCertificationRequestInfo();
            SubjectPublicKeyInfo       certPublicKeyInfo = certInfo.SubjectPublicKeyInfo;
            AsymmetricKeyParameter     certPublicKey     = PublicKeyFactory.CreateKey(certPublicKeyInfo);

            if (!certRequest.Verify(certPublicKey))
            {
                throw new ApplicationException("The CSR is not valid: verification failed");
            }

            //Get private key of intermediate issuer, to be used to sign the certificate
            var issuer = DotNetUtilities.FromX509Certificate(signingCert);
            AsymmetricCipherKeyPair keyPrivate = DotNetUtilities.GetRsaKeyPair(signingCert.GetRSAPrivateKey());
            //Get the serial number of the issuer
            var issuerSerialNumber = new BigInteger(signingCert.GetSerialNumber());

            //Generate a signed certificate
            return(GenerateCertificate(certInfo.Subject, certPublicKey, certPublicKeyInfo,
                                       issuer.SubjectDN, issuer.GetPublicKey(), keyPrivate.Private, issuerSerialNumber));
        }
Exemplo n.º 14
0
        private void readRequest()
        {
            // Perform POP on the request
            if (!request.Verify())
            {
                throw new SignatureException("Invalid signature on PKCS#10 request");
            }

            // Contents
            info = request.GetCertificationRequestInfo();

            // Extensions in OSCA format
            foreach (DerObjectIdentifier oid in Extensions.ExtensionOids)
            {
                oscaExtensions.Add(ProfileExtensionFactory.GetExtension(oid, Extensions.GetExtension(oid)));
            }

            // Attributes
            foreach (object entry in Attributes)
            {
                AttributePkcs attrib = AttributePkcs.GetInstance(entry);
                attributes.Add(attrib.AttrType, attrib.AttrValues);
            }
        }
Exemplo n.º 15
0
        /// <summary>
        /// Generate certificate request and private key file
        /// </summary>
        /// <param name="random"></param>
        /// <param name="subjectKeyPair"></param>
        /// <param name="subjectSerialNumber"></param>
        /// <param name="commonName"></param>
        /// <param name="subjectAlternativeNames"></param>
        /// <param name="issuerKeyPair"></param>
        /// <param name="issuerSerialNumber"></param>
        /// <param name="isCertificateAuthority"></param>
        /// <param name="usages"></param>
        /// <param name="signatureAlgorithm"></param>
        /// <param name="countryCode"></param>
        /// <param name="stateOrProvinceName"></param>
        /// <param name="localityName"></param>
        /// <param name="organization"></param>
        /// <param name="arrccbKeyUsage"></param>
        /// <param name="arrExtendedKeyUsage"></param>
        /// <param name="outputPrivateKeyName"></param>
        /// <param name="outputCertReqFile"></param>
        private async void GenerateCertificate(SecureRandom random,
                                               AsymmetricCipherKeyPair subjectKeyPair,
                                               BigInteger subjectSerialNumber,
                                               string commonName,
                                               string[] subjectAlternativeNames,
                                               AsymmetricCipherKeyPair issuerKeyPair,
                                               BigInteger issuerSerialNumber,
                                               bool isCertificateAuthority,
                                               KeyPurposeID[] usages,
                                               string signatureAlgorithm,
                                               string countryCode,
                                               string stateOrProvinceName,
                                               string localityName,
                                               string organization,
                                               List <int> arrccbKeyUsage,
                                               List <string> arrExtendedKeyUsage,
                                               string outputPrivateKeyName,
                                               string outputCertReqFile)
        {
            #region Private Key
            IDictionary attrs = new Hashtable();
            attrs[X509Name.CN] = commonName;
            attrs[X509Name.C]  = countryCode;
            attrs[X509Name.ST] = stateOrProvinceName;
            attrs[X509Name.L]  = localityName;
            attrs[X509Name.O]  = organization;

            IList ord = new ArrayList();
            ord.Add(X509Name.CN);
            ord.Add(X509Name.C);
            ord.Add(X509Name.ST);
            ord.Add(X509Name.L);
            ord.Add(X509Name.O);

            X509Name issuerDN = new X509Name(ord, attrs);

            try
            {
                using (TextWriter tw = new StreamWriter(outputPrivateKeyName))
                {
                    PemWriter pw = new PemWriter(tw);
                    pw.WriteObject(subjectKeyPair.Private);
                    tw.Flush();
                }

                tbOutputMessageBox.Text += "File with private key: " + outputPrivateKeyName + " sucessfully generated." + "\n";
            }
            catch (Exception ex)
            {
                Brush bckForeground = tbOutputMessageBox.Foreground;
                tbOutputMessageBox.Foreground = new SolidColorBrush(Colors.Red);
                tbOutputMessageBox.Text      += "ERROR creating certificate private key file (.key)" + "\n" + "Error: " + ex.Source + " " + ex.Message;
                tbOutputMessageBox.Foreground = bckForeground;

                var metroWindow = (Application.Current.MainWindow as MetroWindow);
                await metroWindow.ShowMessageAsync("Info Warning",
                                                   "ERROR creating certificate private key file (.key)" + "\n" +
                                                   "Error: " + ex.Source + " " + ex.Message,
                                                   MessageDialogStyle.Affirmative);

                return;
            }
            #endregion Private Key

            #region Public Key - old
            //if (outputPublicKeyName != null)
            //{
            //    //SubjectPublicKeyInfo publicKeyInfo = SubjectPublicKeyInfoFactory.CreateSubjectPublicKeyInfo(subjectKeyPair.Public);
            //    //byte[] serializedPublicBytes = publicKeyInfo.ToAsn1Object().GetDerEncoded();
            //    //string serializedPublic = Convert.ToBase64String(serializedPublicBytes);

            //    ////StringBuilder publicKeyStrBuilder = new StringBuilder();
            //    ////PemWriter publicKeyPemWriter = new PemWriter(new StringWriter(publicKeyStrBuilder));
            //    ////publicKeyPemWriter.WriteObject(subjectKeyPair.Public);
            //    ////publicKeyPemWriter.Writer.Flush();

            //    ////string publicKey = publicKeyStrBuilder.ToString();
            //    try
            //    {
            //        var store = new Pkcs12Store();
            //        string friendlyName = certificate.SubjectDN.ToString();
            //        var certificateEntry = new X509CertificateEntry(certificate);
            //        store.SetCertificateEntry(friendlyName, certificateEntry);
            //        store.SetKeyEntry(friendlyName, new AsymmetricKeyEntry(subjectKeyPair.Private), new[] { certificateEntry });

            //        var stream = new MemoryStream();
            //        store.Save(stream, "password".ToCharArray(), random);

            //        //Verify that the certificate is valid.
            //        var convertedCertificate = new X509Certificate2(stream.ToArray(), "password", X509KeyStorageFlags.PersistKeySet | X509KeyStorageFlags.Exportable);

            //        //Write the file.
            //        File.WriteAllBytes(outputPublicKeyName, stream.ToArray());

            //        File.WriteAllBytes(System.IO.Path.ChangeExtension(outputPublicKeyName, ".cer"), certificate.GetEncoded());

            //        //using (TextWriter tw = new StreamWriter(outputPublicKeyName))
            //        //{
            //        //    PemWriter pw = new PemWriter(tw);
            //        //    pw.WriteObject(subjectKeyPair.Public);
            //        //    tw.Flush();
            //        //}

            //        tbOutputMessageBox.Text += "File with private key: " + outputPublicKeyName + " sucessfully generated." + "\n";
            //    }
            //    catch (Exception ex)
            //    {
            //        var metroWindow = (Application.Current.MainWindow as MetroWindow);
            //        await metroWindow.ShowMessageAsync("Info Warning",
            //             "ERROR creating certificate private key file (.key)" + "\n" +
            //             "Error: " + ex.Source + " " + ex.Message,
            //             MessageDialogStyle.Affirmative);
            //        return;
            //    }
            //}
            #endregion Public Key

            #region CSR - Certificate Request file (.csr)
            // BasicConstraints
            var extensions = new Dictionary <DerObjectIdentifier, Org.BouncyCastle.Asn1.X509.X509Extension>()
            {
                { X509Extensions.BasicConstraints,
                  new Org.BouncyCastle.Asn1.X509.X509Extension(true, new DerOctetString(new BasicConstraints(false))) }
            };
            DerOctetString tmp = new DerOctetString(new BasicConstraints(false));

            //KeyUsage
            if (arrccbKeyUsage.Count > 0)
            {
                int usage = 0;
                for (int i = 0; i < arrccbKeyUsage.Count; i++)
                {
                    usage = usage | arrccbKeyUsage[i];
                }
                KeyUsage keyUsage = new KeyUsage(usage);
                extensions.Add(X509Extensions.KeyUsage,
                               new Org.BouncyCastle.Asn1.X509.X509Extension(true, new DerOctetString(keyUsage)));
            }

            //ExtendedKeyUsage
            if (arrExtendedKeyUsage.Count > 0)
            {
                KeyPurposeID[] extendedKeyUsageArr = new KeyPurposeID[arrExtendedKeyUsage.Count];
                for (int i = 0; i < arrExtendedKeyUsage.Count; i++)
                {
                    if (KeyPurposeID.AnyExtendedKeyUsage.ToString() == arrExtendedKeyUsage[i])
                    {
                        extendedKeyUsageArr[i] = KeyPurposeID.AnyExtendedKeyUsage;
                    }
                    else if (KeyPurposeID.IdKPServerAuth.ToString() == arrExtendedKeyUsage[i])
                    {
                        extendedKeyUsageArr[i] = KeyPurposeID.IdKPServerAuth;
                    }
                    else if (KeyPurposeID.IdKPClientAuth.ToString() == arrExtendedKeyUsage[i])
                    {
                        extendedKeyUsageArr[i] = KeyPurposeID.IdKPClientAuth;
                    }
                    else if (KeyPurposeID.IdKPCodeSigning.ToString() == arrExtendedKeyUsage[i])
                    {
                        extendedKeyUsageArr[i] = KeyPurposeID.IdKPCodeSigning;
                    }
                    else if (KeyPurposeID.IdKPEmailProtection.ToString() == arrExtendedKeyUsage[i])
                    {
                        extendedKeyUsageArr[i] = KeyPurposeID.IdKPEmailProtection;
                    }
                    else if (KeyPurposeID.IdKPIpsecEndSystem.ToString() == arrExtendedKeyUsage[i])
                    {
                        extendedKeyUsageArr[i] = KeyPurposeID.IdKPIpsecEndSystem;
                    }
                    else if (KeyPurposeID.IdKPIpsecTunnel.ToString() == arrExtendedKeyUsage[i])
                    {
                        extendedKeyUsageArr[i] = KeyPurposeID.IdKPIpsecTunnel;
                    }
                    else if (KeyPurposeID.IdKPIpsecUser.ToString() == arrExtendedKeyUsage[i])
                    {
                        extendedKeyUsageArr[i] = KeyPurposeID.IdKPIpsecUser;
                    }
                    else if (KeyPurposeID.IdKPTimeStamping.ToString() == arrExtendedKeyUsage[i])
                    {
                        extendedKeyUsageArr[i] = KeyPurposeID.IdKPTimeStamping;
                    }
                    else if (KeyPurposeID.IdKPOcspSigning.ToString() == arrExtendedKeyUsage[i])
                    {
                        extendedKeyUsageArr[i] = KeyPurposeID.IdKPOcspSigning;
                    }
                }

                ExtendedKeyUsage extendedKeyUsage = new ExtendedKeyUsage(extendedKeyUsageArr);
                Asn1OctetString  asn1ost          = new DerOctetString(extendedKeyUsage);

                extensions.Add(X509Extensions.ExtendedKeyUsage,
                               new Org.BouncyCastle.Asn1.X509.X509Extension(false, new DerOctetString(extendedKeyUsage)));
            }

            //SubjectAlternativeName
            if (subjectAlternativeNames.Length > 0)
            {
                GeneralNames names = new GeneralNames(
                    subjectAlternativeNames.Select(n => new GeneralName(GeneralName.DnsName, n)).ToArray()
                    );

                extensions.Add(X509Extensions.SubjectAlternativeName,
                               new Org.BouncyCastle.Asn1.X509.X509Extension(false, new DerOctetString(names)));
            }

            //SubjectKeyIdentifier
            extensions.Add(X509Extensions.SubjectKeyIdentifier,
                           new Org.BouncyCastle.Asn1.X509.X509Extension(false,
                                                                        new DerOctetString(new SubjectKeyIdentifierStructure(subjectKeyPair.Public))));

            ISignatureFactory sigFactory = new Asn1SignatureFactory(signatureAlgorithm, subjectKeyPair.Private);

            Pkcs10CertificationRequest csr = new Pkcs10CertificationRequest(
                sigFactory,
                issuerDN,
                subjectKeyPair.Public,
                new DerSet(new AttributePkcs(PkcsObjectIdentifiers.Pkcs9AtExtensionRequest, new DerSet(new X509Extensions(extensions)))),
                subjectKeyPair.Private);

            bool isOK = csr.Verify();
            if (isOK)
            {
                tbOutputMessageBox.Text += "File with certificate request : " + outputCertReqFile + " sucessfully generated." + "\n";

                requestFileNamePath           = outputCertReqFile;
                requestFileNamePrivateKeyPath = outputPrivateKeyName;
                btnContinue.IsEnabled         = true;
            }
            else
            {
                Brush bckForeground = tbOutputMessageBox.Foreground;
                tbOutputMessageBox.Foreground = new SolidColorBrush(Colors.Red);
                tbOutputMessageBox.Text      += "File with certificate request : " + outputCertReqFile + " DOES NOT generated sucessfully!!!" + "\n";
                tbOutputMessageBox.Foreground = bckForeground;

                var metroWindow = (Application.Current.MainWindow as MetroWindow);
                await metroWindow.ShowMessageAsync("ERROR",
                                                   "File with certificate request : " + outputCertReqFile + " DOES NOT generated sucessfully!!!",
                                                   MessageDialogStyle.Affirmative);

                return;
            }

            try
            {
                using (TextWriter tw = new StreamWriter(outputCertReqFile))
                {
                    PemWriter pw = new PemWriter(tw);
                    pw.WriteObject(csr);
                    tw.Flush();
                }

                tbOutputMessageBox.Text += "File with certificate request : " + outputCertReqFile + " sucessfully saved." + "\n";
            }
            catch (Exception ex)
            {
                Brush bckForeground = tbOutputMessageBox.Foreground;
                tbOutputMessageBox.Foreground = new SolidColorBrush(Colors.Red);
                tbOutputMessageBox.Text      += "Error, file with certificate request : " + outputCertReqFile + " DOES NOT saved." + "\n";
                tbOutputMessageBox.Foreground = bckForeground;

                var metroWindow = (Application.Current.MainWindow as MetroWindow);
                await metroWindow.ShowMessageAsync("Info Warning",
                                                   "ERROR to save certificate reguest file (.csr)" + "\n" +
                                                   "Error: " + ex.Source + " " + ex.Message,
                                                   MessageDialogStyle.Affirmative);

                return;
            }
            #endregion CSR
        }
Exemplo n.º 16
0
        public override void PerformTest()
        {
            generationTest(512, "RSA", "SHA1withRSA");
            generationTest(512, "GOST3410", "GOST3411withGOST3410");

            //		if (Security.getProvider("SunRsaSign") != null)
            //        {
            //            generationTest(512, "RSA", "SHA1withRSA", "SunRsaSign");
            //        }

            // elliptic curve GOST A parameter set
            Pkcs10CertificationRequest req = new Pkcs10CertificationRequest(gost3410EC_A);

            if (!req.Verify())
            {
                Fail("Failed Verify check gost3410EC_A.");
            }

            // elliptic curve GOST B parameter set
            req = new Pkcs10CertificationRequest(gost3410EC_B);
            if (!req.Verify())
            {
                Fail("Failed Verify check gost3410EC_B.");
            }

            // elliptic curve GOST C parameter set
            req = new Pkcs10CertificationRequest(gost3410EC_C);
            if (!req.Verify())
            {
                Fail("Failed Verify check gost3410EC_C.");
            }

            // elliptic curve GOST ExA parameter set
            req = new Pkcs10CertificationRequest(gost3410EC_ExA);
            if (!req.Verify())
            {
                Fail("Failed Verify check gost3410EC_ExA.");
            }

            // elliptic curve GOST ExB parameter set
            req = new Pkcs10CertificationRequest(gost3410EC_ExB);
            if (!req.Verify())
            {
                Fail("Failed Verify check gost3410EC_ExA.");
            }

            // elliptic curve openSSL
            IAsymmetricCipherKeyPairGenerator g = GeneratorUtilities.GetKeyPairGenerator("ECDSA");

            ECCurve curve = new FpCurve(
                new BigInteger("883423532389192164791648750360308885314476597252960362792450860609699839"),         // q
                new BigInteger("7fffffffffffffffffffffff7fffffffffff8000000000007ffffffffffc", 16),                 // a
                new BigInteger("6b016c3bdcf18941d0d654921475ca71a9db2fb27d1d37796185c2942c0a", 16));                // b

            ECDomainParameters ecSpec = new ECDomainParameters(
                curve,
                curve.DecodePoint(Hex.Decode("020ffa963cdca8816ccc33b8642bedf905c3d358573d3f27fbbd3b3cb9aaaf")),             // G
                new BigInteger("883423532389192164791648750360308884807550341691627752275345424702807307"));                 // n

//			g.initialize(ecSpec, new SecureRandom());
            g.Init(new ECKeyGenerationParameters(ecSpec, new SecureRandom()));

            AsymmetricCipherKeyPair kp = g.GenerateKeyPair();

            req = new Pkcs10CertificationRequest(
                "ECDSAWITHSHA1", new X509Name("CN=XXX"), kp.Public, null, kp.Private);

            if (!req.Verify())
            {
                Fail("Failed Verify check EC.");
            }

            createECRequest("SHA1withECDSA", X9ObjectIdentifiers.ECDsaWithSha1);
            createECRequest("SHA224withECDSA", X9ObjectIdentifiers.ECDsaWithSha224);
            createECRequest("SHA256withECDSA", X9ObjectIdentifiers.ECDsaWithSha256);
            createECRequest("SHA384withECDSA", X9ObjectIdentifiers.ECDsaWithSha384);
            createECRequest("SHA512withECDSA", X9ObjectIdentifiers.ECDsaWithSha512);

            createECGostRequest();

            // TODO The setting of parameters for MGF algorithms is not implemented
//			createPssTest("SHA1withRSAandMGF1");
//			createPssTest("SHA224withRSAandMGF1");
//			createPssTest("SHA256withRSAandMGF1");
//			createPssTest("SHA384withRSAandMGF1");

            nullPointerTest();
        }
Exemplo n.º 17
0
        /// <summary>
        /// Read CA private key file from .key or pfx file
        /// Read data from certificate request file .csr
        /// Generate signed certificate request file .cer
        /// </summary>
        /// <param name="signedCERFile"></param>
        /// <param name="privateKeyFile"></param>
        /// <param name="v"></param>
        /// <param name="password"></param>
        private async void GenerateCerFile(string certRequestFile,
                                           string privateKeyFile,
                                           string generateSignedCertificateFile,
                                           string password, string friendlyName,
                                           DateTime startDate, DateTime endDate)
        {
            #region LoadCertificate

            // read public & private key from file
            AsymmetricKeyParameter privateKey = null;
            AsymmetricKeyParameter publicKey  = null;

            System.Security.Cryptography.X509Certificates.X509Certificate2 issuerCertificate = null;
            Org.BouncyCastle.X509.X509Certificate issuerCertificateX509 = null;

            // Ovo NE radi
            //issuerCertificate = new System.Security.Cryptography.X509Certificates.X509Certificate2(
            //        privateKeyFile,
            //        password
            //        );

            // Ovo RADI
            issuerCertificate = new System.Security.Cryptography.X509Certificates.X509Certificate2(
                privateKeyFile,
                password,
                System.Security.Cryptography.X509Certificates.X509KeyStorageFlags.Exportable
                );

            // This doesn't work for selfsign certificate
            //bool isOK = issuerCertificate.Verify();

            bool     isHasPrivateKey = issuerCertificate.HasPrivateKey;
            DateTime noAfter         = issuerCertificate.NotAfter;
            DateTime noBefore        = issuerCertificate.NotBefore;
            X509ExtensionCollection x509extensions = issuerCertificate.Extensions;

            int errorNum = 0;
            X509CertificateParser parser = new X509CertificateParser();
            Org.BouncyCastle.X509.X509Certificate bouncyCertificate = parser.ReadCertificate(issuerCertificate.RawData);
            BasicConstraints basicConstraints = null;
            bool             isCa             = false;
            Asn1OctetString  str = bouncyCertificate.GetExtensionValue(new DerObjectIdentifier("2.5.29.19"));
            if (str != null)
            {
                basicConstraints = BasicConstraints.GetInstance(
                    X509ExtensionUtilities.FromExtensionValue(str));
                if (basicConstraints != null)
                {
                    isCa = basicConstraints.IsCA();
                }
            }

            if (!isCa)
            {
                errorNum++;
                Brush bckForeground = tbOutputMessageBox.Foreground;
                tbOutputMessageBox.Foreground = new SolidColorBrush(Colors.Red);
                tbOutputMessageBox.Text      += "Loaded CA file: " + privateKeyFile + " IS NOT CA authority certificate file!" + "\n";
                tbOutputMessageBox.Foreground = bckForeground;
            }
            // This doesn't work for selfsign certificate
            //if (!isOK)
            //{
            //    errorNum++;
            //    Brush bckForeground = tbOutputMessageBox.Foreground;
            //    tbOutputMessageBox.Foreground = new SolidColorBrush(Colors.Red);
            //    tbOutputMessageBox.Text += "File with CA certificate NOT valid." + "\n";
            //    tbOutputMessageBox.Foreground = bckForeground;
            //}
            if (!isHasPrivateKey)
            {
                errorNum++;
                Brush bckForeground = tbOutputMessageBox.Foreground;
                tbOutputMessageBox.Foreground = new SolidColorBrush(Colors.Red);
                tbOutputMessageBox.Text      += "File with CA certificate DOES NOT have a private key." + "\n";
                tbOutputMessageBox.Foreground = bckForeground;
            }
            if (noBefore > startDate)
            {
                errorNum++;
                Brush bckForeground = tbOutputMessageBox.Foreground;
                tbOutputMessageBox.Foreground = new SolidColorBrush(Colors.Red);
                tbOutputMessageBox.Text      += "File with CA certificate start date: " + startDate.ToLocalTime() + " DOES NOT valid value. Certificate start date is: " + noBefore.ToLocalTime() + "\n";
                tbOutputMessageBox.Foreground = bckForeground;
            }
            if (noAfter < endDate)
            {
                errorNum++;
                Brush bckForeground = tbOutputMessageBox.Foreground;
                tbOutputMessageBox.Foreground = new SolidColorBrush(Colors.Red);
                tbOutputMessageBox.Text      += "File with CA certificate end date: " + endDate.ToLocalTime() + " DOES NOT valid value. Certificate end date is: " + noAfter.ToLocalTime() + "\n";
                tbOutputMessageBox.Foreground = bckForeground;
            }

            if (errorNum > 0)
            {
                Brush bckForeground = tbOutputMessageBox.Foreground;
                tbOutputMessageBox.Foreground = new SolidColorBrush(Colors.Red);
                tbOutputMessageBox.Text      += "File with CA certificate has error!!!" + "\n";
                tbOutputMessageBox.Foreground = bckForeground;

                return;
            }
            bool isOk = issuerCertificate.Verify();

            AsymmetricCipherKeyPair issuerKeyPairTmp = DotNetUtilities.GetKeyPair(issuerCertificate.PrivateKey);
            privateKey = issuerKeyPairTmp.Private;
            publicKey  = issuerKeyPairTmp.Public;

            issuerCertificateX509 = new Org.BouncyCastle.X509.X509CertificateParser().ReadCertificate(issuerCertificate.GetRawCertData());
            issuerCertificateX509.Verify(publicKey);

            Org.BouncyCastle.X509.X509Certificate x509 = Org.BouncyCastle.Security.DotNetUtilities.FromX509Certificate(issuerCertificate);
            x509.Verify(publicKey);
            x509.CheckValidity(startDate);

            #endregion

            // Read certificate request .csr file
            Pkcs10CertificationRequest cerRequest = null;
            try
            {
                String       input_data = File.ReadAllText(certRequestFile);
                StringReader sr         = new StringReader(input_data);
                PemReader    pr         = new PemReader(sr);
                cerRequest = (Pkcs10CertificationRequest)pr.ReadObject();

                tbOutputMessageBox.Text += "Verify file with certificate request : " + certRequestFile + "\n";
                bool requestIsOK = cerRequest.Verify();
                if (requestIsOK)
                {
                    tbOutputMessageBox.Text += "File with certificate request : " + certRequestFile + " is OK." + "\n";
                }
                else
                {
                    tbOutputMessageBox.Text += "File with certificate request : " + certRequestFile + " NOT valid." + "\n";
                    return;
                }
            }
            catch (Exception ex)
            {
                var metroWindow = (Application.Current.MainWindow as MetroWindow);
                await metroWindow.ShowMessageAsync("Info Warning",
                                                   "ERROR reading certificate request file (.csr)" + "\n" +
                                                   "Error: " + ex.Source + " " + ex.Message,
                                                   MessageDialogStyle.Affirmative);

                return;
            }

            Org.BouncyCastle.X509.X509Certificate genCert = GenerateSignedCertificate(
                cerRequest,
                x509,
                issuerKeyPairTmp,
                startDate, endDate);

            try
            {
                File.WriteAllBytes(System.IO.Path.ChangeExtension(generateSignedCertificateFile, ".cer"), genCert.GetEncoded());
                tbOutputMessageBox.Text += "Certificate file: " + generateSignedCertificateFile + " sucessfully saved." + "\n";

                signedRequestFileNamePath = generateSignedCertificateFile;
                btnContinue.IsEnabled     = true;
            }
            catch (Exception)
            {
                tbOutputMessageBox.Text += "Certificate file sucessfully generated." + "\n";
            }

            #region Public Key
            //try
            //{
            //    var store = new Pkcs12Store();
            //    string friendlyName1 = issuerCertificateX509.SubjectDN.ToString();
            //    var certificateEntry = new X509CertificateEntry(issuerCertificateX509);
            //    store.SetCertificateEntry(friendlyName1, certificateEntry);
            //    store.SetKeyEntry(friendlyName1, new AsymmetricKeyEntry(privateKey), new[] { certificateEntry });

            //    var stream = new MemoryStream();
            //    var random1 = GetSecureRandom();
            //    store.Save(stream, "password".ToCharArray(), random1);

            //    //Verify that the certificate is valid.
            //    var convertedCertificate = new X509Certificate2(stream.ToArray(), "password", X509KeyStorageFlags.PersistKeySet | X509KeyStorageFlags.Exportable);

            //    //Write the file.
            //    File.WriteAllBytes(generateSignedCertificateFile, stream.ToArray());

            //    File.WriteAllBytes(System.IO.Path.ChangeExtension(generateSignedCertificateFile, ".cer"), genCert.GetEncoded());

            //    //using (TextWriter tw = new StreamWriter(outputPublicKeyName))
            //    //{
            //    //    PemWriter pw = new PemWriter(tw);
            //    //    pw.WriteObject(subjectKeyPair.Public);
            //    //    tw.Flush();
            //    //}

            //    tbOutputMessageBox.Text += "File with private key: " + generateSignedCertificateFile + " sucessfully generated." + "\n";
            //}
            //catch (Exception ex)
            //{
            //    var metroWindow = (Application.Current.MainWindow as MetroWindow);
            //    await metroWindow.ShowMessageAsync("Info Warning",
            //         "ERROR creating certificate private key file (.key)" + "\n" +
            //         "Error: " + ex.Source + " " + ex.Message,
            //         MessageDialogStyle.Affirmative);
            //    return;
            //}

            //StringBuilder publicKeyStrBuilder = new StringBuilder();
            //PemWriter publicKeyPemWriter = new PemWriter(new StringWriter(publicKeyStrBuilder));
            //publicKeyPemWriter.WriteObject(genCert.GetPublicKey());
            //publicKeyPemWriter.Writer.Flush();

            //string publicKey = publicKeyStrBuilder.ToString();
            //try
            //{
            //    using (TextWriter tw = new StreamWriter(generateSignedCertificateFile))
            //    {
            //        PemWriter pw = new PemWriter(tw);
            //        pw.WriteObject(genCert.GetPublicKey());
            //        tw.Flush();
            //    }

            //    tbOutputMessageBox.Text += "File with private key: " + generateSignedCertificateFile + " sucessfully generated." + "\n";
            //}
            //catch (Exception ex)
            //{
            //    var metroWindow = (Application.Current.MainWindow as MetroWindow);
            //    await metroWindow.ShowMessageAsync("Info Warning",
            //         "ERROR creating certificate private key file (.key)" + "\n" +
            //         "Error: " + ex.Source + " " + ex.Message,
            //         MessageDialogStyle.Affirmative);
            //    return;
            //}
            #endregion Public Key
        }
Exemplo n.º 18
0
        public static async Task <IActionResult> Run(
            [HttpTrigger(AuthorizationLevel.Function, "post", Route = null)] HttpRequest req,
            ILogger log,
            ExecutionContext context)
        {
            log.LogInformation("Certificate trigger function processed a request.");

            try
            {
                await ReadAppSettings(context, log);

                string requestBody          = await new StreamReader(req.Body).ReadToEndAsync();
                Certificate_Request request = JsonConvert.DeserializeObject <Certificate_Request>(requestBody);

                // Validate payload
                if (string.IsNullOrEmpty(request.RegistrationId) || string.IsNullOrEmpty(request.Csr))
                {
                    return(new BadRequestResult());
                }

                // Check if the device is authorized to request a certificate
                bool isAuthorized = CheckIfAuthorized(request.RegistrationId);

                if (isAuthorized)
                {
                    log.LogInformation($"{request.RegistrationId} is authorized.");

                    Pkcs10CertificationRequest decodedCsr = null;
                    RsaKeyParameters           publicKey  = null;
                    CertificationRequestInfo   info       = null;

                    // Get the signing certificate from a location
                    X509Certificate serverCertificate = ReadCertificate(cert, location, log);

                    if (serverCertificate == null)
                    {
                        throw new System.Exception("ReadCertificate() was unable to retrieve the signing certificate.");
                    }

                    // Get signing cert private key from a location.
                    AsymmetricKeyParameter serverPrivateKey = ReadPrivateKey(key, location, log);

                    if (serverPrivateKey == null)
                    {
                        throw new System.Exception("ReadPrivateKey() was unable to retrieve the private key.");
                    }

                    byte[] csr = Convert.FromBase64String(request.Csr);

                    // Decode DER
                    decodedCsr = new Pkcs10CertificationRequest(csr);
                    info       = decodedCsr.GetCertificationRequestInfo();
                    SubjectPublicKeyInfo publicKeyInfo = info.SubjectPublicKeyInfo;

                    RsaPublicKeyStructure publicKeyStructure = RsaPublicKeyStructure.GetInstance(publicKeyInfo.ParsePublicKey());

                    publicKey = new RsaKeyParameters(false, publicKeyStructure.Modulus, publicKeyStructure.PublicExponent);

                    bool certIsOK = decodedCsr.Verify(publicKey);

                    // Create the device certificate
                    X509V3CertificateGenerator generator = new X509V3CertificateGenerator();

                    generator.SetSerialNumber(BigInteger.ProbablePrime(120, new Random()));
                    generator.SetIssuerDN(serverCertificate.SubjectDN);
                    generator.SetNotBefore(DateTime.Now);
                    generator.SetNotAfter(DateTime.Now.AddYears(certificateLifespanInYears));
                    generator.SetSubjectDN(info.Subject);
                    generator.SetPublicKey(publicKey);
                    generator.SetSignatureAlgorithm("SHA512withRSA");
                    generator.AddExtension(X509Extensions.AuthorityKeyIdentifier, false, new AuthorityKeyIdentifierStructure(serverCertificate));
                    generator.AddExtension(X509Extensions.SubjectKeyIdentifier, false, new SubjectKeyIdentifierStructure(publicKey));

                    // Generate the device certificate
                    var deviceCert = generator.Generate(serverPrivateKey);

                    // Convert to DER
                    byte[] encoded = deviceCert.GetEncoded();

                    // Convert byte array to Base64 string
                    string encodedString = Convert.ToBase64String(encoded);

                    Certificate_Response responseMessage = new Certificate_Response
                    {
                        Certificate = encodedString
                    };

                    log.LogInformation($"Certificate issued for: {info.Subject}");

                    return(new OkObjectResult(responseMessage));
                }
                else
                {
                    log.LogError($"{request.RegistrationId} is NOT authorized.");

                    return(new UnauthorizedResult());
                }
            }
            catch (Exception ex)
            {
                log.LogInformation(ex.Message);
            }

            return(new BadRequestResult());
        }
Exemplo n.º 19
0
        /*
         * we generate a self signed certificate for the sake of testing - SHA224withECDSA
         */
        private void createECRequest(
            string algorithm,
            DerObjectIdentifier algOid)
        {
            FpCurve curve = new FpCurve(
                new BigInteger("6864797660130609714981900799081393217269435300143305409394463459185543183397656052122559640661454554977296311391480858037121987999716643812574028291115057151"), // q (or p)
                new BigInteger("01FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFC", 16),                      // a
                new BigInteger("0051953EB9618E1C9A1F929A21A0B68540EEA2DA725B99B315F3B8B489918EF109E156193951EC7E937B1652C0BD3BB1BF073573DF883D2C34F1EF451FD46B503F00", 16));                     // b

            ECDomainParameters spec = new ECDomainParameters(
                curve,
//				curve.DecodePoint(Hex.Decode("02C6858E06B70404E9CD9E3ECB662395B4429C648139053FB521F828AF606B4D3DBAA14B5E77EFE75928FE1DC127A2FFA8DE3348B3C1856A429BF97E7E31C2E5BD66")), // G
                curve.DecodePoint(Hex.Decode("0200C6858E06B70404E9CD9E3ECB662395B4429C648139053FB521F828AF606B4D3DBAA14B5E77EFE75928FE1DC127A2FFA8DE3348B3C1856A429BF97E7E31C2E5BD66")),     // G
                new BigInteger("01FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFA51868783BF2F966B7FCC0148F709A5D03BB5C9B8899C47AEBB6FB71E91386409", 16));                 // n

            ECPrivateKeyParameters privKey = new ECPrivateKeyParameters(
                new BigInteger("5769183828869504557786041598510887460263120754767955773309066354712783118202294874205844512909370791582896372147797293913785865682804434049019366394746072023"),                 // d
                spec);

            ECPublicKeyParameters pubKey = new ECPublicKeyParameters(
//				curve.DecodePoint(Hex.Decode("026BFDD2C9278B63C92D6624F151C9D7A822CC75BD983B17D25D74C26740380022D3D8FAF304781E416175EADF4ED6E2B47142D2454A7AC7801DD803CF44A4D1F0AC")), // Q
                curve.DecodePoint(Hex.Decode("02006BFDD2C9278B63C92D6624F151C9D7A822CC75BD983B17D25D74C26740380022D3D8FAF304781E416175EADF4ED6E2B47142D2454A7AC7801DD803CF44A4D1F0AC")),                 // Q
                spec);

//			//
//			// set up the keys
//			//
//			AsymmetricKeyParameter privKey;
//			AsymmetricKeyParameter pubKey;
//
//			KeyFactory fact = KeyFactory.getInstance("ECDSA");
//
//			privKey = fact.generatePrivate(privKeySpec);
//			pubKey = fact.generatePublic(pubKeySpec);

            Pkcs10CertificationRequest req = new Pkcs10CertificationRequest(
                algorithm, new X509Name("CN=XXX"), pubKey, null, privKey);

            if (!req.Verify())
            {
                Fail("Failed Verify check EC.");
            }

            req = new Pkcs10CertificationRequest(req.GetEncoded());
            if (!req.Verify())
            {
                Fail("Failed Verify check EC encoded.");
            }

            //
            // try with point compression turned off
            //
//			((ECPointEncoder)pubKey).setPointFormat("UNCOMPRESSED");
            FpPoint q = (FpPoint)pubKey.Q;

            pubKey = new ECPublicKeyParameters(
                pubKey.AlgorithmName,
                new FpPoint(q.Curve, q.X, q.Y, false),
                pubKey.Parameters);

            req = new Pkcs10CertificationRequest(
                algorithm, new X509Name("CN=XXX"), pubKey, null, privKey);
            if (!req.Verify())
            {
                Fail("Failed Verify check EC uncompressed.");
            }

            req = new Pkcs10CertificationRequest(req.GetEncoded());
            if (!req.Verify())
            {
                Fail("Failed Verify check EC uncompressed encoded.");
            }

            if (!req.SignatureAlgorithm.ObjectID.Equals(algOid))
            {
                Fail("ECDSA oid incorrect.");
            }

            if (req.SignatureAlgorithm.Parameters != null)
            {
                Fail("ECDSA parameters incorrect.");
            }

            ISigner sig = SignerUtilities.GetSigner(algorithm);

            sig.Init(false, pubKey);

            byte[] b = req.GetCertificationRequestInfo().GetEncoded();
            sig.BlockUpdate(b, 0, b.Length);

            if (!sig.VerifySignature(req.Signature.GetBytes()))
            {
                Fail("signature not mapped correctly.");
            }
        }
Exemplo n.º 20
0
        /// <summary>
        /// Read CA private key file from .key or pfx file
        /// Read data from certificate request file .csr
        /// Generate signed certificate request file .cer
        /// </summary>
        /// <param name="signedCERFile"></param>
        /// <param name="privateKeyFile"></param>
        /// <param name="v"></param>
        /// <param name="password"></param>
        private async void GenerateCerFile(string certRequestFile,
                                           string privateKeyFile,
                                           string generateSignedCertificateFile,
                                           string password,
                                           DateTime requestStartDate, DateTime requestEndDate)
        {
            int errorNum = 0;

            issueCertificate.IsEnabled = false;
            progressring.Visibility    = Visibility.Visible;
            await System.Threading.Tasks.TaskEx.Delay(1000);

            tbOutputMessageBox.Text = "";

            #region LoadCertificate

            X509Certificate2 issuerCertificate = null;
            try
            {
                await System.Threading.Tasks.TaskEx.Delay(1000);

                issuerCertificate = new X509Certificate2(
                    privateKeyFile,
                    password,
                    X509KeyStorageFlags.Exportable
                    );
            }
            // Exceptions:
            //   T:System.Security.Cryptography.CryptographicException:
            //     An error with the certificate occurs. For example:The certificate file does not
            //     exist.The certificate is invalid.The certificate's password is incorrect.
            catch (System.Security.Cryptography.CryptographicException ex)
            {
                errorNum++;

                progressring.Visibility    = Visibility.Hidden;
                issueCertificate.IsEnabled = true;

                Application.Current.Dispatcher.Invoke(new Action(() =>
                {
                    tbOutputMessageBox.Inlines.Add(new Run
                    {
                        Text       = "Cryptographic ERROR=" + ex.Message + "\n",
                        Foreground = System.Windows.Media.Brushes.Red
                    });
                }));

                return;
            }
            catch (Exception ex)
            {
                errorNum++;

                progressring.Visibility    = Visibility.Hidden;
                issueCertificate.IsEnabled = true;

                Application.Current.Dispatcher.Invoke(new Action(() =>
                {
                    tbOutputMessageBox.Inlines.Add(new Run
                    {
                        Text       = "General ERROR=" + ex.Message + "\n",
                        Foreground = System.Windows.Media.Brushes.Red
                    });
                }));

                return;
            }

            // This doesn't work for selfsign certificate
            //bool isOK = issuerCertificate.Verify();

            bool     isHasPrivateKey = issuerCertificate.HasPrivateKey;
            DateTime noAfter         = issuerCertificate.NotAfter;
            DateTime noBefore        = issuerCertificate.NotBefore;
            X509ExtensionCollection x509extensions = issuerCertificate.Extensions;

            await System.Threading.Tasks.TaskEx.Delay(1000);

            X509CertificateParser parser = new X509CertificateParser();
            Org.BouncyCastle.X509.X509Certificate bouncyCertificate = parser.ReadCertificate(issuerCertificate.RawData);
            BasicConstraints basicConstraints = null;
            bool             isCa             = false;
            Asn1OctetString  str = bouncyCertificate.GetExtensionValue(new DerObjectIdentifier("2.5.29.19")); // Basic Constraints -> DerObjectIdentifier BasicConstraints = new DerObjectIdentifier("2.5.29.19");
            if (str != null)
            {
                basicConstraints = BasicConstraints.GetInstance(X509ExtensionUtilities.FromExtensionValue(str));
                if (basicConstraints != null)
                {
                    isCa = basicConstraints.IsCA();
                }
            }

            if (!isCa)
            {
                errorNum++;

                Application.Current.Dispatcher.Invoke(new Action(() =>
                {
                    tbOutputMessageBox.Inlines.Add(new Run
                    {
                        Text       = "Loaded CA file: " + privateKeyFile + " IS NOT CA authority certificate file!" + "\n",
                        Foreground = System.Windows.Media.Brushes.Red
                    });
                }));
            }

            // This doesn't work for selfsign certificate
            //if (!isOK)
            //{
            //    errorNum++;
            //    Brush bckForeground = tbOutputMessageBox.Foreground;
            //    tbOutputMessageBox.Foreground = new SolidColorBrush(Colors.Red);
            //    tbOutputMessageBox.Text += "File with CA certificate NOT valid." + "\n";
            //    tbOutputMessageBox.Foreground = bckForeground;
            //}
            if (!isHasPrivateKey)
            {
                errorNum++;

                Application.Current.Dispatcher.Invoke(new Action(() =>
                {
                    tbOutputMessageBox.Inlines.Add(new Run
                    {
                        Text       = "File with CA certificate DOES NOT have a private key." + "\n",
                        Foreground = System.Windows.Media.Brushes.Red
                    });
                }));
            }
            if (noBefore > requestStartDate)
            {
                errorNum++;

                Application.Current.Dispatcher.Invoke(new Action(() =>
                {
                    tbOutputMessageBox.Inlines.Add(new Run
                    {
                        Text       = "File with CA certificate start date: " + requestStartDate.ToLocalTime() + " DOES NOT valid value. Certificate start date is: " + noBefore.ToLocalTime() + "\n",
                        Foreground = System.Windows.Media.Brushes.Red
                    });
                }));
            }
            if (noAfter < requestEndDate)
            {
                errorNum++;

                Application.Current.Dispatcher.Invoke(new Action(() =>
                {
                    tbOutputMessageBox.Inlines.Add(new Run
                    {
                        Text       = "File with CA certificate end date: " + requestEndDate.ToLocalTime() + " DOES NOT valid value. Certificate end date is: " + noAfter.ToLocalTime() + "\n",
                        Foreground = System.Windows.Media.Brushes.Red
                    });
                }));
            }

            if (errorNum > 0)
            {
                Application.Current.Dispatcher.Invoke(new Action(() =>
                {
                    tbOutputMessageBox.Inlines.Add(new Run
                    {
                        Text       = "File with CA certificate has error!!!" + "\n",
                        Foreground = System.Windows.Media.Brushes.Red
                    });
                }));

                progressring.Visibility    = Visibility.Hidden;
                issueCertificate.IsEnabled = true;

                return;
            }

            try
            {
                await System.Threading.Tasks.TaskEx.Delay(1000);

                bool isOk = issuerCertificate.Verify();
            }
            catch (Exception ex)
            {
                progressring.Visibility    = Visibility.Hidden;
                issueCertificate.IsEnabled = true;

                Application.Current.Dispatcher.Invoke(new Action(() =>
                {
                    tbOutputMessageBox.Inlines.Add(new Run
                    {
                        Text       = "Error Issuer certificate file: " + issuerCertificate + " Verification error: " + ex.GetHashCode().ToString() + " " + ex.Message + "\n",
                        Foreground = System.Windows.Media.Brushes.Red
                    });
                }));
                return;
            }


            Org.BouncyCastle.X509.X509Certificate issuerCertificateX509 = new X509CertificateParser().ReadCertificate(issuerCertificate.GetRawCertData());
            try
            {
                await System.Threading.Tasks.TaskEx.Delay(1000);

                bool isOK = VerifyCertChain(issuerCertificate);
            }
            catch (Exception ex)
            {
                progressring.Visibility    = Visibility.Hidden;
                issueCertificate.IsEnabled = true;

                Application.Current.Dispatcher.Invoke(new Action(() =>
                {
                    tbOutputMessageBox.Inlines.Add(new Run
                    {
                        Text       = "Error Issuer certificate file: " + issuerCertificate + " public key error: " + ex.GetHashCode().ToString() + " " + ex.Message + "\n",
                        Foreground = System.Windows.Media.Brushes.Red
                    });
                }));
                return;
            }


            Org.BouncyCastle.X509.X509Certificate x509IssuerCert = Org.BouncyCastle.Security.DotNetUtilities.FromX509Certificate(issuerCertificate);
            try
            {
                await System.Threading.Tasks.TaskEx.Delay(1000);

                x509IssuerCert.CheckValidity(requestStartDate);
                await System.Threading.Tasks.TaskEx.Delay(1000);

                x509IssuerCert.CheckValidity(requestEndDate);
            }
            catch (Exception ex)
            {
                progressring.Visibility    = Visibility.Hidden;
                issueCertificate.IsEnabled = true;

                Application.Current.Dispatcher.Invoke(new Action(() =>
                {
                    tbOutputMessageBox.Inlines.Add(new Run
                    {
                        Text       = "Error Issuer certificate file: " + issuerCertificate + " X509 certificate error: " + ex.GetHashCode().ToString() + " " + ex.Message + "\n",
                        Foreground = System.Windows.Media.Brushes.Red
                    });
                }));
                return;
            }

            #endregion

            // Read certificate request .csr file
            Pkcs10CertificationRequest cerRequest = null;
            try
            {
                await System.Threading.Tasks.TaskEx.Delay(1000);

                String       input_data = File.ReadAllText(certRequestFile);
                StringReader sr         = new StringReader(input_data);
                PemReader    pr         = new PemReader(sr);
                cerRequest = (Pkcs10CertificationRequest)pr.ReadObject();

                Application.Current.Dispatcher.Invoke(new Action(() =>
                {
                    tbOutputMessageBox.Inlines.Add(new Run
                    {
                        Text       = "Verify file with certificate request : " + certRequestFile + "\n",
                        Foreground = System.Windows.Media.Brushes.Black
                    });
                }));

                try
                {
                    await System.Threading.Tasks.TaskEx.Delay(1000);

                    bool requestIsOK = cerRequest.Verify();
                    if (requestIsOK)
                    {
                        Application.Current.Dispatcher.Invoke(new Action(() =>
                        {
                            tbOutputMessageBox.Inlines.Add(new Run
                            {
                                Text       = "File with certificate request : " + certRequestFile + " is OK." + "\n",
                                Foreground = System.Windows.Media.Brushes.Black
                            });
                        }));
                    }
                    else
                    {
                        progressring.Visibility    = Visibility.Hidden;
                        issueCertificate.IsEnabled = true;

                        Application.Current.Dispatcher.Invoke(new Action(() =>
                        {
                            tbOutputMessageBox.Inlines.Add(new Run
                            {
                                Text       = "File with certificate request : " + certRequestFile + " NOT valid." + "\n",
                                Foreground = System.Windows.Media.Brushes.Red
                            });
                        }));
                        return;
                    }
                }
                catch (Exception ex)
                {
                    progressring.Visibility    = Visibility.Hidden;
                    issueCertificate.IsEnabled = true;

                    Application.Current.Dispatcher.Invoke(new Action(() =>
                    {
                        tbOutputMessageBox.Inlines.Add(new Run
                        {
                            Text       = "Error certificate request file: " + cerRequest + " Verify error: " + ex.GetHashCode().ToString() + " " + ex.Message + "\n",
                            Foreground = System.Windows.Media.Brushes.Red
                        });
                    }));
                    return;
                }
            }
            catch (Exception ex)
            {
                progressring.Visibility    = Visibility.Hidden;
                issueCertificate.IsEnabled = true;

                var metroWindow = (Application.Current.MainWindow as MetroWindow);
                await metroWindow.ShowMessageAsync("Info Warning",
                                                   "ERROR reading certificate request file (.csr)" + "\n" +
                                                   "Error: " + ex.Source + " " + ex.Message,
                                                   MessageDialogStyle.Affirmative);

                return;
            }

            await System.Threading.Tasks.TaskEx.Delay(1000);

            AsymmetricCipherKeyPair issuerKeyPair = DotNetUtilities.GetKeyPair(issuerCertificate.PrivateKey);

            await System.Threading.Tasks.TaskEx.Delay(1000);

            Org.BouncyCastle.X509.X509Certificate genCert = GenerateSignedCertificate(
                cerRequest,
                x509IssuerCert,
                issuerKeyPair,
                requestStartDate,
                requestEndDate);

            try
            {
                await System.Threading.Tasks.TaskEx.Delay(1000);

                File.WriteAllBytes(System.IO.Path.ChangeExtension(generateSignedCertificateFile, ".cer"), genCert.GetEncoded());

                Application.Current.Dispatcher.Invoke(new Action(() =>
                {
                    tbOutputMessageBox.Inlines.Add(new Run
                    {
                        Text       = "Certificate file: " + generateSignedCertificateFile + " sucessfully saved." + "\n",
                        Foreground = System.Windows.Media.Brushes.Green
                    });
                }));

                btnContinue.IsEnabled = true;
            }
            catch (Exception)
            {
                Application.Current.Dispatcher.Invoke(new Action(() =>
                {
                    tbOutputMessageBox.Inlines.Add(new Run
                    {
                        Text       = "Certificate file sucessfully generated." + "\n",
                        Foreground = System.Windows.Media.Brushes.Green
                    });
                }));
            }
            CertData.cerPublicFilePath = tbPathGenerateCer.Text + "\\" + tbCertFileName.Text + ".cer";

            progressring.Visibility    = Visibility.Hidden;
            issueCertificate.IsEnabled = true;
        }
Exemplo n.º 21
0
        /*
         * we generate a self signed certificate for the sake of testing - SHA224withECDSA
         */
        private void createECRequest(
            string algorithm,
            DerObjectIdentifier algOid)
        {
            X9ECParameters     x9    = ECNamedCurveTable.GetByName("secp521r1");
            ECCurve            curve = x9.Curve;
            ECDomainParameters spec  = new ECDomainParameters(curve, x9.G, x9.N, x9.H);

            ECPrivateKeyParameters privKey = new ECPrivateKeyParameters(
                new BigInteger("5769183828869504557786041598510887460263120754767955773309066354712783118202294874205844512909370791582896372147797293913785865682804434049019366394746072023"), // d
                spec);

            ECPublicKeyParameters pubKey = new ECPublicKeyParameters(
//				curve.DecodePoint(Hex.Decode("026BFDD2C9278B63C92D6624F151C9D7A822CC75BD983B17D25D74C26740380022D3D8FAF304781E416175EADF4ED6E2B47142D2454A7AC7801DD803CF44A4D1F0AC")), // Q
                curve.DecodePoint(Hex.Decode("02006BFDD2C9278B63C92D6624F151C9D7A822CC75BD983B17D25D74C26740380022D3D8FAF304781E416175EADF4ED6E2B47142D2454A7AC7801DD803CF44A4D1F0AC")), // Q
                spec);

//			//
//			// set up the keys
//			//
//			AsymmetricKeyParameter privKey;
//			AsymmetricKeyParameter pubKey;
//
//			KeyFactory fact = KeyFactory.getInstance("ECDSA");
//
//			privKey = fact.generatePrivate(privKeySpec);
//			pubKey = fact.generatePublic(pubKeySpec);

            Pkcs10CertificationRequest req = new Pkcs10CertificationRequest(
                algorithm, new X509Name("CN=XXX"), pubKey, null, privKey);

            if (!req.Verify())
            {
                Fail("Failed Verify check EC.");
            }

            req = new Pkcs10CertificationRequest(req.GetEncoded());
            if (!req.Verify())
            {
                Fail("Failed Verify check EC encoded.");
            }

            //
            // try with point compression turned off
            //
//			((ECPointEncoder)pubKey).setPointFormat("UNCOMPRESSED");
            ECPoint q = pubKey.Q.Normalize();

            pubKey = new ECPublicKeyParameters(
                pubKey.AlgorithmName,
                q.Curve.CreatePoint(q.XCoord.ToBigInteger(), q.YCoord.ToBigInteger()),
                pubKey.Parameters);

            req = new Pkcs10CertificationRequest(
                algorithm, new X509Name("CN=XXX"), pubKey, null, privKey);
            if (!req.Verify())
            {
                Fail("Failed Verify check EC uncompressed.");
            }

            req = new Pkcs10CertificationRequest(req.GetEncoded());
            if (!req.Verify())
            {
                Fail("Failed Verify check EC uncompressed encoded.");
            }

            if (!req.SignatureAlgorithm.Algorithm.Equals(algOid))
            {
                Fail("ECDSA oid incorrect.");
            }

            if (req.SignatureAlgorithm.Parameters != null)
            {
                Fail("ECDSA parameters incorrect.");
            }

            ISigner sig = SignerUtilities.GetSigner(algorithm);

            sig.Init(false, pubKey);

            byte[] b = req.GetCertificationRequestInfo().GetEncoded();
            sig.BlockUpdate(b, 0, b.Length);

            if (!sig.VerifySignature(req.GetSignatureOctets()))
            {
                Fail("signature not mapped correctly.");
            }
        }
Exemplo n.º 22
0
        public override void PerformTest()
        {
            generationTest(512, "RSA", "SHA1withRSA");
            generationTest(512, "GOST3410", "GOST3411withGOST3410");

            //		if (Security.getProvider("SunRsaSign") != null)
            //        {
            //            generationTest(512, "RSA", "SHA1withRSA", "SunRsaSign");
            //        }

            // elliptic curve GOST A parameter set
            Pkcs10CertificationRequest req = new Pkcs10CertificationRequest(gost3410EC_A);

            if (!req.Verify())
            {
                Fail("Failed Verify check gost3410EC_A.");
            }

            // elliptic curve GOST B parameter set
            req = new Pkcs10CertificationRequest(gost3410EC_B);
            if (!req.Verify())
            {
                Fail("Failed Verify check gost3410EC_B.");
            }

            // elliptic curve GOST C parameter set
            req = new Pkcs10CertificationRequest(gost3410EC_C);
            if (!req.Verify())
            {
                Fail("Failed Verify check gost3410EC_C.");
            }

            // elliptic curve GOST ExA parameter set
            req = new Pkcs10CertificationRequest(gost3410EC_ExA);
            if (!req.Verify())
            {
                Fail("Failed Verify check gost3410EC_ExA.");
            }

            // elliptic curve GOST ExB parameter set
            req = new Pkcs10CertificationRequest(gost3410EC_ExB);
            if (!req.Verify())
            {
                Fail("Failed Verify check gost3410EC_ExA.");
            }

            // elliptic curve openSSL
            IAsymmetricCipherKeyPairGenerator g = GeneratorUtilities.GetKeyPairGenerator("ECDSA");

            X9ECParameters     x9     = ECNamedCurveTable.GetByName("prime239v1");
            ECCurve            curve  = x9.Curve;
            ECDomainParameters ecSpec = new ECDomainParameters(curve, x9.G, x9.N, x9.H);

//			g.initialize(ecSpec, new SecureRandom());
            g.Init(new ECKeyGenerationParameters(ecSpec, new SecureRandom()));

            AsymmetricCipherKeyPair kp = g.GenerateKeyPair();

            req = new Pkcs10CertificationRequest(
                "ECDSAWITHSHA1", new X509Name("CN=XXX"), kp.Public, null, kp.Private);

            if (!req.Verify())
            {
                Fail("Failed Verify check EC.");
            }

            createECRequest("SHA1withECDSA", X9ObjectIdentifiers.ECDsaWithSha1);
            createECRequest("SHA224withECDSA", X9ObjectIdentifiers.ECDsaWithSha224);
            createECRequest("SHA256withECDSA", X9ObjectIdentifiers.ECDsaWithSha256);
            createECRequest("SHA384withECDSA", X9ObjectIdentifiers.ECDsaWithSha384);
            createECRequest("SHA512withECDSA", X9ObjectIdentifiers.ECDsaWithSha512);

            createECGostRequest();

            // TODO The setting of parameters for MGF algorithms is not implemented
//			createPssTest("SHA1withRSAandMGF1");
//			createPssTest("SHA224withRSAandMGF1");
//			createPssTest("SHA256withRSAandMGF1");
//			createPssTest("SHA384withRSAandMGF1");

            nullPointerTest();
        }
Exemplo n.º 23
0
        private async Task ProcessCsrGeneration(ThingToGenerate toGenerate)
        {
            SetStatusAndProgress("Generating...");
            var(keyGenerator, signerFactoryFactory) = await CsrGetKeyGeneratorAsync();

            var lines = txtCsrDomains.Text
                        .Split('\r')
                        .Select(x => x.Trim())
                        .Where(x => !string.IsNullOrEmpty(x))
                        .Select(x => x.Split(';', ',').Select(y => y.Trim()).Where(y => !string.IsNullOrEmpty(y)).ToArray())
                        .Where(x => x.Length >= 1)
                        .ToArray();

            string dnO     = txtCsrSubjO.Text.Trim();
            string dnOU    = txtCsrSubjOU.Text.Trim();
            string dnC     = txtCsrSubjC.Text.Trim();
            string dnST    = txtCsrSubjST.Text.Trim();
            string dnL     = txtCsrSubjL.Text.Trim();
            string dnEmail = txtCsrSubjEmail.Text.Trim();

            var dnOrdering = new List <DerObjectIdentifier>();
            var dnValues   = new List <string>();

            dnOrdering.Add(X509Name.CN);
            dnValues.Add("<placeholder>");
            if (!string.IsNullOrEmpty(dnO))
            {
                dnOrdering.Add(X509Name.O); dnValues.Add(dnO);
            }
            if (!string.IsNullOrEmpty(dnOU))
            {
                dnOrdering.Add(X509Name.OU); dnValues.Add(dnOU);
            }
            if (!string.IsNullOrEmpty(dnC))
            {
                dnOrdering.Add(X509Name.C); dnValues.Add(dnC);
            }
            if (!string.IsNullOrEmpty(dnST))
            {
                dnOrdering.Add(X509Name.ST); dnValues.Add(dnST);
            }
            if (!string.IsNullOrEmpty(dnL))
            {
                dnOrdering.Add(X509Name.L); dnValues.Add(dnL);
            }
            if (!string.IsNullOrEmpty(dnEmail))
            {
                dnOrdering.Add(X509Name.EmailAddress); dnValues.Add(dnEmail);
            }

            int cnt = 0;

            foreach (var line in lines)
            {
                SetStatusAndProgress("Generating...", (double)cnt++ / lines.Length);

                string   cn       = line[0];
                string[] altnames = line;

                var dnValuesThese = dnValues.ToArray();
                dnValuesThese[0] = cn;

                var keyPath = Path.Combine(CurrentWorkingDirectory, FixFilename($"{cn}.key"));
                AsymmetricCipherKeyPair key = null;
                if (rdCsrUseExistingKey.Checked && File.Exists(keyPath))
                {
                    try
                    {
                        PemReader pr = new PemReader(File.OpenText(keyPath));
                        key = pr.ReadObject() as AsymmetricCipherKeyPair;
                    }
                    catch { key = null; }
                }

                if (key == null)
                {
                    key = await Task.Factory.StartNew(() => keyGenerator.GenerateKeyPair());

                    WriteToPemFile(keyPath, key);
                }

                X509Name subject = new X509Name(dnOrdering, dnValuesThese);


                if ((toGenerate | ThingToGenerate.Csr) == ThingToGenerate.Csr)
                {
                    X509ExtensionsGenerator extGenerator = GetExtensionsGenerator(altnames);

                    var     exts  = extGenerator.Generate();
                    Asn1Set attrs = new DerSet(new DerSequence(PkcsObjectIdentifiers.Pkcs9AtExtensionRequest, new DerSet(exts)));

                    var req = new Pkcs10CertificationRequest(
                        signerFactoryFactory(key.Private),
                        subject,
                        key.Public,
                        attrs,
                        key.Private);

                    if (!req.Verify())
                    {
                        throw new InvalidOperationException("Generated an invalid CSR.");
                    }
                    WriteToPemFile(Path.Combine(CurrentWorkingDirectory, FixFilename($"{cn}.csr")), req);
                }
                if ((toGenerate | ThingToGenerate.SelfSignedCert) == ThingToGenerate.SelfSignedCert)
                {
                    SecureRandom sr = new SecureRandom();
                    X509V3CertificateGenerator certgen = new X509V3CertificateGenerator();

                    certgen.SetSerialNumber(new BigInteger(128, sr));
                    certgen.SetIssuerDN(subject);
                    certgen.SetSubjectDN(subject);
                    certgen.SetNotBefore(DateTime.Today.Subtract(new TimeSpan(1, 0, 0, 0)));
                    certgen.SetNotAfter(DateTime.Today.AddYears(30));
                    certgen.SetPublicKey(key.Public);

                    foreach (var ext in GetExtensions(altnames))
                    {
                        certgen.AddExtension(ext.oid, ext.isCritical, ext.section);
                    }

                    ISignatureFactory signer;
                    if (key.Private is ECPrivateKeyParameters)
                    {
                        signer = new Asn1SignatureFactory("SHA256WITHECDSA", key.Private, sr);
                    }
                    else
                    {
                        signer = new Asn1SignatureFactory("SHA256WITHRSA", key.Private, sr);
                    }

                    var cert = certgen.Generate(signer);
                    cert.CheckValidity();
                    cert.Verify(key.Public);
                    WriteToPemFile(Path.Combine(CurrentWorkingDirectory, FixFilename($"{cn}.cer")), cert);
                }
            }

            SetStatusAndProgress("Generating CSRs", 1);
        }