A class for verifying and creating Pkcs10 Certification requests.
Inheritance: Org.BouncyCastle.Asn1.Pkcs.CertificationRequest
        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.");
            }
        }
示例#2
0
        public void Certificate_LoadCSR()
        {
            Org.BouncyCastle.Pkcs.Pkcs10CertificationRequest csr = null;
            try
            {
                csr = Certificate.LoadCSR("invalid.csr");
            }
            catch (Exception ex)
            {
                Assert.IsTrue(ex is FileNotFoundException);
            }

            csr = Certificate.LoadCSR("development.com.csr");

            Assert.IsNotNull(csr);

            Org.BouncyCastle.Asn1.Pkcs.CertificationRequestInfo csrInfo = csr.GetCertificationRequestInfo();

            Assert.AreEqual("C=US,ST=Ut,L=SLC,O=Medicity,OU=Healthagen,CN=development.com", csrInfo.Subject.ToString());

            Certificate.SaveCSR(csr, "development.com.copy.csr");

            Org.BouncyCastle.Pkcs.Pkcs10CertificationRequest csr_copy = Certificate.LoadCSR("development.com.copy.csr");

            Assert.AreEqual(csr, csr_copy);
        }
        internal string GenerateCsr(DistinguishedName distinguishedName, string key)
        {
            var keyPair = GetKeyPair(key);

            var csr =
                new Pkcs10CertificationRequest("SHA1WITHRSA", new X509Name(distinguishedName.ToDnString()), keyPair.Public, null, keyPair.Private);

            return GeneratePem(csr);
        }
示例#4
0
 public void generateCSR(string electoralEampaign, string user, string password)
 {
     X509Name name = new X509Name("C=PL, ST=Mazowieckie, L=Warszawa, O=KBW, E=-, OU=" + electoralEampaign + ", CN=" + user);
     RsaKeyPairGenerator keyGenerator = new RsaKeyPairGenerator();
     RsaKeyGenerationParameters param = new RsaKeyGenerationParameters(BigInteger.ValueOf(3L), new SecureRandom(), 2048, 25);
     keyGenerator.Init(param);
     AsymmetricCipherKeyPair ackp = keyGenerator.GenerateKeyPair();
     Pkcs10CertificationRequest csr = new Pkcs10CertificationRequest("SHA1WITHRSA", name, ackp.Public, null, ackp.Private);
     System.Text.StringBuilder CSRPem = new System.Text.StringBuilder();
     PemWriter CSRPemWriter = new PemWriter(new System.IO.StringWriter(CSRPem));
     CSRPemWriter.WriteObject(csr);
     CSRPemWriter.Writer.Flush();
     this.generatedCSR = CSRPem.ToString();
     System.Text.StringBuilder PrivateKeyPem = new System.Text.StringBuilder();
     PemWriter PrivateKeyPemWriter = new PemWriter(new System.IO.StringWriter(PrivateKeyPem));
     PrivateKeyPemWriter.WriteObject(ackp.Private);
     CSRPemWriter.Writer.Flush();
     this.keys = PrivateKeyPem.ToString();
     AsymmetricKeyParameter publicKey = ackp.Public;
     AsymmetricKeyParameter privateKey = ackp.Private;
     System.IO.StringWriter sw = new System.IO.StringWriter();
     PemWriter pw = new PemWriter(sw);
     pw.WriteObject(privateKey, "AES-256-CBC", password.ToCharArray(), new SecureRandom());
     pw.Writer.Close();
     this.keys = sw.ToString();
     if (!System.IO.Directory.Exists(this.path + "\\Licenses"))
     {
         try
         {
             System.IO.Directory.CreateDirectory(this.path + "\\Licenses");
         }
         catch (System.ArgumentNullException)
         {
             MessageBox.Show("Nieprawidłowa ścieżka. Nie można utworzyć katalogu \"Licenses\"", "Error");
         }
         catch (System.ArgumentException)
         {
             MessageBox.Show("Nieprawidłowa ścieżka. Nie można utworzyć katalogu \"Licenses\"", "Error");
         }
         catch (System.UnauthorizedAccessException)
         {
             MessageBox.Show("Nie masz uprawnień do tworzenia katalogów. Otwórz aplikacje jako adnimistrator.", "Uwaga");
         }
         catch (System.IO.PathTooLongException)
         {
             MessageBox.Show("Nieprawidłowa ścieżka. Nie można utworzyć katalogu \"Licenses\"", "Error");
         }
         catch (System.IO.DirectoryNotFoundException)
         {
             MessageBox.Show("Nieprawidłowa ścieżka. Nie można utworzyć katalogu \"Licenses\"", "Error");
         }
         catch (System.NotSupportedException)
         {
             MessageBox.Show("Nieprawidłowy format ścieżki. Nie można utworzyć katalogu \"Licenses\"", "Error");
         }
         catch (System.IO.IOException)
         {
             MessageBox.Show("Nieprawidłowa ścieżka. Nie można utworzyć katalogu \"Licenses\"", "Error");
         }
     }
     string namefile = "";
     try
     {
         int tmp = System.IO.Directory.GetFiles(this.path + "\\Licenses", electoralEampaign.Replace("/", "_") + "_" + user + "*.csr").Length + 1;
         if (tmp > 1)
         {
             string num = tmp.ToString();
             namefile = string.Concat(new string[]
             {
                 electoralEampaign.Replace("/", "_"),
                 "_",
                 user,
                 " ",
                 num
             });
         }
         else
         {
             namefile = electoralEampaign.Replace("/", "_") + "_" + user;
         }
     }
     catch (System.Exception)
     {
         namefile = electoralEampaign.Replace("/", "_") + "_" + user;
     }
     try
     {
         System.IO.StreamWriter sw2 = new System.IO.StreamWriter(this.path + "\\Licenses\\" + namefile + ".csr", false);
         sw2.Write(this.generatedCSR);
         sw2.Close();
         sw2 = new System.IO.StreamWriter(this.path + "\\Licenses\\" + namefile + ".key", false);
         sw2.Write(this.keys);
         sw2.Close();
     }
     catch (System.ArgumentNullException)
     {
         MessageBox.Show("Błędna ścieżka", "Error");
     }
     catch (System.ArgumentException)
     {
         MessageBox.Show("Błędna ścieżka", "Error");
     }
     catch (System.IO.DirectoryNotFoundException)
     {
         MessageBox.Show("Nie znaleziono katalogu", "Error");
     }
     catch (System.IO.PathTooLongException)
     {
         MessageBox.Show("Zbyt długa ścieżka do katalogu", "Error");
     }
     catch (System.IO.IOException)
     {
         MessageBox.Show("Podano ścieżke do pliku zamiast katalogu", "Error");
     }
     catch (System.UnauthorizedAccessException)
     {
         MessageBox.Show("Program nie posiada uprawnień do zapisywania plików. Otwórz aplikacje jako Administrator", "Error");
     }
     catch (System.Exception e)
     {
         MessageBox.Show("Nie można zapisać pliku. Orginal error: " + e.Message, "Error");
     }
 }
		//@TODO: Generates a seemingly valid CSR but the Apple website doesn't accept this one (there is a context dependant 0 missing and a null missing compared to Keychain or OpenSSL generated ones, so the files aren't structurally identical)
		private void GenerateSigningRequestViaBouncyCastle(string TargetCertRequestFileName, AsymmetricCipherKeyPair KeyPair)
		{
			// Construct the request subject
			Hashtable Attributes = new Hashtable();
			Attributes.Add(X509Name.EmailAddress, EMailEditBox.Text);
			Attributes.Add(X509Name.CN, CommonNameEditBox.Text);
			Attributes.Add(X509Name.C, System.Globalization.RegionInfo.CurrentRegion.TwoLetterISORegionName);

			X509Name Subject = new X509Name(new ArrayList(Attributes.Keys), Attributes);

			// Generate a certificate signing request
			Pkcs10CertificationRequest CSR = new Pkcs10CertificationRequest(
				"SHA1withRSA",
				Subject,
				KeyPair.Public,
				null,
				KeyPair.Private);

			// Save the CSR to disk
			File.WriteAllBytes(TargetCertRequestFileName, CSR.GetEncoded());
		}
        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()));

            IAsymmetricCipherKeyPair 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();
        }
        // previous code found to cause a NullPointerException
        private void nullPointerTest()
        {
            IAsymmetricCipherKeyPairGenerator keyGen = GeneratorUtilities.GetKeyPairGenerator("RSA");
            keyGen.Init(new KeyGenerationParameters(new SecureRandom(), 1024));

            IAsymmetricCipherKeyPair pair = keyGen.GenerateKeyPair();

            IList oids = new ArrayList();
            IList values = new ArrayList();
            oids.Add(X509Extensions.BasicConstraints);
            values.Add(new X509Extension(true, new DerOctetString(new BasicConstraints(true))));
            oids.Add(X509Extensions.KeyUsage);
            values.Add(new X509Extension(true, new DerOctetString(
                new KeyUsage(KeyUsage.KeyCertSign | KeyUsage.CrlSign))));
            SubjectKeyIdentifier subjectKeyIdentifier = new SubjectKeyIdentifierStructure(pair.Public);
            X509Extension ski = new X509Extension(false, new DerOctetString(subjectKeyIdentifier));
            oids.Add(X509Extensions.SubjectKeyIdentifier);
            values.Add(ski);

            AttributePkcs attribute = new AttributePkcs(PkcsObjectIdentifiers.Pkcs9AtExtensionRequest,
                new DerSet(new X509Extensions(oids, values)));

            Pkcs10CertificationRequest p1 = new Pkcs10CertificationRequest(
                "SHA1WithRSA", new X509Name("cn=csr"), pair.Public, new DerSet(attribute), pair.Private);
            Pkcs10CertificationRequest p2 = new Pkcs10CertificationRequest(
                "SHA1WithRSA", new X509Name("cn=csr"), pair.Public, new DerSet(attribute), pair.Private);

            if (!p1.Equals(p2))
            {
                Fail("cert request comparison failed");
            }
        }
        private void generationTest(
			int		keySize,
			string	keyName,
			string	sigName)
        {
            IAsymmetricCipherKeyPairGenerator kpg = GeneratorUtilities.GetKeyPairGenerator(keyName);

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

            IAsymmetricCipherKeyPair 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.");
            }
        }
        /*
         * 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
            //			//
            //			IAsymmetricKeyParameter privKey;
            //			IAsymmetricKeyParameter 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.");
            }
        }
        private void createECGostRequest()
        {
            string algorithm = "GOST3411withECGOST3410";
            IAsymmetricCipherKeyPairGenerator ecGostKpg = GeneratorUtilities.GetKeyPairGenerator("ECGOST3410");

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

            //
            // set up the keys
            //
            IAsymmetricCipherKeyPair pair = ecGostKpg.GenerateKeyPair();
            IAsymmetricKeyParameter privKey = pair.Private;
            IAsymmetricKeyParameter 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.");
            }
        }
        public void TestMethod1()
        {
            // this snippet can be easily used in any normal c# project as well by simply removing the .Dump() methods
            // and saving the output into a variable / file of your choice.
            // you'll need to add BouncyCastle.Crypto nuget to use this.
            // tested on 1.8.0-beta4

            AsymmetricCipherKeyPair pair;
            Pkcs10CertificationRequest csr;

            var ecMode = false;
            var values = new Dictionary<DerObjectIdentifier, string> {
    {X509Name.CN, ""}, //domain name
    {X509Name.OU, "Domain Control Validated"},
    {X509Name.O, ""}, //Organisation's Legal name
    {X509Name.L, "London"},
    {X509Name.ST, "England"},
    {X509Name.C, "GB"},
};

            var subjectAlternateNames = new GeneralName[] { };

            var extensions = new Dictionary<DerObjectIdentifier, X509Extension>()
{
    {X509Extensions.BasicConstraints, new X509Extension(true, new DerOctetString(new BasicConstraints(false)))},
    {X509Extensions.KeyUsage, new X509Extension(true, new DerOctetString(new KeyUsage(KeyUsage.DigitalSignature | KeyUsage.KeyEncipherment | KeyUsage.DataEncipherment | KeyUsage.NonRepudiation)))},
    {X509Extensions.ExtendedKeyUsage, new X509Extension(false, new DerOctetString(new ExtendedKeyUsage(KeyPurposeID.IdKPServerAuth)))},
};

            if (values[X509Name.CN].StartsWith("www.")) values[X509Name.CN] = values[X509Name.CN].Substring(4);

            if (!values[X509Name.CN].StartsWith("*.") && subjectAlternateNames.Length == 0)
                subjectAlternateNames = new GeneralName[] { new GeneralName(GeneralName.DnsName, $"www.{values[X509Name.CN]}") };

            if (subjectAlternateNames.Length > 0) extensions.Add(X509Extensions.SubjectAlternativeName, new X509Extension(false, new DerOctetString(new GeneralNames(subjectAlternateNames))));

            var subject = new X509Name(values.Keys.Reverse().ToList(), values);

            if (ecMode)
            {
                var gen = new ECKeyPairGenerator();
                var ecp = Org.BouncyCastle.Asn1.Sec.SecNamedCurves.GetByName("secp384r1");
                gen.Init(new ECKeyGenerationParameters(new ECDomainParameters(ecp.Curve, ecp.G, ecp.N, ecp.H, ecp.GetSeed()), new SecureRandom()));

                pair = gen.GenerateKeyPair();

                extensions.Add(X509Extensions.SubjectKeyIdentifier, new X509Extension(false, new DerOctetString(new SubjectKeyIdentifierStructure(pair.Public))));
                csr = new Pkcs10CertificationRequest("SHA256withECDSA", subject, pair.Public, new DerSet(new AttributePkcs(PkcsObjectIdentifiers.Pkcs9AtExtensionRequest, new DerSet(new X509Extensions(extensions)))), pair.Private);

            }
            else
            {
                var gen = new RsaKeyPairGenerator();
                gen.Init(new KeyGenerationParameters(new SecureRandom(), 2048));

                pair = gen.GenerateKeyPair();
                extensions.Add(X509Extensions.SubjectKeyIdentifier, new X509Extension(false, new DerOctetString(new SubjectKeyIdentifierStructure(pair.Public))));
                csr = new Pkcs10CertificationRequest("SHA256withRSA", subject, pair.Public, new DerSet(new AttributePkcs(PkcsObjectIdentifiers.Pkcs9AtExtensionRequest, new DerSet(new X509Extensions(extensions)))), pair.Private);
            }

            //Convert BouncyCastle csr to .PEM file.
            var csrPem = new StringBuilder();
            var csrPemWriter = new PemWriter(new StringWriter(csrPem));
            csrPemWriter.WriteObject(csr);
            csrPemWriter.Writer.Flush();

            Console.WriteLine(csrPem.ToString());

            var privateKeyPem = new StringBuilder();
            var privateKeyPemWriter = new PemWriter(new StringWriter(privateKeyPem));
            privateKeyPemWriter.WriteObject(pair.Private);
            csrPemWriter.Writer.Flush();

            //privateKeyPem.ToString().Dump("Private Key");
        }
 internal string GeneratePem(Pkcs10CertificationRequest certificationRequest)
 {
     return GeneratePemFromObject(certificationRequest);
 }
        //public string GenerateSwCertificate(string edId)
        //{
        //    byte[] csrBinary = GenerateCSR(edId);
        //    return System.Convert.ToBase64String(csrBinary);
        //}
        private string GenerateCSR(string edId)
        {
            Dictionary<Org.BouncyCastle.Asn1.DerObjectIdentifier, string> Dn = new Dictionary<Org.BouncyCastle.Asn1.DerObjectIdentifier, string>();
            Dn.Add(X509Name.UID, edId);

            //X509Name name = new X509Name(new ArrayList(Dn.Keys), new ArrayList(Dn.Values)); //( "CN="+EdId+", C=AT"); //, E=" + EdId);
            X509Name name = new X509Name(new List<DerObjectIdentifier>(Dn.Keys), new List<string>(Dn.Values));
            //Key generation 2048bits
            rkpg = new RsaKeyPairGenerator();
            rkpg.Init(new KeyGenerationParameters(new SecureRandom(), 2048));

            ackp = rkpg.GenerateKeyPair();

            //PKCS #10 Certificate.Certificate Signing Request
            KeyUsage usage = new KeyUsage(KeyUsage.DigitalSignature | KeyUsage.KeyEncipherment);

            Pkcs10CertificationRequest csr = new Pkcs10CertificationRequest("SHA256WITHRSA", name, ackp.Public, null, ackp.Private);
            byte[] csrBinary = csr.GetDerEncoded();
            return System.Convert.ToBase64String(csrBinary);
        }
示例#14
0
        /// <summary>
        /// Erstellt die für die PKCS#10-Datei notwendigen Daten
        /// </summary>
        /// <returns>Die für die PKCS#10-Datei notwendigen Daten</returns>
        public Pkcs10Data CreateRequest()
        {
            var sigAlgoName = "SHA256WITHRSA";
            var subject = new X509Name(
                true,
                $"CN={Requester.Surname}, OU={Requester.Number}, OU={Requester.CompanyName}, O={"ITSG TrustCenter fuer Arbeitgeber"}, C={"DE"}",
                new Pkcs.X509ItsgEntryConverter()
            );

            var rng = new SecureRandom();
            var rsaKeyPair = RSA;
            if (rsaKeyPair == null)
            {
                var keyPairGen = new RsaKeyPairGenerator();
                keyPairGen.Init(new KeyGenerationParameters(rng, 2048));
                rsaKeyPair = keyPairGen.GenerateKeyPair();
            }
            var csr = new Pkcs10CertificationRequest(sigAlgoName, subject, rsaKeyPair.Public, null, rsaKeyPair.Private);
            
            var outputCsrPem = new StringWriter();
            {
                var pemWriter = new PemWriter(outputCsrPem);
                pemWriter.WriteObject(csr);
            }

            var outputPrivateKeyPem = new StringWriter();
            {
                var pemWriter = new PemWriter(outputPrivateKeyPem);
                if (string.IsNullOrEmpty(Password))
                {
                    pemWriter.WriteObject(rsaKeyPair.Private);
                }
                else
                {
                    pemWriter.WriteObject(
                        rsaKeyPair.Private,
                        "des-ede3-cbc",
                        Password.ToCharArray(),
                        rng
                    );
                }
            }

            var rsaPubKey = (RsaKeyParameters)rsaKeyPair.Public;
            var rawPubKeyData = OstcUtils.CalculatePublicKeyHash(rsaPubKey);

            return new Pkcs10Data(csr.GetEncoded(), outputCsrPem.ToString(), outputPrivateKeyPem.ToString(), rawPubKeyData);
        }