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.");
            }
        }
示例#2
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);

            return(pkcs10CertificationRequest.GetEncoded());
        }
    }
示例#3
0
 /// <summary>
 /// Create a PKCS#10 Parser using an Asn1Sequence
 /// </summary>
 /// <param name="Sequence">Asn1Sequence containing request</param>
 /// <exception cref="SignatureException">POP test failed</exception>
 public Pkcs10Parser(Asn1Sequence Sequence)
 {
     this.request = new Pkcs10CertificationRequest(Sequence);
     readRequest();
 }
示例#4
0
 /// <summary>
 /// Create a PKCS#10 Parser using a byte[]
 /// </summary>
 /// <param name="Request">byte[] containing request</param>
 /// <exception cref="SignatureException">POP test failed</exception>
 public Pkcs10Parser(byte[] Request)
 {
     this.request = new Pkcs10CertificationRequest(Request);
     readRequest();
 }
        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();
        }
        public async Task ValidateMergeCertificate()
        {
            string serverCertificateName = Recording.GenerateId();

            // Generate the request.
            CertificatePolicy policy = new CertificatePolicy(WellKnownIssuerNames.Unknown, "CN=Azure SDK")
            {
                CertificateTransparency = false,
                ContentType             = CertificateContentType.Pkcs12,
            };

            CertificateOperation operation = await Client.StartCreateCertificateAsync(serverCertificateName, policy);

            RegisterForCleanup(serverCertificateName);
            await using IAsyncDisposable disposableOperation = EnsureDeleted(operation);

            // Read the CA.
            byte[]           caCertificateBytes = Convert.FromBase64String(CaPublicKeyBase64);
            X509Certificate2 caCertificate      = new X509Certificate2(caCertificateBytes);

            // Read CA private key since getting it from caCertificate above throws.
            AsymmetricCipherKeyPair caPrivateKey;

            using (StringReader caPrivateKeyReader = new StringReader(CaPrivateKeyPem))
            {
                PemReader reader = new PemReader(caPrivateKeyReader);
                caPrivateKey = (AsymmetricCipherKeyPair)reader.ReadObject();
            }

            // Read the CSR.
            Pkcs10CertificationRequest csr     = new Pkcs10CertificationRequest(operation.Properties.Csr);
            CertificationRequestInfo   csrInfo = csr.GetCertificationRequestInfo();

            // Parse the issuer subject name.
            Hashtable oidLookup = new Hashtable(X509Name.DefaultLookup)
            {
                { "s", new DerObjectIdentifier("2.5.4.8") },
            };

            X509Name issuerName = new X509Name(true, oidLookup, caCertificate.Subject);

            // Sign the request.
            X509V3CertificateGenerator generator = new X509V3CertificateGenerator();

            generator.SetIssuerDN(issuerName);
            generator.SetSerialNumber(BigInteger.One);
            generator.SetNotBefore(DateTime.Now);
            generator.SetNotAfter(DateTime.Now.AddDays(1));
            generator.SetSubjectDN(csrInfo.Subject);
            generator.SetPublicKey(csr.GetPublicKey());

            Asn1SignatureFactory signatureFactory      = new Asn1SignatureFactory("SHA256WITHRSA", caPrivateKey.Private);
            X509Certificate      serverSignedPublicKey = generator.Generate(signatureFactory);

            // Merge the certificate chain.
            MergeCertificateOptions       options = new MergeCertificateOptions(serverCertificateName, new[] { serverSignedPublicKey.GetEncoded(), caCertificateBytes });
            KeyVaultCertificateWithPolicy mergedServerCertificate = await Client.MergeCertificateAsync(options);

            X509Certificate2 serverCertificate = new X509Certificate2(mergedServerCertificate.Cer);

            Assert.AreEqual(csrInfo.Subject.ToString(), serverCertificate.Subject);
            Assert.AreEqual(serverCertificateName, mergedServerCertificate.Name);

            KeyVaultCertificateWithPolicy completedServerCertificate = await WaitForCompletion(operation);

            Assert.AreEqual(mergedServerCertificate.Name, completedServerCertificate.Name);
            CollectionAssert.AreEqual(mergedServerCertificate.Cer, completedServerCertificate.Cer);
        }
示例#7
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();
        }
示例#8
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());
        }
示例#9
0
 private void GenerationRequestToServerForDotP7B(long iD, int keyStoreType, Pkcs10CertificationRequest certificationRequest)
 {
     new NetworkHandler().PostCertificateGenerationRequest(iD, keyStoreType, certificationRequest);
 }
示例#10
0
        static void Main(string[] args)
        {
            Console.WriteLine("Please select option 1/2");

            string option = Console.ReadLine();

            if (option == "1")
            {
                Certificate cert = new Certificate(2048);

                Console.WriteLine("---------------------------- AS2805.6.5.3 Option 1--------------------------------------------------------");



                Console.WriteLine("---------------Manufacturer’s key pair (PKman, SKman)---------------");
                Certificate man   = new Certificate(2048);
                byte[]      PKman = man.GetPublicKey();
                byte[]      SKman = man.GetPrivateKey();


                Console.WriteLine("------------------Terminal cryptographic unit’s key pair (PKtcu, SKtcu)-------------------");
                Certificate tcu   = new Certificate(2048);
                byte[]      PKtcu = tcu.GetPublicKey();
                byte[]      SKtcu = tcu.GetPrivateKey();

                Console.WriteLine("----------------Sponsor’s key pair (PKsp, SKsp)------------------------");
                Certificate sp   = new Certificate(2048);
                byte[]      PKsp = sp.GetPublicKey();
                byte[]      SKsp = sp.GetPrivateKey();

                Console.WriteLine("--------------Getting RNsp, tcuid and user data -------------- ");
                Random rnd        = new Random();
                string RNsp       = rnd.Next(222222, 999999).ToString();
                byte[] RNsp_bytes = Encoding.ASCII.GetBytes(RNsp);
                Console.WriteLine("RNsp: \t" + RNsp);

                string user_data       = "OPTIONAL USER DATA THAT CAN BE ANY LENGTH";
                byte[] user_data_bytes = Encoding.ASCII.GetBytes(user_data);
                Console.WriteLine("User Data: \t" + user_data);

                string tcuid       = "MN044712H";
                byte[] tcuid_bytes = Encoding.ASCII.GetBytes(tcuid);
                Console.WriteLine("TCUID: \t" + tcuid);


                string AIIC       = "0000045127823121";
                byte[] AIIC_bytes = Encoding.ASCII.GetBytes(AIIC);
                Console.WriteLine("AIIC: \t" + AIIC);


                SecureRandom       random = new SecureRandom();
                DesEdeKeyGenerator keyGen = new DesEdeKeyGenerator();
                keyGen.Init(new KeyGenerationParameters(random, 128));

                byte[] KI_bytes = keyGen.GenerateKey();
                string KI       = BitConverter.ToString(KI_bytes).Replace("-", string.Empty);
                Console.WriteLine("KI: \t" + KI);


                byte[] KIA_bytes = keyGen.GenerateKey();

                string KIA = BitConverter.ToString(KIA_bytes).Replace("-", string.Empty);
                Console.WriteLine("KIA: \t" + KIA);



                byte[] KCA_bytes = keyGen.GenerateKey();
                string KCA       = BitConverter.ToString(KCA_bytes).Replace("-", string.Empty);
                Console.WriteLine("KCA: \t" + KCA);

                DateTime today       = DateTime.Now.Date;
                byte[]   today_bytes = Encoding.ASCII.GetBytes(today.ToString("yyyyMMdd HH:mm:ss"));
                Console.WriteLine("DTS: \t" + today.ToString("yyyyMMdd HH:mm:ss"));



                Console.WriteLine("-----------------------------------------------------------------------");


                Console.WriteLine("--------------------------Sponsor Pre-Compute--------------------------");
                HashMAC hash             = new HashMAC(new Sha256Digest());
                byte[]  H_PKman_userdata = hash.Hash_Data(PKman.Concat(user_data_bytes).ToArray());
                Console.WriteLine("SHA256 Hash of PKman + user data : \n" + Utils.HexDump(H_PKman_userdata));

                byte[] H_PKsp_RNsp_userdata = hash.Hash_Data(PKsp.Concat(RNsp_bytes).Concat(user_data_bytes).ToArray());
                //Console.WriteLine("SHA256 Hash of PKsp + user data : \n" + Utils.HexDump(H_PKman_userdata));

                Console.WriteLine("----------------------------------------------------------------------------------");
                Signature sign = new Signature();
                byte[]    sSKman_H_PKman_userdata = sign.SignData(H_PKman_userdata, man.get_Private_Params());
                Console.WriteLine("Sponsor Verifies Manufacturer Signature of sSKman(H(PKman + user data)) : \n" + Utils.HexDump(sSKman_H_PKman_userdata));


                byte[] sSKman_H_PKsp_RNsp_userdata = sign.SignData(H_PKsp_RNsp_userdata, man.get_Private_Params());
                //Console.WriteLine("Signature of sSKman(H(PKsp + user data)) : \n" + Utils.HexDump(sSKman_H_PKsp_userdata));

                byte[] H_PKsp = hash.Hash_Data(PKsp);
                //Console.WriteLine("SHA256 Hash of PKsp : \n" + Utils.HexDump(H_PKsp));

                byte[] sSKman_H_PKsp = sign.SignData(H_PKsp, man.get_Private_Params());
                //Console.WriteLine("Signature of sSKman(H(PKsp))) : \n" + Utils.HexDump(sSKman_H_PKsp));

                //Console.WriteLine("--------------------------TCU Pre-Compute--------------------------");


                byte[] H_PKtcu = hash.Hash_Data(PKtcu);
                //Console.WriteLine("SHA256 Hash of PKtcu : \n" + Utils.HexDump(H_PKtcu));

                //Pad pad = new Pad();
                //var padHash = pad.Pad_Data(H_PKtcu, 128);
                //Console.WriteLine("SHA256 Hash of PKtcu and PKCS v1.5 padding : \n" + Utils.HexDump(padHash));
                Console.WriteLine("----------------------------------------------------------------------------------");
                byte[] sSKman_H_PKtcu_ = sign.SignData(H_PKtcu, man.get_Private_Params());
                Console.WriteLine("Termninal Verifies Manufacturer Signature of PKtcu sSKman(H(PKtcu)) :\n" + Utils.HexDump(sSKman_H_PKtcu_));
                Console.WriteLine("----------------------------------------------------------------------------------");

                byte[] sSKman_H_PKtcu_TCUID_userdata = sign.SignData(H_PKtcu.Concat(tcuid_bytes).Concat(user_data_bytes).ToArray(), man.get_Private_Params());
                //Console.WriteLine("Signature of sSKman(H(PKtcu)|TCUID|user data) : \n" + Utils.HexDump(sSKman_H_PKtcu));
                //Console.ReadLine();


                Console.WriteLine("-------------------------- OPTION 1 --------------------------");


                Console.WriteLine("--------------------------SIGN ON REQUEST 1--------------------------\n\n");
                Console.WriteLine("----------------------------------------------------------------------------------");
                Console.WriteLine("TCU -> Sending:...");
                Console.WriteLine("----------------------------------------------------------------------------------");
                Console.WriteLine("User Data: " + user_data + "\n" + Utils.HexDump(user_data_bytes));
                Console.WriteLine("----------------------------------------------------------------------------------");
                Console.WriteLine("TCUID: " + tcuid + " \n" + Utils.HexDump(tcuid_bytes));
                Console.WriteLine("----------------------------------------------------------------------------------");
                Console.WriteLine("H(PKtcu) \n" + Utils.HexDump(H_PKtcu));
                Console.WriteLine("----------------------------------------------------------------------------------");
                Console.WriteLine("sSKman(H(PKtcu)|TCUID|user data) \n" + Utils.HexDump(sSKman_H_PKtcu_TCUID_userdata));
                Console.WriteLine("----------------------------------------------------------------------------------");
                Console.WriteLine("------------------------SIGN ON RESPONSE 1--------------------------------------");
                Console.WriteLine("Veryfying Signature of sSKman(H(PKtcu)|TCUID|user data)");
                Console.WriteLine("----------------------------------------------------------------------------------");
                Console.WriteLine("User Data: " + user_data + "\n" + Utils.HexDump(user_data_bytes));
                Console.WriteLine("----------------------------------------------------------------------------------");
                Console.WriteLine("RNsp: " + RNsp + "\n" + Utils.HexDump(RNsp_bytes));
                Console.WriteLine("----------------------------------------------------------------------------------");
                Console.WriteLine("H(PKsp|RNsp|userdata) \n" + Utils.HexDump(H_PKsp_RNsp_userdata));
                Console.WriteLine("----------------------------------------------------------------------------------");
                Console.WriteLine("Sign: sSKman(H(PKsp|RNsp|user data)):\n" + Utils.HexDump(sSKman_H_PKsp_RNsp_userdata));
                Console.WriteLine("----------------------------------------------------------------------------------");
                Console.WriteLine("-------------------------- SIGN ON REQUEST 2--------------------------\n\n");
                //Construct cryptogram encrypted by PKsp
                Console.WriteLine("Constructing the KI KeyBlock cryptogram (KI, TCUID, RNsp, DTS, user dat)----------");
                Asn1 asn = new Asn1();

                byte[] KI_KeyBlock_bytes = asn.KI_KeyBlock(KI_bytes, tcuid_bytes, today_bytes, RNsp_bytes, user_data_bytes);
                Console.WriteLine("----------------------------------------------------------------------------------");
                Console.WriteLine(Utils.HexDump(KI_KeyBlock_bytes));
                Console.WriteLine("----------------------------------------------------------------------------------");
                Console.WriteLine("Encrypt: ePKsp(KI, TCUID, RNsp, DTS, user data): \n");
                byte[] PKsp_KI_TCUID_RNsp_DTS_user_data = sp.Encrypt(KI_KeyBlock_bytes);
                Console.WriteLine(Utils.HexDump(PKsp_KI_TCUID_RNsp_DTS_user_data));
                Console.WriteLine("----------------------------------------------------------------------------------");
                Console.WriteLine("Hash: H(ePKsp(KI, TCUID, RNsp, DTS, user data)): \n");
                byte[] H_PKsp_KI_TCUID_RNsp_DTS_user_data = hash.Hash_Data(PKsp_KI_TCUID_RNsp_DTS_user_data);
                Console.WriteLine(Utils.HexDump(H_PKsp_KI_TCUID_RNsp_DTS_user_data));
                Console.WriteLine("----------------------------------------------------------------------------------");
                Console.WriteLine("Sign: sSKtcu(H(ePKsp(KI, TCUID, RNsp, DTS, user data))): \n");
                byte[] sSKtcu_H_PKsp_KI_TCUID_RNsp_DTS_user_data = sign.SignData(H_PKsp_KI_TCUID_RNsp_DTS_user_data, tcu.get_Private_Params());
                Console.WriteLine(Utils.HexDump(sSKtcu_H_PKsp_KI_TCUID_RNsp_DTS_user_data));
                Console.WriteLine("----------------------------------------------------------------------------------");
                Console.WriteLine("Send Signature and Encryption to Sponsor so that KI can be extracted \n");
                Console.WriteLine("----------------------------------------------------------------------------------");
                Console.WriteLine("Verify: sSKtcu(H(ePKsp(KI, TCUID, RNsp, DTS, user data))): \n");
                bool sSKtcuV = sign.VerifySignature(tcu.get_Public_Params(), sSKtcu_H_PKsp_KI_TCUID_RNsp_DTS_user_data, H_PKsp_KI_TCUID_RNsp_DTS_user_data);
                Console.WriteLine("Verified: " + sSKtcuV);
                Console.WriteLine("----------------------------------------------------------------------------------");
                Console.WriteLine("Decrypt: ePKsp(KI, TCUID, RNsp, DTS, user data): \n");
                Console.WriteLine("Decrypted:\n" + Utils.HexDump(sp.Decrypt(PKsp_KI_TCUID_RNsp_DTS_user_data)));
                Console.WriteLine("----------------------------------------------------------------------------------\n\n");

                Console.WriteLine("--------------------------  SIGN ON RESPONSE 2-------------------------\n\n");

                /*
                 * The KCA shall be used to derive a unique KIA_n per acquirer. The sponsor shall be responsible for providing the KIA_n to each acquirer through a secure channel.
                 * Each acquirer shall use its unique KIAn to download or derive the initial key(s) required for the appropriate key management scheme
                 *
                 *
                 * The AIIC is right justified and left zero filled in a 128-bit data field.
                 *  KMACI_n = (OWF(KIA_n,D))
                 *  KCA =
                 */
                DESAES desaes = new DESAES();


                Console.WriteLine("-------------------------Calculate KMACI_n = HMAC(KIA_n,AIIC) -------------------------\n");
                Console.WriteLine("-------------------------OWF = SHA256 HMAC -------------------------");
                byte[] H_KIA_n_AIIC = hash.HMAC(AIIC_bytes, KIA_bytes);
                Console.WriteLine("KMAC = \n" + Utils.HexDump(H_KIA_n_AIIC));
                Console.WriteLine("----------------------------------------------------------------------------------");
                Console.WriteLine("KCA = \n" + Utils.HexDump(KCA_bytes));
                Console.WriteLine("------------------------------ENCRYPT---------------------------------------------");
                var E_KMAC = desaes.EncryptDES3(H_KIA_n_AIIC, KI_bytes);
                Console.WriteLine("e(KMAC) = \n" + Utils.HexDump(E_KMAC));
                Console.WriteLine("----------------------------------------------------------------------------------");
                var E_KCA = desaes.EncryptDES3(KCA_bytes, KI_bytes);
                Console.WriteLine("e(KCA) = \n" + Utils.HexDump(E_KCA));
                Console.WriteLine("----------------------------------------------------------------------------------");
                Console.WriteLine("------------------------------DECRYPT---------------------------------------------");
                var D_KCA = desaes.DecryptDES3(E_KCA, KI_bytes);
                Console.WriteLine("d(KCA) = \n" + Utils.HexDump(D_KCA));
                Console.WriteLine("----------------------------------------------------------------------------------");
                var D_KMAC = desaes.DecryptDES3(E_KMAC, KI_bytes);
                Console.WriteLine("d(KMAC) = \n" + Utils.HexDump(D_KMAC));
                Console.WriteLine("----------------------------------------------------------------------------------");
                Console.WriteLine("**------------------------------DONE--------------------------------------------**");
            }
            else
            {
                bool ForEncryption = true;

                //Requested Certificate Name and things
                X509Name name = new X509Name("C=Commonwealth Bank of Australia, O=CBA, OU=Cryptographical Services, CN=TID25124548");



                //Key generation 2048bits
                var rkpg = new RsaKeyPairGenerator();
                rkpg.Init(new KeyGenerationParameters(new SecureRandom(), 2048));
                AsymmetricCipherKeyPair ackp = rkpg.GenerateKeyPair(); //BAPI.EncryptionKey;
                                                                       //if (!ForEncryption) ackp = BAPI.SignKey;

                //Key Usage Extension
                var ku     = new KeyUsage(ForEncryption ? KeyUsage.KeyEncipherment : KeyUsage.DigitalSignature);
                var extgen = new Org.BouncyCastle.Asn1.X509.X509ExtensionsGenerator();
                extgen.AddExtension(X509Extensions.KeyUsage, true, ku);
                var attribute = new AttributeX509(PkcsObjectIdentifiers.Pkcs9AtExtensionRequest, new DerSet(extgen.Generate()));

                //PKCS #10 Certificate Signing Request
                Pkcs10CertificationRequest csr = new Pkcs10CertificationRequest("SHA1WITHRSA", name, ackp.Public, new DerSet(attribute), ackp.Private); //new DerSet(new DerOctetString(ku))

                var csrbytedata = csr.GetDerEncoded();

                var asn1Csr = csr.ToAsn1Object();
                //////
                Console.WriteLine(asn1Csr.GetDerEncoded().ToString());
                Console.WriteLine(Utils.HexDump(csrbytedata));
                string pwd       = "password";
                var    suppliers = new[] { "CN=*.cba.com.au" };

                var CA_issuer = new X509(suppliers, "CN=CBA RootCA, OU=Cryptographical Services, O=Commonwealth Bank of Australia, L=SYDNEY, C=AU", CertStrength.bits_2048);
                X509Certificate2 GeneratedCert = CA_issuer.MakeCertificate(pwd, "CN=TID25124548.cba.com.au, OU=Commonwealth Bank of Australia, OU=CBA Business System Hosting, O=Commonwealth Bank of Australia, C=AU", 2);

                Console.WriteLine(GeneratedCert.ToString());
                Console.WriteLine(Utils.HexDump(GeneratedCert.Export(X509ContentType.Pkcs12, pwd)));

                Console.ReadLine();
            }
        }
示例#11
0
        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");
        }
    }
        public PkiCertificateSigningRequest(PkiEncodingFormat format, byte[] encoded,
                                            PkiHashAlgorithm hashAlgorithm)
        {
            Pkcs10CertificationRequest pkcs10;

            switch (format)
            {
            case PkiEncodingFormat.Pem:
                var encodedString = Encoding.UTF8.GetString(encoded);
                using (var sr = new StringReader(encodedString))
                {
                    var pemReader = new PemReader(sr);
                    pkcs10 = pemReader.ReadObject() as Pkcs10CertificationRequest;
                    if (pkcs10 == null)
                    {
                        throw new Exception("invalid PEM object is not PKCS#10 archive");
                    }
                }
                break;

            case PkiEncodingFormat.Der:
                pkcs10 = new Pkcs10CertificationRequest(encoded);
                break;

            default:
                throw new NotSupportedException();
            }

            var info            = pkcs10.GetCertificationRequestInfo();
            var nativePublicKey = pkcs10.GetPublicKey();
            var rsaKey          = nativePublicKey as RsaKeyParameters;
            var ecdsaKey        = nativePublicKey as ECPublicKeyParameters;

            if (rsaKey != null)
            {
                PublicKey = new PkiKey(nativePublicKey, PkiAsymmetricAlgorithm.Rsa);
            }
            else if (ecdsaKey != null)
            {
                PublicKey = new PkiKey(nativePublicKey, PkiAsymmetricAlgorithm.Ecdsa);
            }
            else
            {
                throw new NotSupportedException("unsupported asymmetric algorithm key");
            }
            SubjectName   = info.Subject.ToString();
            HashAlgorithm = hashAlgorithm;


            // // // Based on:
            // // //    http://forum.rebex.net/4284/pkcs10-certificate-request-example-provided-castle-working

            // // var extGen = new X509ExtensionsGenerator();
            // // foreach (var ext in CertificateExtensions)
            // // {
            // //     extGen.AddExtension(ext.Identifier, ext.IsCritical, ext.Value);
            // // }
            // // var attr = new AttributeX509(PkcsObjectIdentifiers.Pkcs9AtExtensionRequest,
            // //         new DerSet(extGen.Generate()));


            // Based on:
            //    http://unitstep.net/blog/2008/10/27/extracting-x509-extensions-from-a-csr-using-the-bouncy-castle-apis/
            //    https://stackoverflow.com/q/24448909/5428506
            foreach (var attr in info.Attributes.ToArray())
            {
                if (attr is DerSequence derSeq && derSeq.Count == 2)
                {
                    var attrX509 = AttributeX509.GetInstance(attr);
                    if (object.Equals(attrX509.AttrType, PkcsObjectIdentifiers.Pkcs9AtExtensionRequest))
                    {
                        // The `Extension Request` attribute is present.
                        // The X509Extensions are contained as a value of the ASN.1 Set.
                        // Assume that it is the first value of the set.
                        if (attrX509.AttrValues.Count >= 1)
                        {
                            var csrExts = X509Extensions.GetInstance(attrX509.AttrValues[0]);
                            foreach (var extOid in csrExts.GetExtensionOids())
                            {
                                if (object.Equals(extOid, X509Extensions.SubjectAlternativeName))
                                {
                                    var ext    = csrExts.GetExtension(extOid);
                                    var extVal = ext.Value;
                                    var der    = extVal.GetDerEncoded();
                                    // The ext value, which is an ASN.1 Octet String, **MIGHT** be tagged with
                                    // a leading indicator that it's an Octet String and its length, so we want
                                    // to remove it if that's the case to extract the GeneralNames collection
                                    if (der.Length > 2 && der[0] == 4 && der[1] == der.Length - 2)
                                    {
                                        der = der.Skip(2).ToArray();
                                    }
                                    var asn1obj = Asn1Object.FromByteArray(der);
                                    var gnames  = GeneralNames.GetInstance(asn1obj);
                                    CertificateExtensions.Add(new PkiCertificateExtension
                                    {
                                        Identifier = extOid,
                                        IsCritical = ext.IsCritical,
                                        Value      = gnames,
                                    });
                                }
                            }

                            // No need to search any more.
                            break;
                        }
                    }
                }
            }
        }
        /// <summary>
        /// Creates an ASN.1 DER-encoded PKCS#10 CertificationRequest object representing
        /// the current state of this CertificateRequest object.
        /// </summary>
        /// <returns>An ASN.1 DER-encoded certificate signing request.</returns>
        public byte[] ExportSigningRequest(PkiEncodingFormat format)
        {
            if (!HasPrivateKey)
            {
                throw new InvalidOperationException("cannot export CSR without a private key");
            }

            // Based on:
            //    https://github.com/bcgit/bc-csharp/blob/master/crypto/test/src/pkcs/test/PKCS10Test.cs
            //    https://stackoverflow.com/questions/46182659/how-to-delay-sign-the-certificate-request-using-bouncy-castle-with-ecdsa-signatu
            //    http://www.bouncycastle.org/wiki/display/JA1/X.509+Public+Key+Certificate+and+Certification+Request+Generation:
            //        #X.509PublicKeyCertificateandCertificationRequestGeneration-EllipticCurve(ECDSA)
            //        #X.509PublicKeyCertificateandCertificationRequestGeneration-RSA
            //        #X.509PublicKeyCertificateandCertificationRequestGeneration-CreatingCertificationRequests
            //    https://stackoverflow.com/a/37563051/5428506

            var x509name = new X509Name(SubjectName);
            var pubKey   = _keyPair.PublicKey.NativeKey;
            var prvKey   = _keyPair.PrivateKey.NativeKey;

            // Asn1Set attrSet = null;
            // if (CertificateExtensions.Count > 0)
            // {
            //     var certExts = CertificateExtensions.ToDictionary(
            //             ext => ext.Identifier, ext => ext.Value);
            //     var csrAttrs = new[]
            //     {
            //         new Org.BouncyCastle.Asn1.Cms.Attribute(
            //             PkcsObjectIdentifiers.Pkcs9AtExtensionRequest,
            //             new DerSet(new X509Extensions(certExts))),
            //     };
            //     attrSet = new DerSet(csrAttrs);
            // }

            // Based on:
            //    http://forum.rebex.net/4284/pkcs10-certificate-request-example-provided-castle-working

            var extGen = new X509ExtensionsGenerator();

            foreach (var ext in CertificateExtensions)
            {
                extGen.AddExtension(ext.Identifier, ext.IsCritical, ext.Value);
            }
            var attr = new AttributeX509(PkcsObjectIdentifiers.Pkcs9AtExtensionRequest,
                                         new DerSet(extGen.Generate()));

            var sigFactory = ComputeSignatureAlgorithm(prvKey);
            var pkcs10     = new Pkcs10CertificationRequest(sigFactory, x509name,
                                                            pubKey, new DerSet(attr));

            switch (format)
            {
            case PkiEncodingFormat.Pem:
                using (var sw = new StringWriter())
                {
                    var pemWriter = new PemWriter(sw);
                    pemWriter.WriteObject(pkcs10);
                    return(Encoding.UTF8.GetBytes(sw.GetStringBuilder().ToString()));
                }

            case PkiEncodingFormat.Der:
                return(pkcs10.GetDerEncoded());

            default:
                throw new NotSupportedException();
            }
        }
        /// <summary>
        /// Create a CSR and submit it to the Acme server for signing. Returns the certificate chain.
        /// </summary>
        /// <param name="domains">The list of domains that this certificate will be for. The first domain listed will be the CommonName.</param>
        /// <param name="keyPair">The RSA key pair for signing the certificate request, this is the key that will be used in conjunction with the certificate.</param>
        /// <returns>A tuple whose first value is the private key data and whose second value is a list of certificates. Everything is encoded in DER format, the first certificate is the signed certificate.</returns>
        public Tuple <byte[], List <byte[]> > GetCertificate(ICollection <string> domains)
        {
            //
            // Generate a new key for the certificate.
            //
            var generator = new RsaKeyPairGenerator();

            generator.Init(new KeyGenerationParameters(new SecureRandom(), 2048));
            var keyPair = generator.GenerateKeyPair();
            var sig     = new Asn1SignatureFactory("SHA256WITHRSA", keyPair.Private);

            var commonName = new X509Name(new DerObjectIdentifier[] { X509Name.CN }, new string[] { domains.First() });

            //
            // Generate the list of subject alternative names.
            //
            List <GeneralName> names = new List <GeneralName>();

            foreach (var domain in domains)
            {
                names.Add(new GeneralName(GeneralName.DnsName, domain));
            }
            var sanOctect    = new DerOctetString(new GeneralNames(names.ToArray()));
            var sanSequence  = new DerSequence(X509Extensions.SubjectAlternativeName, sanOctect);
            var extensionSet = new DerSet(new DerSequence(sanSequence));
            var attributes   = new DerSet(new DerSequence(PkcsObjectIdentifiers.Pkcs9AtExtensionRequest, extensionSet));

            //
            // Generate the CSR from all the data.
            //
            var csr = new Pkcs10CertificationRequest(sig, commonName, keyPair.Public, attributes, keyPair.Private);

            var payload = new
            {
                resource = "new-cert",
                csr      = UrlBase64Encode(csr.GetDerEncoded())
            };

            var certificates = new List <X509Certificate>();
            var certParser   = new X509CertificateParser();

            byte[] certData;

            //
            // Send the request and fetch the certificate data.
            //
            certData = SendMessage <byte[]>(Directory.NewCert, payload, GetNonce(), out WebHeaderCollection headers);
            certificates.Add(certParser.ReadCertificate(certData));

            //
            // Fetch all the certificates in the chain.
            //
            foreach (var link in headers.GetValues("Link"))
            {
                var match = System.Text.RegularExpressions.Regex.Match(link, "\\<(.*)\\>;rel=\"(.*)\"");
                if (match.Success && match.Groups[2].Value == "up")
                {
                    certData = GetRequest <byte[]>(match.Groups[1].Value);
                    certificates.Add(certParser.ReadCertificate(certData));
                }
            }

            var privateKeyData  = PrivateKeyInfoFactory.CreatePrivateKeyInfo(keyPair.Private).ToAsn1Object().GetDerEncoded();
            var certificateData = certificates.Select(c => c.GetEncoded()).ToList();

            return(new Tuple <byte[], List <byte[]> >(privateKeyData, certificateData));
        }
示例#15
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);
        }
示例#16
0
        public void PostCertificateGenerationRequest(long enrollmentID, int keyStoreType, Pkcs10CertificationRequest certificationSigningRequest)
        {
            PemObject    pemObject = new PemObject("CERTIFICATE REQUEST", certificationSigningRequest.GetEncoded());
            StringWriter str       = new StringWriter();
            PemWriter    pemWriter = new PemWriter(str);

            pemWriter.WriteObject(pemObject);
            String csr = str.ToString();

            str.Close();
            String URL = requestProtocol + Constants.BASE_URL + "/" + Constants.PartialUrlOfApi.CRS + "?"
                         + "csr=" + WebUtility.UrlEncode(csr) + "&serialNo=" + enrollmentID + "&keystoreType="
                         + keyStoreType + "&mode=csr";;

            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(URL);

            request.Method      = "POST";
            request.ContentType = "application/x-www-form-urlencoded; charset=utf-8";

            HttpWebResponse response     = (HttpWebResponse)request.GetResponse();
            Stream          stream       = response.GetResponseStream();
            StreamReader    streamReader = new StreamReader(stream);

            Console.WriteLine(streamReader.ReadToEnd());

            System.Threading.Thread.Sleep(3000);
        }
示例#17
0
        public override Csr GenerateCsr(CsrParams csrParams, PrivateKey pk, Crt.MessageDigest md)
        {
            var csrDetails = csrParams.Details;
            var mdVal      = Enum.GetName(typeof(Crt.MessageDigest), md);

            var attrs = new Dictionary <DerObjectIdentifier, string>();

            if (!string.IsNullOrEmpty(csrDetails.CommonName /**/))
            {
                attrs.Add(X509Name.CN, csrDetails.CommonName);                                                                  // CN;
            }
            if (!string.IsNullOrEmpty(csrDetails.Country /**/))
            {
                attrs.Add(X509Name.C, csrDetails.Country);                                                                      // C;
            }
            if (!string.IsNullOrEmpty(csrDetails.StateOrProvince /**/))
            {
                attrs.Add(X509Name.ST, csrDetails.StateOrProvince);                                                             // ST;
            }
            if (!string.IsNullOrEmpty(csrDetails.Locality /**/))
            {
                attrs.Add(X509Name.L, csrDetails.Locality);                                                                     // L;
            }
            if (!string.IsNullOrEmpty(csrDetails.Organization /**/))
            {
                attrs.Add(X509Name.O, csrDetails.Organization);                                                                 // O;
            }
            if (!string.IsNullOrEmpty(csrDetails.OrganizationUnit /**/))
            {
                attrs.Add(X509Name.OU, csrDetails.OrganizationUnit);                                                            // OU;
            }
            if (!string.IsNullOrEmpty(csrDetails.Surname /**/))
            {
                attrs.Add(X509Name.Surname, csrDetails.Surname);                                                                // S;
            }
            if (!string.IsNullOrEmpty(csrDetails.GivenName /**/))
            {
                attrs.Add(X509Name.GivenName, csrDetails.GivenName);                                                            // G;
            }
            if (!string.IsNullOrEmpty(csrDetails.Initials /**/))
            {
                attrs.Add(X509Name.Initials, csrDetails.Initials);                                                              // I;
            }
            if (!string.IsNullOrEmpty(csrDetails.Title /**/))
            {
                attrs.Add(X509Name.T, csrDetails.Title);                                                                                      // T;
            }
            if (!string.IsNullOrEmpty(csrDetails.SerialNumber /**/))
            {
                attrs.Add(X509Name.SerialNumber, csrDetails.SerialNumber);                                                                    // SN;
            }
            if (!string.IsNullOrEmpty(csrDetails.UniqueIdentifier /**/))
            {
                attrs.Add(X509Name.UniqueIdentifier, csrDetails.UniqueIdentifier);                                                            // UID;
            }
            var subj = new X509Name(attrs.Keys.ToList(), attrs.Values.ToList());

            var rsaPk = pk as RsaPrivateKey;

            if (rsaPk != null)
            {
                using (var tr = new StringReader(rsaPk.Pem))
                {
                    var pr   = new PemReader(tr);
                    var pem  = pr.ReadObject();
                    var ackp = pem as AsymmetricCipherKeyPair;

                    if (ackp != null)
                    {
                        var sigAlg   = $"{mdVal}withRSA";
                        var csrAttrs = new List <Asn1Encodable>();

                        if (csrDetails.AlternativeNames != null)
                        {
                            var gnames = new List <GeneralName>();

                            // Start off with the common name as the first alternative name
                            gnames.Add(new GeneralName(GeneralName.DnsName, csrDetails.CommonName));
                            // Combine with all subsequent alt names
                            foreach (var n in csrDetails.AlternativeNames)
                            {
                                gnames.Add(new GeneralName(GeneralName.DnsName, n));
                            }

                            var altNames = new GeneralNames(gnames.ToArray());
#pragma warning disable CS0612 // Type or member is obsolete
                            var x509Ext = new X509Extensions(new Hashtable
                            {
                                [X509Extensions.SubjectAlternativeName] = new X509Extension(false, new DerOctetString(altNames))
                            });
#pragma warning restore CS0612 // Type or member is obsolete

                            csrAttrs.Add(new Org.BouncyCastle.Asn1.Cms.Attribute(
                                             PkcsObjectIdentifiers.Pkcs9AtExtensionRequest,
                                             new DerSet(x509Ext)));
                        }

#pragma warning disable CS0618 // Type or member is obsolete
                        var csr = new Pkcs10CertificationRequest(sigAlg,
                                                                 subj, ackp.Public, new DerSet(csrAttrs.ToArray()), ackp.Private);
#pragma warning restore CS0618 // Type or member is obsolete

                        var csrPem = ToCsrPem(csr);
                        return(new Csr(csrPem));
                    }
                }
            }

            throw new NotSupportedException("unsupported private key type");
        }
示例#18
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");
            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.");
            }
        }
示例#19
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
        }
示例#20
0
        /// <summary>
        /// Create an OSCA Profile using a PKCS#10 Certificate Request
        /// </summary>
        /// <param name="Request">PKCS#10 Certificate Request</param>
        /// <returns></returns>
        public static Profile FromPkcs10Request(Pkcs10CertificationRequest Request)
        {
            Pkcs10Parser parser = new Pkcs10Parser(Request);

            return(new Profile(parser.Extensions));
        }
示例#21
0
        /// <summary>
        /// Enroll certificate file base on request
        /// </summary>
        /// <param name="csr"></param>
        /// <param name="rootCert"></param>
        /// <param name="issuerKeyPair"></param>
        /// <param name="startDate"></param>
        /// <param name="endDate"></param>
        /// <returns></returns>
        private Org.BouncyCastle.X509.X509Certificate GenerateSignedCertificate(
            Pkcs10CertificationRequest csr,
            Org.BouncyCastle.X509.X509Certificate rootCert,
            AsymmetricCipherKeyPair issuerKeyPair,
            DateTime startDate, DateTime endDate)
        {
            X509V3CertificateGenerator certGen = new X509V3CertificateGenerator();

            //List<ExtensionsItem> extensions = null;

            certGen.SetSerialNumber(BigInteger.One);

            certGen.SetIssuerDN(rootCert.SubjectDN);

            certGen.SetNotBefore(startDate);
            certGen.SetNotAfter(endDate);

            CertificationRequestInfo info = csr.GetCertificationRequestInfo();

            certGen.SetSubjectDN(info.Subject);

            certGen.SetPublicKey(csr.GetPublicKey());

            var sigAlg  = csr.Signature;
            var sigAlg1 = csr.SignatureAlgorithm;

            certGen.SetSignatureAlgorithm("SHA1WithRSAEncryption");


            // Add certificate extensions
            Asn1Set attributes = csr.GetCertificationRequestInfo().Attributes;

            if (attributes != null)
            {
                for (int i = 0; i != attributes.Count; i++)
                {
                    AttributePkcs attr = AttributePkcs.GetInstance(attributes[i]);

                    if (attr.AttrType.Equals(PkcsObjectIdentifiers.Pkcs9AtExtensionRequest))
                    {
                        X509Extensions extensions1 = X509Extensions.GetInstance(attr.AttrValues[0]);

                        foreach (DerObjectIdentifier oid in extensions1.ExtensionOids)
                        {
                            Org.BouncyCastle.Asn1.X509.X509Extension ext = extensions1.GetExtension(oid);

                            // !!! NOT working !!!
                            //certGen.AddExtension(oid, ext.IsCritical, ext.Value);

                            //OK
                            certGen.AddExtension(oid, ext.IsCritical, ext.Value, true);
                        }
                    }
                }
            }

            Org.BouncyCastle.X509.X509Certificate issuedCert = null;
            try
            {
                issuedCert = certGen.Generate(issuerKeyPair.Private);
                tbOutputMessageBox.Text += "Certificate file sucessfully generated." + "\n";
            }
            catch (Exception ex)
            {
                Brush bckForeground = tbOutputMessageBox.Foreground;
                tbOutputMessageBox.Foreground = new SolidColorBrush(Colors.Red);
                tbOutputMessageBox.Text      += "Error, generate certificate file." + "\n" + "ERROR: " + ex.GetHashCode().ToString() + " " + ex.Message + "\n";
                tbOutputMessageBox.Foreground = bckForeground;
            }

            try
            {
                tbOutputMessageBox.Text += "Check if generated certificate file is valid, plase wait ..." + "\n";
                issuedCert.CheckValidity(DateTime.UtcNow);
                tbOutputMessageBox.Text += "Generate certificate file is valid." + "\n";
            }
            catch (Exception ex)
            {
                Brush bckForeground = tbOutputMessageBox.Foreground;
                tbOutputMessageBox.Foreground = new SolidColorBrush(Colors.Red);
                tbOutputMessageBox.Text      += "Error, generated certificate file is INVALID." + "\n" + "ERROR: " + ex.GetHashCode().ToString() + " " + ex.Message + "\n";
                tbOutputMessageBox.Foreground = bckForeground;
            }

            try
            {
                tbOutputMessageBox.Text += "Verify generated certificate file, plase wait ..." + "\n";
                issuedCert.Verify(issuerKeyPair.Public);
                tbOutputMessageBox.Text += "Generate certificate file verification is OK." + "\n";
            }
            catch (Exception ex)
            {
                Brush bckForeground = tbOutputMessageBox.Foreground;
                tbOutputMessageBox.Foreground = new SolidColorBrush(Colors.Red);
                tbOutputMessageBox.Text      += "Error, generated certificate file verification is INVALID." + "\n" + "ERROR: " + ex.GetHashCode().ToString() + " " + ex.Message + "\n";
                tbOutputMessageBox.Foreground = bckForeground;
            }
            return(issuedCert);
        }
        /*
         * 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.");
            }
        }
        /// <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());
            }
        }
 public CertificateSigningRequestBC(Stream stream)
 {
     m_Request = new Pkcs10CertificationRequest(new Asn1InputStream(stream).ReadObject() as Asn1Sequence);
 }
示例#25
0
        /// <summary>
        /// Builds the CSR depending on the parameters provided.
        /// </summary>
        /// <returns>CSR data.</returns>
        public CSR GenerateCSR()
        {
            // Generating Random Numbers
            var randomGenerator = new CryptoApiRandomGenerator();
            var random          = new SecureRandom(randomGenerator);

            // The Certificate Generator
            var certificateGenerator = new X509V3CertificateGenerator();

            // Serial Number
            var serialNumber = BigIntegers.CreateRandomInRange(BigInteger.One, BigInteger.ValueOf(long.MaxValue), random);

            certificateGenerator.SetSerialNumber(serialNumber);

            // Signature Algorithm
            if (_signatureAlgorithm < 0 || (int)_signatureAlgorithm >= PKCS15SignatureAlgorithmList.Length)
            {
                _signatureAlgorithm = PKCS15SignatureAlgorithm.SHA256WITHRSA;
            }

            // Issuer and Subject Name
            if (_DistinguishedName == null)
            {
                certificateGenerator.SetIssuerDN(new X509Name(_subjectName));
                certificateGenerator.SetSubjectDN(new X509Name(_subjectName));
            }
            else
            {
                certificateGenerator.SetIssuerDN(DistinguishedNamesToX509Name(_DistinguishedName));
                certificateGenerator.SetSubjectDN(DistinguishedNamesToX509Name(_DistinguishedName));
            }

            // Add SAN extension
            if (_SubjectAlternativeName != null)
            {
                certificateGenerator.AddExtension
                (
                    X509Extensions.SubjectAlternativeName,
                    false,
                    SubjectAlternativeNamesToGeneralNames(_SubjectAlternativeName)
                );
            }

            // Basic Constraints - certificate is not allowed to be used as intermediate.
            certificateGenerator.AddExtension(
                X509Extensions.BasicConstraints.Id, true, new BasicConstraints(false));

            // Key intended purpose constrain
            if (_keyPurpose.Length > 0)
            {
                ArrayList kpList = new ArrayList();
                for (int i = 0; i < _keyPurpose.Length; i++)
                {
                    kpList.Add(new DerObjectIdentifier(_keyPurpose[i]));
                }
                IEnumerable kp = kpList;
                certificateGenerator.AddExtension(
                    X509Extensions.ExtendedKeyUsage.Id,
                    _criticalKeyPurpose,
                    new ExtendedKeyUsage(kp)
                    );
            }

            // Key usage
            if (_keyUsage > 0)
            {
                certificateGenerator.AddExtension(
                    X509Extensions.KeyUsage.Id,
                    _criticalKeyUsage,
                    new KeyUsage(_keyUsage)
                    );
            }

            // Valid For
            certificateGenerator.SetNotBefore(_notBefore ?? DateTime.UtcNow.Date);
            certificateGenerator.SetNotAfter(_notAfter ?? DateTime.UtcNow.Date.AddYears(2));

            // Subject Public Key
            var keyGenerationParameters = new KeyGenerationParameters(random, _keyStrength);
            var keyPairGenerator        = new RsaKeyPairGenerator();

            keyPairGenerator.Init(keyGenerationParameters);

            var subjectKeyPair = keyPairGenerator.GenerateKeyPair();
            var issuerKeyPair  = _issuerPrivateKey == null
                ? subjectKeyPair
                : DotNetUtilities.GetKeyPair(_issuerPrivateKey);

            certificateGenerator.SetPublicKey(subjectKeyPair.Public);

            //Generate CSR
            ISignatureFactory          signatureFactory     = new Asn1SignatureFactory(PKCS15SignatureAlgorithmList[(int)_signatureAlgorithm], issuerKeyPair.Private, random);
            Pkcs10CertificationRequest certificationRequest = null;

            if (_DistinguishedName == null)
            {
                certificationRequest = new Pkcs10CertificationRequest(signatureFactory, new X509Name(_subjectName), subjectKeyPair.Public, null);
            }
            else
            {
                certificationRequest = new Pkcs10CertificationRequest(signatureFactory, DistinguishedNamesToX509Name(_DistinguishedName), subjectKeyPair.Public, null);
            }
            var certificate = certificateGenerator.Generate(signatureFactory);

            //Build the CSR
            StringBuilder csrStrBuilder = new StringBuilder();
            PemWriter     csrPemWriter  = new PemWriter(new StringWriter(csrStrBuilder));

            csrPemWriter.WriteObject(certificationRequest);
            csrPemWriter.Writer.Flush();

            CSR csrResult = new CSR();

            csrResult.CSRPEM = csrStrBuilder.ToString();

            //Merge the private key into X509Certificate2
            X509Certificate2 privateKey;

            if (_friendlyName != null)
            {
                privateKey = new X509Certificate2(certificate.GetEncoded())
                {
                    PrivateKey   = ConvertToRsaPrivateKey(subjectKeyPair),
                    FriendlyName = _friendlyName
                };
            }
            else
            {
                privateKey = new X509Certificate2(certificate.GetEncoded())
                {
                    PrivateKey = ConvertToRsaPrivateKey(subjectKeyPair)
                };
            }
            csrResult.PrivateKey = privateKey;

            return(csrResult);
        }
示例#26
0
 /// <summary>
 /// Create a PKCS#10 Parser using a PEM object
 /// </summary>
 /// <param name="Request">PEM object containing request</param>
 /// <exception cref="SignatureException">POP test failed</exception>
 public Pkcs10Parser(PemObject Request)
 {
     this.request = new Pkcs10CertificationRequest(Request.Content);
     readRequest();
 }
        protected override void CompleteWizard()
        {
            // Generate the CSR
            X509Name subjectName =
                new X509Name(string.Format("C={0},ST={1},L={2},O={3},OU={4},CN={5}",
                                           _wizardData.Country,
                                           _wizardData.State,
                                           _wizardData.City,
                                           _wizardData.Organization,
                                           _wizardData.Unit,
                                           _wizardData.CommonName));

            // Generate the private/public keypair
            RsaKeyPairGenerator      kpgen           = new RsaKeyPairGenerator();
            CryptoApiRandomGenerator randomGenerator = new CryptoApiRandomGenerator();

            kpgen.Init(new KeyGenerationParameters(new SecureRandom(randomGenerator), _wizardData.Length));
            AsymmetricCipherKeyPair keyPair = kpgen.GenerateKeyPair();
            // Generate the CSR

            Asn1Set attributes = new DerSet(
                new DerSequence(
                    new DerObjectIdentifier("1.3.6.1.4.1.311.13.2.3"),
                    new DerSet(new DerIA5String(Environment.OSVersion.Version.ToString()))),
                new DerSequence(
                    new DerObjectIdentifier("1.3.6.1.4.1.311.21.20"),
                    new DerSet(
                        new DerSequence(
                            new DerInteger(5),
                            new DerUtf8String(Environment.MachineName),
                            new DerUtf8String(Environment.UserName),
                            new DerUtf8String("JexusManager.exe")))),
                new DerSequence(
                    new DerObjectIdentifier("1.3.6.1.4.1.311.13.2.2"),
                    new DerSet(
                        new DerSequence(
                            new DerInteger(1),
                            new DerBmpString("Microsoft RSA SChannel Cryptographic Provider"),
                            new DerBitString(new byte[0])))),
                new DerSequence(
                    new DerObjectIdentifier("1.2.840.113549.1.9.14"),
                    new DerSet(
                        new DerSequence(
                            new DerSequence(
                                new DerObjectIdentifier("2.5.29.15"),
                                new DerBoolean(new byte[] { 0x01 }),
                                new DerOctetString(new byte[] { 0x03, 0x02, 0x04, 0xF0 })),
                            new DerSequence(
                                new DerObjectIdentifier("2.5.29.37"),
                                new DerOctetString(new byte[]
            {
                0x30, 0x0a, 0x06, 0x08,
                0x2b, 0x06, 0x01, 0x05,
                0x05, 0x07, 0x03, 0x01
            })),
                            new DerSequence(
                                new DerObjectIdentifier("1.2.840.113549.1.9.15"),
                                new DerOctetString(new byte[]
            {
                0x30, 0x69, 0x30, 0x0e,
                0x06, 0x08, 0x2a, 0x86,
                0x48, 0x86, 0xf7, 0x0d,
                0x03, 0x02, 0x02, 0x02,
                0x00, 0x80, 0x30, 0x0e,
                0x06, 0x08, 0x2a, 0x86,
                0x48, 0x86, 0xf7, 0x0d,
                0x03, 0x04, 0x02, 0x02,
                0x00, 0x80, 0x30, 0x0b,
                0x06, 0x09, 0x60, 0x86,
                0x48, 0x01, 0x65, 0x03,
                0x04, 0x01, 0x2a, 0x30,
                0x0b, 0x06, 0x09, 0x60,
                0x86, 0x48, 0x01, 0x65,
                0x03, 0x04, 0x01, 0x2d,
                0x30, 0x0b, 0x06, 0x09,
                0x60, 0x86, 0x48, 0x01,
                0x65, 0x03, 0x04, 0x01,
                0x02, 0x30, 0x0b, 0x06,
                0x09, 0x60, 0x86, 0x48,
                0x01, 0x65, 0x03, 0x04,
                0x01, 0x05, 0x30, 0x07,
                0x06, 0x05, 0x2b, 0x0e,
                0x03, 0x02, 0x07, 0x30,
                0x0a, 0x06, 0x08, 0x2a,
                0x86, 0x48, 0x86, 0xf7,
                0x0d, 0x03, 0x07
            })),
                            new DerSequence(
                                new DerObjectIdentifier("2.5.29.14"),
                                new DerOctetString(new byte[]
            {
                0x04, 0x14, 0xaa, 0x25,
                0xd9, 0xa2, 0x39, 0x7e,
                0x49, 0xd2, 0x94, 0x85,
                0x7e, 0x82, 0xa8, 0x8f,
                0x3b, 0x20, 0xf1, 0x4e, 0x65, 0xe5
            }))))));

            var signing = new Asn1SignatureFactory("SHA256withRSA", keyPair.Private);
            Pkcs10CertificationRequest kpGen = new Pkcs10CertificationRequest(signing, subjectName, keyPair.Public, attributes, keyPair.Private);

            using (var stream = new StreamWriter(_wizardData.FileName))
            {
                stream.WriteLine(_wizardData.UseIisStyle ? "-----BEGIN NEW CERTIFICATE REQUEST-----" : "-----BEGIN CERTIFICATE REQUEST-----");
                stream.WriteLine(Convert.ToBase64String(kpGen.GetDerEncoded(), Base64FormattingOptions.InsertLineBreaks));
                stream.WriteLine(_wizardData.UseIisStyle ? "-----END NEW CERTIFICATE REQUEST-----" : "-----END CERTIFICATE REQUEST-----");
            }

            var        key = DotNetUtilities.ToRSAParameters((RsaPrivateCrtKeyParameters)keyPair.Private);
            PrivateKey pvk = new PrivateKey();

            pvk.RSA = new RSACryptoServiceProvider();
            pvk.RSA.ImportParameters(key);

            var file   = DialogHelper.GetPrivateKeyFile(subjectName.ToString());
            var folder = Path.GetDirectoryName(file);

            if (!Directory.Exists(folder))
            {
                Directory.CreateDirectory(folder);
            }

            pvk.Save(file);
        }
示例#28
0
 /// <summary>
 /// Create a PKCS#10 Parser using a Pkcs10CertificationRequest object
 /// </summary>
 /// <param name="Request">Pkcs10CertificationRequest object</param>
 /// <exception cref="SignatureException">POP test failed</exception>
 public Pkcs10Parser(Pkcs10CertificationRequest Request)
 {
     this.request = Request;
     readRequest();
 }
        protected override void CompleteWizard()
        {
            X509Name subjectName = new X509Name(_existing.Subject);

            var useRsa = true;
            AsymmetricAlgorithm privateKey = _existing.GetRSAPrivateKey();

            if (privateKey == null)
            {
                useRsa     = false;
                privateKey = _existing.GetECDsaPrivateKey();
                ShowError(null, "Renewing ECDSA based certificates is not yet supported.", false);
                return;
            }

            // Generate the private/public keypair
            var keyPair = DotNetUtilities.GetKeyPair(privateKey);

            // Generate the CSR
            Asn1Set attributes = new DerSet(
                new DerSequence(
                    new DerObjectIdentifier("1.3.6.1.4.1.311.13.2.3"),
                    new DerSet(new DerIA5String(Environment.OSVersion.Version.ToString()))),
                new DerSequence(
                    new DerObjectIdentifier("1.3.6.1.4.1.311.21.20"),
                    new DerSet(
                        new DerSequence(
                            new DerInteger(5),
                            new DerUtf8String(Environment.MachineName),
                            new DerUtf8String(Environment.UserName),
                            new DerUtf8String("JexusManager.exe")))),
                new DerSequence(
                    new DerObjectIdentifier("1.3.6.1.4.1.311.13.2.2"),
                    new DerSet(
                        new DerSequence(
                            new DerInteger(1),
                            new DerBmpString("Microsoft RSA SChannel Cryptographic Provider"),
                            new DerBitString(new byte[0])))),
                new DerSequence(
                    new DerObjectIdentifier("1.2.840.113549.1.9.14"),
                    new DerSet(
                        new DerSequence(
                            new DerSequence(
                                new DerObjectIdentifier("2.5.29.15"),
                                new DerBoolean(new byte[] { 0x01 }),
                                new DerOctetString(new byte[] { 0x03, 0x02, 0x04, 0xF0 })),
                            new DerSequence(
                                new DerObjectIdentifier("2.5.29.37"),
                                new DerOctetString(new byte[]
            {
                0x30, 0x0a, 0x06, 0x08,
                0x2b, 0x06, 0x01, 0x05,
                0x05, 0x07, 0x03, 0x01
            })),
                            new DerSequence(
                                new DerObjectIdentifier("1.2.840.113549.1.9.15"),
                                new DerOctetString(new byte[]
            {
                0x30, 0x69, 0x30, 0x0e,
                0x06, 0x08, 0x2a, 0x86,
                0x48, 0x86, 0xf7, 0x0d,
                0x03, 0x02, 0x02, 0x02,
                0x00, 0x80, 0x30, 0x0e,
                0x06, 0x08, 0x2a, 0x86,
                0x48, 0x86, 0xf7, 0x0d,
                0x03, 0x04, 0x02, 0x02,
                0x00, 0x80, 0x30, 0x0b,
                0x06, 0x09, 0x60, 0x86,
                0x48, 0x01, 0x65, 0x03,
                0x04, 0x01, 0x2a, 0x30,
                0x0b, 0x06, 0x09, 0x60,
                0x86, 0x48, 0x01, 0x65,
                0x03, 0x04, 0x01, 0x2d,
                0x30, 0x0b, 0x06, 0x09,
                0x60, 0x86, 0x48, 0x01,
                0x65, 0x03, 0x04, 0x01,
                0x02, 0x30, 0x0b, 0x06,
                0x09, 0x60, 0x86, 0x48,
                0x01, 0x65, 0x03, 0x04,
                0x01, 0x05, 0x30, 0x07,
                0x06, 0x05, 0x2b, 0x0e,
                0x03, 0x02, 0x07, 0x30,
                0x0a, 0x06, 0x08, 0x2a,
                0x86, 0x48, 0x86, 0xf7,
                0x0d, 0x03, 0x07
            })),
                            new DerSequence(
                                new DerObjectIdentifier("2.5.29.14"),
                                new DerOctetString(new byte[]
            {
                0x04, 0x14, 0xaa, 0x25,
                0xd9, 0xa2, 0x39, 0x7e,
                0x49, 0xd2, 0x94, 0x85,
                0x7e, 0x82, 0xa8, 0x8f,
                0x3b, 0x20, 0xf1, 0x4e, 0x65, 0xe5
            }))))));

            var signing = new Asn1SignatureFactory(useRsa ? "SHA256withRSA" : "SHA256WithECDSA", keyPair.Private);
            Pkcs10CertificationRequest kpGen = new Pkcs10CertificationRequest(signing, subjectName, keyPair.Public, attributes);

            using (var stream = new StreamWriter(_wizardData.FileName))
            {
                stream.WriteLine(_wizardData.UseIisStyle ? "-----BEGIN NEW CERTIFICATE REQUEST-----" : "-----BEGIN CERTIFICATE REQUEST-----");
                stream.WriteLine(Convert.ToBase64String(kpGen.GetDerEncoded(), Base64FormattingOptions.InsertLineBreaks));
                stream.WriteLine(_wizardData.UseIisStyle ? "-----END NEW CERTIFICATE REQUEST-----" : "-----END CERTIFICATE REQUEST-----");
            }

            var        key = DotNetUtilities.ToRSAParameters((RsaPrivateCrtKeyParameters)keyPair.Private);
            PrivateKey pvk = new PrivateKey();

            pvk.RSA = new RSACryptoServiceProvider();
            pvk.RSA.ImportParameters(key);

            var file   = DialogHelper.GetPrivateKeyFile(_existing.Subject);
            var folder = Path.GetDirectoryName(file);

            if (!Directory.Exists(folder))
            {
                Directory.CreateDirectory(folder);
            }

            pvk.Save(file);
        }
示例#30
0
        void IPKIEncordeService.GenerateGemFileForKPI(
            string commonName,
            string organization,
            string organizationalUnit,
            string locality,
            string state,
            string countryIso2Characters,
            string emailAddress,
            SignatureAlgorithm signatureAlgorithm,
            RsaKeyLength rsaKeyLength)
        {
            countryIso2Characters = "US";
            emailAddress          = "";
            signatureAlgorithm    = SignatureAlgorithm.SHA256;
            rsaKeyLength          = RsaKeyLength.Length2048Bits;

            #region Determine Signature Algorithm

            string signatureAlgorithmStr;
            switch (signatureAlgorithm)
            {
            case SignatureAlgorithm.SHA1:
                signatureAlgorithmStr = PkcsObjectIdentifiers.Sha1WithRsaEncryption.Id;
                break;

            case SignatureAlgorithm.SHA256:
                signatureAlgorithmStr = PkcsObjectIdentifiers.Sha256WithRsaEncryption.Id;
                break;

            case SignatureAlgorithm.SHA512:
                signatureAlgorithmStr = PkcsObjectIdentifiers.Sha512WithRsaEncryption.Id;
                break;

            default:
                signatureAlgorithmStr = PkcsObjectIdentifiers.Sha256WithRsaEncryption.Id;
                break;
            }

            #endregion

            #region Cert Info

            IDictionary attrs = new Hashtable();

            attrs.Add(X509Name.CN, commonName);
            attrs.Add(X509Name.O, organization);
            attrs.Add(X509Name.OU, organizationalUnit);
            attrs.Add(X509Name.L, locality);
            attrs.Add(X509Name.ST, state);
            attrs.Add(X509Name.C, countryIso2Characters);
            attrs.Add(X509Name.EmailAddress, emailAddress);

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

            #endregion

            #region Key Generator

            RsaKeyPairGenerator rsaKeyPairGenerator = new RsaKeyPairGenerator();
            rsaKeyPairGenerator.Init(new KeyGenerationParameters(new SecureRandom(new CryptoApiRandomGenerator()), (int)rsaKeyLength));
            AsymmetricCipherKeyPair pair = rsaKeyPairGenerator.GenerateKeyPair();

            #endregion

            #region CSR Generator

            string path_project_bin = Path.GetDirectoryName(Assembly.GetEntryAssembly().Location.Substring(0, Assembly.GetEntryAssembly().Location.IndexOf("bin\\")));

            Asn1SignatureFactory signatureFactory = new Asn1SignatureFactory(signatureAlgorithmStr, pair.Private);

            Pkcs10CertificationRequest csr = new Pkcs10CertificationRequest(signatureFactory, subject, pair.Public, null, pair.Private);

            #endregion

            #region Convert to PEM and Output

            #region Private Key

            StringBuilder privateKeyStrBuilder = new StringBuilder();
            PemWriter     privateKeyPemWriter  = new PemWriter(new StringWriter(privateKeyStrBuilder));
            privateKeyPemWriter.WriteObject(pair.Private);
            privateKeyPemWriter.Writer.Flush();
            string        pathToNewFolder = System.IO.Path.Combine(path_project_bin + "/bin/keys/users/", "2");
            DirectoryInfo directory       = Directory.CreateDirectory(pathToNewFolder);
            File.WriteAllText(path_project_bin + "/bin/keys/users/2/private.pem", privateKeyStrBuilder.ToString());

            PrivateKey = privateKeyStrBuilder.ToString();

            #endregion Private Key

            #region Public Key

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

            File.WriteAllText(path_project_bin + "/bin/keys/users/2/public.pem", publicKeyStrBuilder.ToString());

            PublicKey = publicKeyStrBuilder.ToString();

            #endregion Public Key

            #region CSR


            StringBuilder csrStrBuilder = new StringBuilder();
            PemWriter     csrPemWriter  = new PemWriter(new StringWriter(csrStrBuilder));
            csrPemWriter.WriteObject(csr);
            csrPemWriter.Writer.Flush();
            File.WriteAllText(path_project_bin + "/bin/keys/users/2/publicCert.pem", csrStrBuilder.ToString());

            Csr = csrStrBuilder.ToString();

            #endregion CSR

            #endregion
        }
示例#31
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()));
 }