Exemple #1
0
        private static void GenerateNew(string scepURL, string pfxOutputPath, string certOutputPath, string pkcs10OutputPath, string challengePassword, string cN = null)
        {
            AsymmetricCipherKeyPair rsaKeyPair = GenerateRSAKeyPair(2048);

            Pkcs10CertificationRequest request = CreatePKCS10(cN ?? Guid.NewGuid().ToString(), challengePassword, rsaKeyPair);

            byte[] pkcs10 = request.GetDerEncoded();
            if (!string.IsNullOrWhiteSpace(pkcs10OutputPath))
            {
                File.WriteAllBytes(pkcs10OutputPath, pkcs10);
            }

            X509Certificate selfSignedCertBC = SignCertificateFromRequest(request, new Asn1SignatureFactory("SHA256WITHRSA", rsaKeyPair.Private));

            byte[] baSelfSignedCert = SaveAsPkcs12(selfSignedCertBC, rsaKeyPair, PasswordForTemporaryKeys);

            byte[] binIssuedCertSCEPResponse;

            using (X509Certificate2 selfSignedCert = new X509Certificate2(baSelfSignedCert, PasswordForTemporaryKeys))
                binIssuedCertSCEPResponse = SubmitPkcs10ToScep(scepURL, pkcs10, selfSignedCert);

            X509Certificate bcIssuedCert = new X509CertificateParser().ReadCertificate(binIssuedCertSCEPResponse);

            File.WriteAllBytes(certOutputPath, bcIssuedCert.GetEncoded());
            byte[] issuedPkcs12 = SaveAsPkcs12(bcIssuedCert, rsaKeyPair, "password");
            File.WriteAllBytes(pfxOutputPath, issuedPkcs12);
        }
        private byte[] CreateCsr(AsymmetricCipherKeyPair signingKeyPair, string signatureAlgorithm)
        {
            var key = signingKeyPair;

            Dictionary <DerObjectIdentifier, string> values = CreateSubjectValues("my common name");

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

            DerSet attributes = null;

            var signatureFactory = new Asn1SignatureFactory(signatureAlgorithm, key.Private);

            var pkcs10Csr = new Pkcs10CertificationRequest(
                signatureFactory,
                subject,
                key.Public,
                attributes,
                key.Private);

            byte[] derEncoded = pkcs10Csr.GetDerEncoded();

            //string stringEncoded = Convert.ToBase64String(derEncoded);
            //return stringEncoded;
            return(derEncoded);
        }
Exemple #3
0
        private static void GenerateComputerCertificateRequest(string scepURL, string challengePassword, string outputPath)
        {
            bool   useDebugOutput = !string.IsNullOrEmpty(outputPath);
            string pfxPassword    = useDebugOutput ? "password" : PasswordForTemporaryKeys;

            AsymmetricCipherKeyPair rsaKeyPair = GenerateRSAKeyPair(2048);

            Pkcs10CertificationRequest request = CreatePKCS10ForComputer(challengePassword, rsaKeyPair);

            byte[] pkcs10 = request.GetDerEncoded();

            X509Certificate selfSignedCertBC = SignCertificateFromRequest(request, new Asn1SignatureFactory("SHA256WITHRSA", rsaKeyPair.Private));

            byte[] baSelfSignedCert = SaveAsPkcs12(selfSignedCertBC, rsaKeyPair, PasswordForTemporaryKeys);

            byte[] binIssuedCert;

            using (X509Certificate2 selfSignedCert = new X509Certificate2(baSelfSignedCert, PasswordForTemporaryKeys))
                binIssuedCert = SubmitPkcs10ToScep(scepURL, pkcs10, selfSignedCert);

            X509Certificate bcIssuedCert = new X509CertificateParser().ReadCertificate(binIssuedCert);

            byte[] issuedPkcs12 = SaveAsPkcs12(bcIssuedCert, rsaKeyPair, pfxPassword);
            if (useDebugOutput)
            {
                File.WriteAllBytes(outputPath, issuedPkcs12);
            }

            ImportPFX2MachineStore(useDebugOutput, pfxPassword, issuedPkcs12);
        }
Exemple #4
0
        public static byte[] GenerateEcCsr(IEnumerable <string> names,
                                           CertPrivateKey pk, SysHashAlgorName?hashAlgor = null)
        {
            if (hashAlgor == null)
            {
                hashAlgor = SysHashAlgorName.SHA256;
            }

            var attrs = new Dictionary <DerObjectIdentifier, string>
            {
                [X509Name.CN] = names.First(),
            };
            var subj = new X509Name(attrs.Keys.ToList(), attrs.Values.ToList());

            var ackp = pk.KeyPair;

            var sigAlg   = $"{hashAlgor.Value.Name}withECDSA";
            var csrAttrs = new List <Asn1Encodable>();

            var gnames = new List <GeneralName>(
                names.Select(x => new GeneralName(GeneralName.DnsName, x)));

            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

            return(csr.GetDerEncoded());
        }
        public bool GenerarLLavesSoftware(string subject, string challenge, string fileName)
        {
            try
            {
                RsaKeyPairGenerator r = new RsaKeyPairGenerator();
                var param             = new RsaKeyGenerationParameters(new BigInteger("10001", 16), new SecureRandom(), 1024, 80);
                r.Init(param);
                AsymmetricCipherKeyPair k = r.GenerateKeyPair();
                var privada = PrivateKeyInfoFactory.CreatePrivateKeyInfo(k.Private);
                SubjectPublicKeyInfo pubInfo = SubjectPublicKeyInfoFactory.CreateSubjectPublicKeyInfo(k.Public);
                string priv = Convert.ToBase64String(privada.GetDerEncoded());
                string pub  = Convert.ToBase64String(pubInfo.GetDerEncoded());
                File.WriteAllText("Privada.pem", priv);
                File.WriteAllText("Publica.pem", pub);
                RsaPrivateCrtKeyParameters privateKey = (RsaPrivateCrtKeyParameters)PrivateKeyFactory.CreateKey(Convert.FromBase64String(priv));
                RsaKeyParameters           publicKey  = (RsaKeyParameters)PublicKeyFactory.CreateKey(Convert.FromBase64String(pub));

                DerSet derset = null;
                if (challenge != null)
                {
                    ChallengePassword chpass = new ChallengePassword(challenge);
                    derset = new DerSet(chpass);
                }
                else
                {
                    derset = new DerSet();
                }

                X509Name sub = new X509Name(subject, new ConverterSidetec());
                Pkcs10CertificationRequest ds = new Pkcs10CertificationRequest("SHA1WITHRSA", sub, publicKey, derset, privateKey);

                File.WriteAllBytes(fileName, ds.GetDerEncoded());
                return(true);
            }
            catch (Exception ee)
            {
                Log.Error(ee.Message);
                return(false);
            }
        }
Exemple #6
0
        /// <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), prvKey);

            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();
            }
        }
        protected override void CompleteWizard()
        {
            X509Name subjectName = new X509Name(_existing.Subject);

            // Generate the private/public keypair
            var keyPair = DotNetUtilities.GetKeyPair(_existing.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("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(_existing.Subject);
            var folder = Path.GetDirectoryName(file);

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

            pvk.Save(file);
        }
Exemple #8
0
        /// <summary>
        /// Issues the certificate.
        /// </summary>
        /// <param name="request">The request.</param>
        /// <param name="profile">The profile</param>
        /// <param name="notBefore">The not before.</param>
        /// <param name="notAfter">The not after.</param>
        /// <returns>
        /// Certificate
        /// </returns>
        /// <exception cref="System.ArgumentException">Invalid signature algorithm in request</exception>
        /// <exception cref="System.ArgumentOutOfRangeException">Invalid lifetime units in ValidityPeriod</exception>
        private X509Certificate issueCertificate(Pkcs10CertificationRequest request, Profile.Profile profile, DateTime notBefore, DateTime notAfter)
        {
            X509Certificate newCert;
            string          profileName = "";

            // Parse the request
            Pkcs10Parser p10 = new Pkcs10Parser(request);

            // Check that correct sig algorithm has been used
            DerObjectIdentifier sigAlgOid = X509Utilities.GetAlgorithmOid(signatureAlgorithm);

            if (!p10.SignatureAlgorithm.Equals(sigAlgOid))
            {
                logEvent(LogEvent.EventType.Error, "Invalid signature algorithm in request: " + p10.SignatureAlgorithm.ToString());
                throw new ArgumentException("Invalid signature algorithm in request", p10.SignatureAlgorithm.ToString());
            }

            // Create a Cert Generator according to the FIPS 140 policy and CA Type
            ICertGen certGen;

            if ((fips140) && (type == CA_Type.dhTA.ToString()))
            {
                certGen = new SysV1CertGen();
            }
            else if ((fips140) && (type != CA_Type.dhTA.ToString()))
            {
                certGen = new SysV3CertGen(policyEnforcement);
            }
            else
            {
                certGen = new BcV3CertGen(policyEnforcement);
            }

            // Setup the certificate
            certGen.SetSerialNumber(nextCertSerial());
            certGen.SetIssuerDN(caCertificate.SubjectDN);
            certGen.SetSubjectDN(p10.Subject);
            certGen.SetPublicKey(p10.PublicKey);
            certGen.SetSignatureAlgorithm(signatureAlgorithm);
            if (certGen.GetVersion() == X509ver.V3)
            {
                ((V3CertGen)certGen).AddExtension(X509Extensions.AuthorityKeyIdentifier, false, new AuthorityKeyIdentifierStructure(caCertificate.GetPublicKey()));
                ((V3CertGen)certGen).AddExtension(X509Extensions.SubjectKeyIdentifier, false, new SubjectKeyIdentifierStructure(p10.PublicKey));
            }

            // Add further extensions either from profile or request attributes
            // If a profile is specified ignore all attributes apart from SubjAltName
            if (profile != null)
            {
                // Add in SubjAltName if there is one
                if ((p10.SubjectAltNames != null) && (certGen.GetVersion() == X509ver.V3))
                {
                    bool critical = p10.IsCritical(X509Extensions.SubjectAlternativeName);
                    ((V3CertGen)certGen).AddExtension(X509Extensions.SubjectAlternativeName, critical, p10.SubjectAltNames);
                }

                // Capture the profile name for database
                profileName = profile.Name;

                // cut the cert
                newCert = generate(certGen, profile, notBefore, notAfter);
            }
            else    // No profile
            {
                // Set the validity period
                certGen.SetNotBefore(notBefore.ToUniversalTime());
                certGen.SetNotAfter(notAfter.ToUniversalTime());

                // Do what it says in the request
                newCert = generate(certGen, p10.Extensions);
            }

            // Add certificate to the CA DB
            Database.AddCertificate(newCert, request.GetDerEncoded(), profileName, dbFileLocation, caCertificate, cspParam);
            logEvent(LogEvent.EventType.DBAddCert, "DB: Certificate added: " + newCert.SerialNumber.ToString());

            return(newCert);
        }
Exemple #9
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();
            }
        }
        /// <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));
        }
Exemple #11
0
        protected override void CompleteWizard()
        {
            // Generate the CSR
            X509Name subjectName;

            try
            {
                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));
            }
            catch (ArgumentException ex)
            {
                ShowError(ex, Text, false);
                return;
            }

            // 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);

            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);
        }