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.");
            }
        }
        /// <summary>
        /// Creates a certificate signing request from an
        /// existing certificate with a private key.
        /// </summary>
        public static byte[] CreateSigningRequest(
            X509Certificate2 certificate,
            IList <String> domainNames = null
            )
        {
            if (certificate == null)
            {
                throw new ArgumentNullException(nameof(certificate));
            }
            using (var cfrg = new CertificateFactoryRandomGenerator())
            {
                SecureRandom random = new SecureRandom(cfrg);

                // try to get signing/private key from certificate passed in
                AsymmetricKeyParameter signingKey = X509Utils.GetPrivateKeyParameter(certificate);
                RsaKeyParameters       publicKey  = X509Utils.GetPublicKeyParameter(certificate);

                ISignatureFactory signatureFactory =
                    new Asn1SignatureFactory(X509Utils.GetRSAHashAlgorithm(X509Defaults.HashAlgorithmName), signingKey, random);

                Asn1Set attributes = null;
                var     san        = X509Extensions.FindExtension <X509SubjectAltNameExtension>(certificate);
                X509SubjectAltNameExtension alternateName = new X509SubjectAltNameExtension(san, san.Critical);

                string applicationUri = null;
                domainNames = domainNames ?? new List <String>();
                if (alternateName != null)
                {
                    if (alternateName.Uris.Count > 0)
                    {
                        applicationUri = alternateName.Uris[0];
                    }
                    foreach (var name in alternateName.DomainNames)
                    {
                        if (!domainNames.Any(s => s.Equals(name, StringComparison.OrdinalIgnoreCase)))
                        {
                            domainNames.Add(name);
                        }
                    }
                    foreach (var ipAddress in alternateName.IPAddresses)
                    {
                        if (!domainNames.Any(s => s.Equals(ipAddress, StringComparison.OrdinalIgnoreCase)))
                        {
                            domainNames.Add(ipAddress);
                        }
                    }
                }

                // build CSR extensions
                var generalNames = new List <GeneralName>();

                if (applicationUri != null)
                {
                    generalNames.Add(new GeneralName(GeneralName.UniformResourceIdentifier, applicationUri));
                }

                if (domainNames.Count > 0)
                {
                    generalNames.AddRange(BouncyCastle.X509Extensions.CreateSubjectAlternateNameDomains(domainNames));
                }

                if (generalNames.Count > 0)
                {
                    IList oids   = new ArrayList();
                    IList values = new ArrayList();
                    oids.Add(Org.BouncyCastle.Asn1.X509.X509Extensions.SubjectAlternativeName);
                    values.Add(new Org.BouncyCastle.Asn1.X509.X509Extension(false,
                                                                            new DerOctetString(new GeneralNames(generalNames.ToArray()).GetDerEncoded())));
                    var attribute = new Org.BouncyCastle.Asn1.Pkcs.AttributePkcs(Org.BouncyCastle.Asn1.Pkcs.PkcsObjectIdentifiers.Pkcs9AtExtensionRequest,
                                                                                 new DerSet(new Org.BouncyCastle.Asn1.X509.X509Extensions(oids, values)));
                    attributes = new DerSet(attribute);
                }

                var pkcs10CertificationRequest = new Pkcs10CertificationRequest(
                    signatureFactory,
                    new CertificateFactoryX509Name(false, certificate.Subject),
                    publicKey,
                    attributes);

                return(pkcs10CertificationRequest.GetEncoded());
            }
        }
Exemplo n.º 3
0
    /// <summary>
    /// Creates a certificate signing request from an existing certificate.
    /// </summary>
    public static byte[] CreateSigningRequest(
        X509Certificate2 certificate,
        IList <String> domainNames = null
        )
    {
        using (var cfrg = new CertificateFactoryRandomGenerator())
        {
            SecureRandom random = new SecureRandom(cfrg);

            // try to get signing/private key from certificate passed in
            AsymmetricKeyParameter signingKey = GetPrivateKeyParameter(certificate);
            RsaKeyParameters       publicKey  = GetPublicKeyParameter(certificate);

            ISignatureFactory signatureFactory =
                new Asn1SignatureFactory(GetRSAHashAlgorithm(defaultHashSize), signingKey, random);

            Asn1Set attributes = null;
            X509SubjectAltNameExtension alternateName = null;
            foreach (System.Security.Cryptography.X509Certificates.X509Extension extension in certificate.Extensions)
            {
                if (extension.Oid.Value == X509SubjectAltNameExtension.SubjectAltNameOid || extension.Oid.Value == X509SubjectAltNameExtension.SubjectAltName2Oid)
                {
                    alternateName = new X509SubjectAltNameExtension(extension, extension.Critical);
                    break;
                }
            }

            domainNames = domainNames ?? new List <String>();
            if (alternateName != null)
            {
                foreach (var name in alternateName.DomainNames)
                {
                    if (!domainNames.Any(s => s.Equals(name, StringComparison.OrdinalIgnoreCase)))
                    {
                        domainNames.Add(name);
                    }
                }
                foreach (var ipAddress in alternateName.IPAddresses)
                {
                    if (!domainNames.Any(s => s.Equals(ipAddress, StringComparison.OrdinalIgnoreCase)))
                    {
                        domainNames.Add(ipAddress);
                    }
                }
            }

            // build CSR extensions
            List <GeneralName> generalNames = new List <GeneralName>();

            string applicationUri = Utils.GetApplicationUriFromCertificate(certificate);
            if (applicationUri != null)
            {
                generalNames.Add(new GeneralName(GeneralName.UniformResourceIdentifier, applicationUri));
            }

            if (domainNames.Count > 0)
            {
                generalNames.AddRange(CreateSubjectAlternateNameDomains(domainNames));
            }

            if (generalNames.Count > 0)
            {
                IList oids   = new ArrayList();
                IList values = new ArrayList();
                oids.Add(X509Extensions.SubjectAlternativeName);
                values.Add(new Org.BouncyCastle.Asn1.X509.X509Extension(false,
                                                                        new DerOctetString(new GeneralNames(generalNames.ToArray()).GetDerEncoded())));
                AttributePkcs attribute = new AttributePkcs(PkcsObjectIdentifiers.Pkcs9AtExtensionRequest,
                                                            new DerSet(new X509Extensions(oids, values)));
                attributes = new DerSet(attribute);
            }

            Pkcs10CertificationRequest pkcs10CertificationRequest = new Pkcs10CertificationRequest(
                signatureFactory,
                new CertificateFactoryX509Name(false, certificate.Subject),
                publicKey,
                attributes,
                signingKey);

            return(pkcs10CertificationRequest.GetEncoded());
        }
    }
Exemplo n.º 4
0
 /// <summary>
 /// Base64 encode a PKCS#10 certificate request
 /// </summary>
 /// <param name="request"></param>
 /// <returns></returns>
 public static string rqst64(Pkcs10CertificationRequest request)
 {
     return(Convert.ToBase64String(request.GetEncoded()));
 }
Exemplo n.º 5
0
        public static Tuple <string, AsymmetricKeyParameter> GetSMCsr(string issuerName)
        {
            //generate KeyPair
            var keyGenerator             = new ECKeyPairGenerator();
            ECKeyGenerationParameters pa = new ECKeyGenerationParameters(GMObjectIdentifiers.sm2p256v1, new SecureRandom());

            keyGenerator.Init(pa);
            var keypair = keyGenerator.GenerateKeyPair();

            //domain name of CSR file
            X509Name principal = new X509Name(string.Format("CN={0},OU=client,O=BSN", string.IsNullOrEmpty(issuerName) ? "test02@app0001202004161020152918451" : issuerName));

            //load public key
            SubjectPublicKeyInfo subjectPublicKeyInfo = SubjectPublicKeyInfoFactory.CreateSubjectPublicKeyInfo(keypair.Public);

            CertificationRequestInfo info = new CertificationRequestInfo(principal, subjectPublicKeyInfo, new DerSet());

            //signature
            byte[] bs = ECDSAHelper.CsrSignData(info.GetEncoded(Asn1Encodable.Der), keypair.Private, pa.DomainParameters.N);
            //generate csr object
            Pkcs10CertificationRequest p10 = new Pkcs10CertificationRequest(new CertificationRequest
                                                                                (info, new AlgorithmIdentifier(GMObjectIdentifiers.sm2sign_with_sm3),
                                                                                new DerBitString(bs)).GetEncoded());

            //generate csr string
            Org.BouncyCastle.Utilities.IO.Pem.PemObject pemCSR = new Org.BouncyCastle.Utilities.IO.Pem.PemObject("CERTIFICATE REQUEST", p10.GetEncoded());

            StringWriter str = new StringWriter();

            Org.BouncyCastle.Utilities.IO.Pem.PemWriter pemCsr = new Org.BouncyCastle.Utilities.IO.Pem.PemWriter(str);
            pemCsr.WriteObject(pemCSR);
            pemCsr.Writer.Flush();

            return(new Tuple <string, AsymmetricKeyParameter>(str.ToString(), keypair.Private));
        }
Exemplo n.º 6
0
        internal byte[] CreatePKCS10CSRTest(ParametersValidation validationRequest, out StepType stepType, out SoapException exc, out int timeout, DistinguishedName Subject, string KeyID, CSRAttribute[] CSRAttribute, AlgorithmIdentifier SignatureAlgorithm)
        {
            int special;


            VoidCommand("CreatePKCS10CSR", CreatePKCS10CSR, validationRequest, true, out stepType, out exc, out timeout, out special);

            byte[] result;


            switch (special)
            {
            case 1:
                //Correct response
                var subject = "";
                if (null != Subject)
                {
                    var r = new StringBuilder();
                    if (null != Subject.CommonName)
                    {
                        r.Append(string.Format("CN={0},", Subject.CommonName));
                    }
                    if (null != Subject.Country)
                    {
                        r.Append(string.Format("C={0},", Subject.Country));
                    }
                    if (null != Subject.Locality)
                    {
                        r.Append(string.Format("L={0},", Subject.Locality));
                    }
                    if (null != Subject.Organization)
                    {
                        r.Append(string.Format("O={0},", Subject.Organization));
                    }
                    if (null != Subject.OrganizationalUnit)
                    {
                        r.Append(string.Format("OU={0},", Subject.OrganizationalUnit));
                    }
                    if (null != Subject.StateOrProvinceName)
                    {
                        r.Append(string.Format("ST={0},", Subject.StateOrProvinceName));
                    }

                    subject = r.ToString().TrimEnd(',');
                }

                var generator = new RsaKeyPairGenerator();
                generator.Init(new KeyGenerationParameters(new SecureRandom(), 1024));

                var keyPair = generator.GenerateKeyPair();

                var signatureAlg = "SHA1WithRSAEncryption";
                if (null != SignatureAlgorithm && !string.IsNullOrEmpty(SignatureAlgorithm.algorithm))
                {
                    signatureAlg = SignatureAlgorithm.algorithm;
                }

                var csr = new Pkcs10CertificationRequest(signatureAlg, new X509Name(subject), keyPair.Public, null, keyPair.Private);
                TestCommon.writeToLogInfo("Public Key: " + csr.GetCertificationRequestInfo().SubjectPublicKeyInfo.PublicKeyData.ToString());
                TestCommon.writeToLogInfo("Signature: " + csr.Signature.ToString());
                TestCommon.writeToLogInfo("SignatureAlgorithm: " + csr.SignatureAlgorithm.ObjectID.ToString());
                TestCommon.writeToLogInfo("Subject: " + csr.GetCertificationRequestInfo().Subject.ToString());

                result = csr.GetEncoded();
                break;

            case 2:
                //with sign error, sign lenght 1024
                result = TestCommon.ReadBinary(TestCommon.PCS10Binary3Uri);
                break;

            case 3:
                //without error, sign lenght 3072
                result = new byte[1];
                break;

            case 4:
                //without error, sign lenght 3072
                result = new byte[0];
                break;

            case 5:
                //without sign error, sign lenght 1024, with wrong subject
                result = TestCommon.ReadBinary(TestCommon.PCS10Binary2Uri);
                break;

            default:
                result = null;
                break;
            }

            return(result);
        }
        /*
         * 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");
            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.");
            }
        }