Ejemplo n.º 1
0
        /// <summary>
        /// Creates a self signed Certificate using Boncy castle crypto
        /// </summary>
        /// <param name="request"></param>
        /// <param name="issuerPrivKey"></param>
        /// <param name="myPrivateKey"></param>
        /// <returns></returns>
        public static X509Certificate2 CreateSelfSignedCertificateBasedOnCertificateAuthorityPrivateKey(APICertificateRequest request, AsymmetricKeyParameter issuerPrivKey, ref AsymmetricKeyParameter myPrivateKey)
        {
            const int keyStrength = 4096;

            // Generating Random Numbers
            CryptoApiRandomGenerator randomGenerator = new CryptoApiRandomGenerator();
            SecureRandom             random          = new SecureRandom(randomGenerator);
            //ISignatureFactory signatureFactory = new Asn1SignatureFactory("SHA512WITHRSA", issuerPrivKey, random);
            ISignatureFactory signatureFactory = new Asn1SignatureFactory("SHA512WITHRSA", issuerPrivKey, random);
            // The Certificate Generator
            X509V3CertificateGenerator certificateGenerator = new X509V3CertificateGenerator();

            certificateGenerator.AddExtension(X509Extensions.ExtendedKeyUsage, true, new ExtendedKeyUsage((new List <DerObjectIdentifier>()
            {
                new DerObjectIdentifier("1.3.6.1.5.5.7.3.1"), new DerObjectIdentifier("1.3.6.1.5.5.7.3.2")
            })));

            var lExtensions = new List <DerObjectIdentifier>();

            if (request.Aspsp)
            {
                lExtensions.Add(new DerObjectIdentifier("0.4.0.19495.1.1"));//, PSD2Roles.ASPSP);
            }
            if (request.Pisp)
            {
                lExtensions.Add(new DerObjectIdentifier("0.4.0.19495.1.2"));//, PSD2Roles.PISP);
            }
            if (request.Aisp)
            {
                lExtensions.Add(new DerObjectIdentifier("0.4.0.19495.1.3"));//, PSD2Roles.AISP);
            }
            if (request.Piisp)
            {
                lExtensions.Add(new DerObjectIdentifier("0.4.0.19495.1.4"));//, PSD2Roles.PIISP);
            }
            certificateGenerator.AddExtension(X509Extensions.QCStatements, true, new ExtendedKeyUsage(lExtensions));


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

            certificateGenerator.SetSerialNumber(serialNumber);

            // Issuer and Subject Name
            // build name attributes
            var nameOids = new ArrayList();

            nameOids.Add(X509Name.CN);
            nameOids.Add(X509Name.O);
            nameOids.Add(X509Name.OU);
            nameOids.Add(X509Name.C);
            nameOids.Add(X509Name.L);
            nameOids.Add(X509Name.ST);

            var nameValues = new ArrayList();

            nameValues.Add(request.CommonName);
            nameValues.Add(request.Organization);
            nameValues.Add(request.OrganizationUnit);
            nameValues.Add(request.Country);
            nameValues.Add(request.City);
            nameValues.Add(request.State);


            //X509Name subjectDN = new X509Name("CN="+request.CommonName);
            X509Name subjectDN = new X509Name(nameOids, nameValues);
            X509Name issuerDN  = new X509Name("CN=" + request.CommonName);

            certificateGenerator.SetIssuerDN(issuerDN);
            certificateGenerator.SetSubjectDN(subjectDN);

            // Valid For
            DateTime notBefore = DateTime.UtcNow.Date;
            DateTime notAfter  = notBefore.AddDays(request.Validity);

            certificateGenerator.SetNotBefore(notBefore);
            certificateGenerator.SetNotAfter(notAfter);

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

            keyPairGenerator.Init(keyGenerationParameters);
            subjectKeyPair = keyPairGenerator.GenerateKeyPair();
            myPrivateKey   = subjectKeyPair.Private;
            certificateGenerator.SetPublicKey(subjectKeyPair.Public);

            //GeneralNames subjectAltName = new GeneralNames(new GeneralName(GeneralName.OtherName, subjectName));
            //certificateGenerator.AddExtension(X509Extensions.SubjectAlternativeName, false, subjectAltName);


            // self sign certificate
            Org.BouncyCastle.X509.X509Certificate certificate = certificateGenerator.Generate(signatureFactory);

            X509Certificate2 certificate2 = new X509Certificate2(certificate.GetEncoded());

            //certificate2.Import(certificate.GetEncoded());
            return(certificate2);
        }
        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);
        }
Ejemplo n.º 3
0
        // Note: Much of this code comes from https://stackoverflow.com/a/22247129
        private static X509Certificate2 GenerateSelfSignedCertificate(string subject)
        {
            const int keyStrength = 2048;

            // Generating Random Numbers
            var randomGenerator = new CryptoApiRandomGenerator();
            var random          = new SecureRandom(randomGenerator);

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

            // Serial Number
            certificateGenerator.SetSerialNumber(BigIntegers.CreateRandomInRange(BigInteger.One, BigInteger.ValueOf(long.MaxValue), random));

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

            keyPairGenerator.Init(keyGenerationParameters);
            var subjectKeyPair = keyPairGenerator.GenerateKeyPair();

            certificateGenerator.SetPublicKey(subjectKeyPair.Public);

            // Subject DN
            certificateGenerator.SetSubjectDN(new X509Name("CN=" + subject));

            // Subject Alternative Name
            var subjectAlternativeNames = new List <Asn1Encodable>()
            {
                new GeneralName(GeneralName.DnsName, Environment.MachineName),
                new GeneralName(GeneralName.DnsName, "localhost"),
                new GeneralName(GeneralName.IPAddress, "127.0.0.1"),
            };

            if (subject != "localhost" && subject != Environment.MachineName)
            {
                subjectAlternativeNames.Add(new GeneralName(GeneralName.DnsName, subject));
            }

            certificateGenerator.AddExtension(X509Extensions.SubjectAlternativeName.Id, false, new DerSequence(subjectAlternativeNames.ToArray()));

            // Issuer
            certificateGenerator.SetIssuerDN(new X509Name("CN=" + subject));
            certificateGenerator.AddExtension(X509Extensions.SubjectKeyIdentifier.Id, false, new SubjectKeyIdentifier(SubjectPublicKeyInfoFactory.CreateSubjectPublicKeyInfo(subjectKeyPair.Public)));

            // Valid For
            var notBefore = DateTime.UtcNow.Date;
            var notAfter  = notBefore.AddYears(2);

            certificateGenerator.SetNotBefore(notBefore);
            certificateGenerator.SetNotAfter(notAfter);

            // Add basic constraint
            certificateGenerator.AddExtension(X509Extensions.BasicConstraints.Id, true, new BasicConstraints(false));

            certificateGenerator.AddExtension(X509Extensions.ExtendedKeyUsage.Id, false, new ExtendedKeyUsage(KeyPurposeID.IdKPServerAuth));

            // Signature Algorithm
            const string signatureAlgorithm = "SHA256WithRSA";
            var          signatureFactory   = new Asn1SignatureFactory(signatureAlgorithm, subjectKeyPair.Private);

            // selfsign certificate
            var certificate = certificateGenerator.Generate(signatureFactory);

            // correcponding private key
            var info = PrivateKeyInfoFactory.CreatePrivateKeyInfo(subjectKeyPair.Private);

            // merge into X509Certificate2
            var x509 = new X509Certificate2(certificate.GetEncoded());
            var seq  = (Asn1Sequence)Asn1Object.FromByteArray(info.ParsePrivateKey().GetDerEncoded());

            if (seq.Count != 9)
            {
                // throw new PemException("malformed sequence in RSA private key");
            }

            var rsa       = RsaPrivateKeyStructure.GetInstance(seq);
            var rsaparams = new RsaPrivateCrtKeyParameters(
                rsa.Modulus, rsa.PublicExponent, rsa.PrivateExponent, rsa.Prime1, rsa.Prime2, rsa.Exponent1, rsa.Exponent2, rsa.Coefficient);

            try
            {
                x509.PrivateKey = ToDotNetKey(rsaparams); // x509.PrivateKey = DotNetUtilities.ToRSA(rsaparams);
            }
            catch (CryptographicException e)
            {
                throw new Exception($"Exception on cert generation!\nSubject {subject}\nHostname {Environment.MachineName}\nSequenceCount {seq.Count} (should be 9?)", e);
            }

            return(x509);
        }
Ejemplo n.º 4
0
        static void Main(string[] args)
        {
            //web site: https://www.youtube.com/watch?v=4iPzIEXC7a8

            string SourceData;

            byte[] tmpSource;
            byte[] tmpHash;

            //enter the any text
            Console.WriteLine("Enter any text: ");

            //var _database = DataBase.meuTexto(); //database
            //var _iOS = iOS.meuTexto();
            var _ws = WebApi.meuTexto();

            SourceData = _ws;//Console.ReadLine();

            //create byte array from source data
            tmpSource = ASCIIEncoding.ASCII.GetBytes(SourceData);
            Console.WriteLine();
            Console.WriteLine();
            Console.WriteLine("Key pairs are generating ... please wait for few minutes ... ");
            Console.WriteLine();

            //RSAKeyPairGeneration
            RsaKeyPairGenerator rsaKeyPairGen = new RsaKeyPairGenerator();

            rsaKeyPairGen.Init(new KeyGenerationParameters(new SecureRandom(), 2048));
            AsymmetricCipherKeyPair keyPair = rsaKeyPairGen.GenerateKeyPair();

            //extrating the private key from the pair
            RsaKeyParameters PrivateKey = (RsaKeyParameters)keyPair.Private;
            RsaKeyParameters PublicKey  = (RsaKeyParameters)keyPair.Public;

            //print the public key in pem format
            TextWriter textWriter1 = new StringWriter();
            PemWriter  pemWriter1  = new PemWriter(textWriter1);

            pemWriter1.WriteObject(PublicKey);
            pemWriter1.Writer.Flush();
            string print_publicKey = textWriter1.ToString();

            Console.WriteLine("Public Key is: {0}", print_publicKey);
            Console.WriteLine();

            //generation of digital signature sha-512
            ISigner sign = SignerUtilities.GetSigner(PkcsObjectIdentifiers.Sha512WithRsaEncryption.Id);

            sign.Init(true, PrivateKey);
            sign.BlockUpdate(tmpSource, 0, tmpSource.Length);
            byte[] signature = sign.GenerateSignature();

            Console.WriteLine();
            Console.WriteLine("The digital signature is: ");
            Console.WriteLine(ByteArrayToString(signature));
            Console.WriteLine();

            //verification of the digital signature
            ISigner sign1 = SignerUtilities.GetSigner(PkcsObjectIdentifiers.Sha512WithRsaEncryption.Id);

            sign1.Init(false, PublicKey);
            sign1.BlockUpdate(tmpSource, 0, tmpSource.Length);
            bool status = sign1.VerifySignature(signature);

            Console.WriteLine();
            Console.WriteLine("Status of the digital signature: " + " ");
            if (status == true)
            {
                Console.WriteLine("Signature is valid");
                Console.WriteLine();
                Console.ReadLine();
            }
            else
            {
                Console.WriteLine("Signature is not valid");
                Console.WriteLine();
                Console.ReadLine();
            }
            Console.WriteLine("Please click enter two times");
            Console.ReadLine();
        }
Ejemplo n.º 5
0
        /// <summary>
        /// Builds the certificate depending on the parameters
        /// </summary>
        /// <returns>X509Certificate2 from the chosen parameters</returns>
        public X509Certificate2 Build()
        {
            // 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;
            }

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

            // Issuer and Subject Name
            if (_DistinguishedName == null)
            {
                certificateGenerator.SetIssuerDN(new X509Name(_issuerName ?? _subjectName));
                certificateGenerator.SetSubjectDN(new X509Name(_subjectName));
            }
            else
            {
                if (_issuerName != null && _issuerName.Length > 0)
                {
                    certificateGenerator.SetIssuerDN(new X509Name(_issuerName));
                }
                else
                {
                    certificateGenerator.SetIssuerDN(DistinguishedNamesToX509Name(_DistinguishedName));
                }
                certificateGenerator.SetSubjectDN(DistinguishedNamesToX509Name(_DistinguishedName));
            }

            // Authority Key Identifier
            if (_issuer != null)
            {
                var authorityKeyIdentifier = new AuthorityKeyIdentifierStructure(
                    DotNetUtilities.FromX509Certificate(_issuer)
                    );
                certificateGenerator.AddExtension(
                    X509Extensions.AuthorityKeyIdentifier.Id,
                    false,
                    authorityKeyIdentifier
                    );
            }

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

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

            // self-sign certificate
            ISignatureFactory signatureFactory = new Asn1SignatureFactory(PKCS15SignatureAlgorithmList[(int)_signatureAlgorithm], issuerKeyPair.Private, random);
            var certificate = certificateGenerator.Generate(signatureFactory);

            // merge into X509Certificate2
            if (_friendlyName != null)
            {
                return(new X509Certificate2(certificate.GetEncoded())
                {
                    PrivateKey = ConvertToRsaPrivateKey(subjectKeyPair),
                    FriendlyName = _friendlyName
                });
            }
            return(new X509Certificate2(certificate.GetEncoded())
            {
                PrivateKey = ConvertToRsaPrivateKey(subjectKeyPair)
            });
        }
Ejemplo n.º 6
0
        public static void Main(string[] args)
        {
            try
            {
                // Keypair Generator
                RsaKeyPairGenerator kpGenerator = new RsaKeyPairGenerator();
                kpGenerator.Init(new KeyGenerationParameters(new SecureRandom(), 1024));

                // Create a keypair
                AsymmetricCipherKeyPair keys = kpGenerator.GenerateKeyPair();

                // Connect to the TPM
                Tpm2Device tpmDevice = new TbsDevice();
                tpmDevice.Connect();
                Tpm2      tpm       = new Tpm2(tpmDevice);
                AuthValue ownerAuth = new AuthValue();

                // Create a handle based on the hash of the cert thumbprint
                ushort    hashcode = (ushort)keys.GetHashCode();
                TpmHandle nvHandle = TpmHandle.NV(hashcode);

                // Clean up the slot
                tpm[ownerAuth]._AllowErrors().NvUndefineSpace(TpmHandle.RhOwner, nvHandle);

                // Export serial number, the "valid from" date (the cert will be valid for 1 year, so no need to store that date, too!), the size of the keys blob and the keys themselves
                TextWriter textWriter = new StringWriter();
                PemWriter  pemWriter  = new PemWriter(textWriter);
                pemWriter.WriteObject(keys);
                pemWriter.Writer.Flush();
                byte[] rawData = Encoding.ASCII.GetBytes(textWriter.ToString().ToCharArray());

                ushort size   = (ushort)(sizeof(long) + sizeof(long) + rawData.Length + sizeof(int) + 64);
                ushort offset = 0;

                // Define a slot for the keys, which is 64 bytes bigger than we need as we write in 64-byte chunks
                tpm[ownerAuth].NvDefineSpace(TpmHandle.RhOwner, ownerAuth, new NvPublic(nvHandle, TpmAlgId.Sha256, NvAttr.Authread | NvAttr.Authwrite, new byte[0], size));

                // Write the serial number
                tpm[ownerAuth].NvWrite(nvHandle, nvHandle, BitConverter.GetBytes(BigInteger.ProbablePrime(120, new Random()).LongValue), offset);
                offset += sizeof(long);

                // Write the "valid from" date (today) in FileTime format
                tpm[ownerAuth].NvWrite(nvHandle, nvHandle, BitConverter.GetBytes(DateTime.Today.ToFileTime()), offset);
                offset += sizeof(long);

                // Write the size of the keys
                tpm[ownerAuth].NvWrite(nvHandle, nvHandle, BitConverter.GetBytes(rawData.Length), offset);
                offset += sizeof(int);

                // Write the keys themselves (in 64-byte chunks)
                byte[] dataToWrite = new byte[64];
                int    index       = 0;
                while (index < rawData.Length)
                {
                    for (int i = 0; i < 64; i++)
                    {
                        if (index < rawData.Length)
                        {
                            dataToWrite[i] = rawData[index];
                            index++;
                        }
                        else
                        {
                            // fill the rest of the buffer with zeros
                            dataToWrite[i] = 0;
                        }
                    }

                    tpm[ownerAuth].NvWrite(nvHandle, nvHandle, dataToWrite, offset);
                    offset += 64;
                }

                tpm.Dispose();

                Console.WriteLine("Keys successfully generated and copied to TPM. Hashcode=" + hashcode.ToString());
            }
            catch (Exception e)
            {
                Console.WriteLine("Could not generate or copy keys to TPM: " + e.Message);
            }
        }
        public static X509Certificate2 CreateCertificateAuthorityCertificate(string subjectName, out AsymmetricKeyParameter CaPrivateKey, out AsymmetricKeyParameter CaPublicKey)
        {
            const int keyStrength = 2048;

            // Generating Random Numbers
            CryptoApiRandomGenerator randomGenerator = new CryptoApiRandomGenerator();
            SecureRandom             random          = new SecureRandom(randomGenerator);

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

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

            certificateGenerator.SetSerialNumber(serialNumber);

            // Issuer and Subject Name
            X509Name subjectDN = new X509Name(subjectName);
            X509Name issuerDN  = subjectDN;

            certificateGenerator.SetIssuerDN(issuerDN);
            certificateGenerator.SetSubjectDN(subjectDN);

            // Valid For
            DateTime notBefore = DateTime.UtcNow.Date;
            DateTime notAfter  = notBefore.AddYears(2);

            certificateGenerator.SetNotBefore(notBefore);
            certificateGenerator.SetNotAfter(notAfter);

            // Subject Public Key
            AsymmetricCipherKeyPair subjectKeyPair;
            KeyGenerationParameters keyGenerationParameters = new KeyGenerationParameters(random, keyStrength);
            RsaKeyPairGenerator     keyPairGenerator        = new RsaKeyPairGenerator();

            keyPairGenerator.Init(keyGenerationParameters);
            subjectKeyPair = keyPairGenerator.GenerateKeyPair();

            certificateGenerator.SetPublicKey(subjectKeyPair.Public);

            // Generating the Certificate
            AsymmetricCipherKeyPair issuerKeyPair    = subjectKeyPair;
            ISignatureFactory       signatureFactory = new Asn1SignatureFactory("SHA512WITHRSA", issuerKeyPair.Private, random);

            // selfsign certificate
            Org.BouncyCastle.X509.X509Certificate certificate = certificateGenerator.Generate(signatureFactory);
            var dotNetPrivateKey = ToDotNetKey((RsaPrivateCrtKeyParameters)subjectKeyPair.Private);

            //X509Certificate2 x509 = new X509Certificate2(certificate.GetEncoded());
            //x509.FriendlyName = subjectName;

            X509Certificate2 x509 = new X509Certificate2(DotNetUtilities.ToX509Certificate(certificate));

            //x509.PrivateKey = dotNetPrivateKey; set private key for x509 is not supported for now
            x509.FriendlyName = subjectName;

            CaPrivateKey = issuerKeyPair.Private;
            CaPublicKey  = subjectKeyPair.Public;

            return(x509);
        }
Ejemplo n.º 8
0
        public static void GenerateRootCertificate(string subjectName, DateTime expireOnUtc, out string password, out string pemValue, out byte[] cerData, out byte[] pkcs12Data)
        {
            // Generating Random Numbers
            var randomGenerator = new CryptoApiRandomGenerator();
            var random          = new SecureRandom(randomGenerator);

            var kpgen = new RsaKeyPairGenerator();

            kpgen.Init(new KeyGenerationParameters(random, 2048));
            var subjectKeyPair = kpgen.GenerateKeyPair();

            var gen = new X509V3CertificateGenerator();

            var        certName = new X509Name("CN=" + subjectName);
            BigInteger serialNo = BigInteger.ProbablePrime(120, random);

            gen.SetSerialNumber(serialNo);

            gen.SetSubjectDN(certName);
            gen.SetIssuerDN(certName);

            gen.SetNotAfter(expireOnUtc);
            gen.SetNotBefore(DateTime.Now.Subtract(new TimeSpan(7, 0, 0, 0)));
            gen.SetSignatureAlgorithm("SHA256WithRSA");
            gen.SetPublicKey(subjectKeyPair.Public);

            var certificate = gen.Generate(subjectKeyPair.Private, random);

            var privateKeyPem       = new StringBuilder();
            var privateKeyPemWriter = new PemWriter(new StringWriter(privateKeyPem));

            privateKeyPemWriter.WriteObject(certificate);
            privateKeyPemWriter.WriteObject(subjectKeyPair.Private);
            privateKeyPemWriter.Writer.Flush();
            pemValue = privateKeyPem.ToString();

            PrivateKeyInfo info = PrivateKeyInfoFactory.CreatePrivateKeyInfo(subjectKeyPair.Private);
            var            x509 = X509CertificateHelper.GetCertificate(certificate.GetEncoded(), null, System.Security.Cryptography.X509Certificates.X509KeyStorageFlags.Exportable);
            var            seq  = (Asn1Sequence)Asn1Object.FromByteArray(info.PrivateKey.GetDerEncoded());

            if (seq.Count != 9)
            {
                throw new PemException("Malformed sequence in RSA private key.");
            }

            var rsa = new RsaPrivateKeyStructure(seq);
            RsaPrivateCrtKeyParameters rsaparams = new RsaPrivateCrtKeyParameters(
                rsa.Modulus, rsa.PublicExponent, rsa.PrivateExponent, rsa.Prime1, rsa.Prime2, rsa.Exponent1, rsa.Exponent2, rsa.Coefficient);

            RSAParameters rsaParameters = DotNetUtilities.ToRSAParameters(rsaparams);
            CspParameters cspParameters = new CspParameters();

            cspParameters.KeyContainerName = Guid.NewGuid().ToString(); // "MyKeyContainer";
            RSACryptoServiceProvider rsaKey = new RSACryptoServiceProvider(2048, cspParameters);

            rsaKey.ImportParameters(rsaParameters);

            x509.PrivateKey = rsaKey;

            // Generating Random Numbers
            var chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-()#$%^&@+=!";
            var rnd   = new Random();

            var result = new string(
                Enumerable.Repeat(chars, 15)
                .Select(s => s[rnd.Next(s.Length)])
                .ToArray());

            password = result;

            cerData    = x509.Export(System.Security.Cryptography.X509Certificates.X509ContentType.Cert);
            pkcs12Data = x509.Export(System.Security.Cryptography.X509Certificates.X509ContentType.Pfx, password);
        }
Ejemplo n.º 9
0
        public static (CertPrivateKey, BcCertificate) GenerateRsaCACertificate(string subjectName,
                                                                               int keyStrength = 2048)
        {
            // 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(Int64.MaxValue), random);

            certificateGenerator.SetSerialNumber(serialNumber);

            // Signature Algorithm
            const string signatureAlgorithm = "SHA256WithRSA";

#pragma warning disable CS0618 // Type or member is obsolete
            certificateGenerator.SetSignatureAlgorithm(signatureAlgorithm);
#pragma warning restore CS0618 // Type or member is obsolete

            // Issuer and Subject Name
            var subjectDN = new X509Name(subjectName);
            var issuerDN  = subjectDN;
            certificateGenerator.SetIssuerDN(issuerDN);
            certificateGenerator.SetSubjectDN(subjectDN);

            // Valid For
            var notBefore = DateTime.UtcNow.Date;
            var notAfter  = notBefore.AddYears(2);

            certificateGenerator.SetNotBefore(notBefore);
            certificateGenerator.SetNotAfter(notAfter);

            // Subject Public Key
            AsymmetricCipherKeyPair subjectKeyPair;
            var keyGenerationParameters = new KeyGenerationParameters(random, keyStrength);
            var keyPairGenerator        = new RsaKeyPairGenerator();
            keyPairGenerator.Init(keyGenerationParameters);
            subjectKeyPair = keyPairGenerator.GenerateKeyPair();

            certificateGenerator.SetPublicKey(subjectKeyPair.Public);

            // Generating the Certificate
            var issuerKeyPair = subjectKeyPair;

            // selfsign certificate
#pragma warning disable CS0618 // Type or member is obsolete
            var certificate = certificateGenerator.Generate(issuerKeyPair.Private, random);
#pragma warning restore CS0618 // Type or member is obsolete

            // var x509 = new System.Security.Cryptography.X509Certificates.X509Certificate2(certificate.GetEncoded());
            // // Add CA certificate to Root store
            // addCertToStore(cert, StoreName.Root, StoreLocation.CurrentUser);

            var key = new CertPrivateKey
            {
                KeyPair = issuerKeyPair,
            };

            return(key, certificate);
        }
Ejemplo n.º 10
0
        public override void PerformTest()
        {
            testSig(1, pub1, prv1, slt1a, msg1a, sig1a);
            testSig(2, pub1, prv1, slt1b, msg1b, sig1b);
            testSig(3, pub2, prv2, slt2a, msg2a, sig2a);
            testSig(4, pub2, prv2, slt2b, msg2b, sig2b);
            testSig(5, pub4, prv4, slt4a, msg4a, sig4a);
            testSig(6, pub4, prv4, slt4b, msg4b, sig4b);
            testSig(7, pub8, prv8, slt8a, msg8a, sig8a);
            testSig(8, pub8, prv8, slt8b, msg8b, sig8b);
            testSig(9, pub9, prv9, slt9a, msg9a, sig9a);
            testSig(10, pub9, prv9, slt9b, msg9b, sig9b);

            //
            // loop test
            //
            int failed = 0;

            byte[] data = new byte[DATA_LENGTH];

            SecureRandom random = new SecureRandom();


            RsaKeyParameters[] kprv = { prv1, prv2, prv4, prv8, prv9 };
            RsaKeyParameters[] kpub = { pub1, pub2, pub4, pub8, pub9 };

            for (int j = 0, i = 0; j < NUM_TESTS; j++, i++)
            {
                if (i == kprv.Length)
                {
                    i = 0;
                }

                if (!isProcessingOkay(kpub[i], kprv[i], data, random))
                {
                    failed++;
                }
            }

            if (failed != 0)
            {
                Fail("loop test failed - failures: " + failed);
            }

            //
            // key generation test
            //
            RsaKeyPairGenerator        pGen     = new RsaKeyPairGenerator();
            RsaKeyGenerationParameters genParam = new RsaKeyGenerationParameters(
                BigInteger.ValueOf(0x11), new SecureRandom(), 1024, 25);

            pGen.Init(genParam);
            failed = 0;

            for (int k = 0; k < NUM_TESTS_WITH_KEY_GENERATION; k++)
            {
                AsymmetricCipherKeyPair pair = pGen.GenerateKeyPair();

                for (int j = 0; j < NUM_TESTS; j++)
                {
                    if (!isProcessingOkay((RsaKeyParameters)pair.Public, (RsaKeyParameters)pair.Private, data, random))
                    {
                        failed++;
                    }
                }
            }

            if (failed != 0)
            {
                Fail("loop test with key generation failed - failures: " + failed);
            }
        }
Ejemplo n.º 11
0
        /// <summary>
        ///
        /// </summary>
        /// <remarks>Based on <see cref="http://www.fkollmann.de/v2/post/Creating-certificates-using-BouncyCastle.aspx"/></remarks>
        /// <param name="subjectName"></param>
        /// <returns></returns>
        public static void GenerateCertificate(string subjectName, DateTime expireOnUtc, byte[] issuingCertificate, string issuingCertificatePassword, out string password, out byte[] cerData, out byte[] pkcs12Data)
        {
            AsymmetricKeyParameter caPrivateKey;
            var caCert = ReadCertificateFromBytes(issuingCertificate, issuingCertificatePassword, out caPrivateKey);

            var caAuth    = new AuthorityKeyIdentifierStructure(caCert);
            var authKeyId = new AuthorityKeyIdentifier(caAuth.GetKeyIdentifier());

            // Generating Random Numbers
            var randomGenerator = new CryptoApiRandomGenerator();
            var random          = new SecureRandom(randomGenerator);

            var chars  = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-()#$%^&@+=!";
            var rnd    = new Random();
            var result = new string(
                Enumerable.Repeat(chars, 15)
                .Select(s => s[rnd.Next(s.Length)])
                .ToArray());

            password = result;

            var gen      = new X509V3CertificateGenerator();
            var certName = new X509Name("CN=" + subjectName);
            var serialNo = BigInteger.ProbablePrime(120, random);

            gen.SetSerialNumber(serialNo);
            gen.SetSubjectDN(certName);
            gen.SetIssuerDN(caCert.IssuerDN);

            // gen.SetIssuerUniqueID(caCert.IssuerUniqueID.GetBytes())

            gen.SetNotAfter(expireOnUtc);
            gen.SetNotBefore(DateTime.Now.Subtract(new TimeSpan(7, 0, 0, 0)));
            gen.SetSignatureAlgorithm("SHA256WithRSA"); //("MD5WithRSA");

            var kpgen = new RsaKeyPairGenerator();

            kpgen.Init(new KeyGenerationParameters(random, 2048)); // new SecureRandom(new CryptoApiRandomGenerator()), 2048));
            var subjectKeyPair = kpgen.GenerateKeyPair();

            gen.SetPublicKey(subjectKeyPair.Public);

            //gen.AddExtension(
            //    X509Extensions.ExtendedKeyUsage.Id,
            //    false,
            //    new ExtendedKeyUsage(new KeyPurposeID[] { KeyPurposeID.IdKPClientAuth, KeyPurposeID.IdKPServerAuth, KeyPurposeID.IdKPCodeSigning }));

            //1.3.6.1.5.5.7.3.1 = server authentication
            //1.3.6.1.5.5.7.3.2 = client authentication
            //1.3.6.1.5.5.7.3.3 = code signing

            var certificate = gen.Generate(caPrivateKey);

            PrivateKeyInfo info = PrivateKeyInfoFactory.CreatePrivateKeyInfo(subjectKeyPair.Private);

            // merge into X509Certificate2
            var x509 = X509CertificateHelper.GetCertificate(certificate.GetEncoded(), null, System.Security.Cryptography.X509Certificates.X509KeyStorageFlags.Exportable);
            var seq  = (Asn1Sequence)Asn1Object.FromByteArray(info.PrivateKey.GetDerEncoded());

            if (seq.Count != 9)
            {
                throw new PemException("Malformed sequence in RSA private key.");
            }

            var rsa = new RsaPrivateKeyStructure(seq);
            RsaPrivateCrtKeyParameters rsaparams = new RsaPrivateCrtKeyParameters(
                rsa.Modulus, rsa.PublicExponent, rsa.PrivateExponent, rsa.Prime1, rsa.Prime2, rsa.Exponent1, rsa.Exponent2, rsa.Coefficient);

            RSAParameters rsaParameters = DotNetUtilities.ToRSAParameters(rsaparams);
            CspParameters cspParameters = new CspParameters();

            cspParameters.KeyContainerName = Guid.NewGuid().ToString(); // "MyKeyContainer";
            RSACryptoServiceProvider rsaKey = new RSACryptoServiceProvider(2048, cspParameters);

            rsaKey.ImportParameters(rsaParameters);

            x509.PrivateKey = rsaKey;
            cerData         = x509.Export(System.Security.Cryptography.X509Certificates.X509ContentType.Cert);
            pkcs12Data      = x509.Export(System.Security.Cryptography.X509Certificates.X509ContentType.Pkcs12, password);
        }
Ejemplo n.º 12
0
        private void cmdOK_Click(object sender, EventArgs e)
        {
            X509V1CertificateGenerator certGen = new X509V1CertificateGenerator();

            IDictionary attrs = new Hashtable();

            attrs[X509Name.CN] = txtCN.Text;
            attrs[X509Name.O]  = txtCompany.Text;
            attrs[X509Name.C]  = txtCC.Text;
            attrs[X509Name.ST] = txtProvince.Text;
            attrs[X509Name.OU] = txtOU.Text;
            attrs[X509Name.L]  = txtCity.Text;



            IList ord = new ArrayList();

            ord.Add(X509Name.CN);
            ord.Add(X509Name.O);
            ord.Add(X509Name.C);
            ord.Add(X509Name.ST);
            ord.Add(X509Name.OU);
            ord.Add(X509Name.L);


            X509Name CN = new X509Name(ord, attrs);

            Org.BouncyCastle.X509.X509Certificate newCert;

            certGen.SetSerialNumber(BigInteger.ProbablePrime(120, new Random()));
            certGen.SetIssuerDN(CN);
            certGen.SetNotAfter(new DateTime(DT.Value.Year, DT.Value.Month, DT.Value.Day, 0, 0, 0, 0));
            certGen.SetNotBefore(DateTime.Now.Subtract(new TimeSpan(7, 0, 0, 0)));
            certGen.SetSubjectDN(CN);
            CryptoApiRandomGenerator randomGenerator = new CryptoApiRandomGenerator();

            SecureRandom            random;
            AsymmetricCipherKeyPair keypair;

            if (txtSPKI.Text == "")
            {
                RsaKeyPairGenerator keypairgen = new RsaKeyPairGenerator();
                keypairgen.Init(new KeyGenerationParameters(new SecureRandom(new CryptoApiRandomGenerator()), 2048));

                keypair = keypairgen.GenerateKeyPair();
                certGen.SetPublicKey(keypair.Public);
                random = new SecureRandom(randomGenerator);
                ISignatureFactory signatureFactory = new Asn1SignatureFactory("SHA256WITHRSA", keypair.Private, random);
                newCert = certGen.Generate(signatureFactory);
            }
            else
            {
                RsaPublicKeyStructure rsaPubStructure = RsaPublicKeyStructure.GetInstance(Asn1Object.FromByteArray(File.ReadAllBytes(txtSPKI.Text)));

                AsymmetricKeyParameter extpublickey = (AsymmetricKeyParameter)(new RsaKeyParameters(false, rsaPubStructure.Modulus, rsaPubStructure.PublicExponent));
                certGen.SetPublicKey(extpublickey);

                RsaKeyPairGenerator keypairgen = new RsaKeyPairGenerator();
                keypairgen.Init(new KeyGenerationParameters(new SecureRandom(new CryptoApiRandomGenerator()), 2048));
                keypair = keypairgen.GenerateKeyPair();
                random  = new SecureRandom(randomGenerator);
                ISignatureFactory signatureFactory = new Asn1SignatureFactory("SHA256WITHRSA", keypair.Private, random);
                newCert = certGen.Generate(signatureFactory);
            }


            byte[] PlainCer = newCert.GetEncoded();

            SaveFileDialog save = new SaveFileDialog();

            if (lstOutput.SelectedIndex == 0)
            {
                save.Filter     = "Certificate|*.cer";
                save.DefaultExt = ".cer";
                save.Title      = "Save CER file";
            }
            if (lstOutput.SelectedIndex == 1)
            {
                save.Filter     = "Certificate|*.der";
                save.DefaultExt = ".der";
                save.Title      = "Save DER file";
            }
            if (lstOutput.SelectedIndex == 2)
            {
                save.Filter     = "Certificate|*.p12";
                save.DefaultExt = ".p12";
                save.Title      = "Save P12 file";
            }
            if (save.ShowDialog(this) != System.Windows.Forms.DialogResult.OK)
            {
                return;
            }
            if (lstOutput.SelectedIndex == 0)
            {
                File.WriteAllBytes(save.FileName, PlainCer);
            }
            if (lstOutput.SelectedIndex == 1)
            {
                TextWriter txt  = new StreamWriter(save.FileName, false, Encoding.ASCII);
                PemWriter  text = new PemWriter(txt);
                text.WriteObject(newCert);
                txt.Close();
            }
            if (lstOutput.SelectedIndex == 2)
            {
                Pkcs12Store pkcs = new Pkcs12Store();
                pkcs.SetCertificateEntry(txtCN.Text, new X509CertificateEntry(newCert));
                AsymmetricKeyEntry keyentry = new AsymmetricKeyEntry(keypair.Private);
                pkcs.SetKeyEntry(txtCN.Text, keyentry, new[] { new X509CertificateEntry(newCert) });
                MemoryStream mem = new MemoryStream();
                pkcs.Save(mem, txtPassword.Text.ToCharArray(), random);
                PlainCer = newCert.GetEncoded();

                File.WriteAllBytes(save.FileName, mem.GetBuffer());
            }
            this.Close();
        }
Ejemplo n.º 13
0
        /// <summary>
        /// Creates a self signed application instance certificate.
        /// </summary>
        /// <param name="storeType">Type of certificate store (Directory) <see cref="CertificateStoreType"/>.</param>
        /// <param name="storePath">The store path (syntax depends on storeType).</param>
        /// <param name="password">The password to use to protect the certificate.</param>
        /// <param name="applicationUri">The application uri (created if not specified).</param>
        /// <param name="applicationName">Name of the application (optional if subjectName is specified).</param>
        /// <param name="subjectName">The subject used to create the certificate (optional if applicationName is specified).</param>
        /// <param name="domainNames">The domain names that can be used to access the server machine (defaults to local computer name if not specified).</param>
        /// <param name="keySize">Size of the key (1024, 2048 or 4096).</param>
        /// <param name="startTime">The start time.</param>
        /// <param name="lifetimeInMonths">The lifetime of the key in months.</param>
        /// <param name="hashSizeInBits">The hash size in bits.</param>
        /// <param name="isCA">if set to <c>true</c> then a CA certificate is created.</param>
        /// <param name="issuerCAKeyCert">The CA cert with the CA private key.</param>
        /// <returns>The certificate with a private key.</returns>
        public static X509Certificate2 CreateCertificate(
            string storeType,
            string storePath,
            string password,
            string applicationUri,
            string applicationName,
            string subjectName,
            IList <String> domainNames,
            ushort keySize,
            DateTime startTime,
            ushort lifetimeInMonths,
            ushort hashSizeInBits,
            bool isCA,
            X509Certificate2 issuerCAKeyCert)
        {
            if (issuerCAKeyCert != null)
            {
                if (!issuerCAKeyCert.HasPrivateKey)
                {
                    throw new NotSupportedException("Cannot sign with a CA certificate without a private key.");
                }

                throw new NotSupportedException("Signing with an issuer CA certificate is currently unsupported.");
            }

            // set default values.
            SetSuitableDefaults(
                ref applicationUri,
                ref applicationName,
                ref subjectName,
                ref domainNames,
                ref keySize,
                ref lifetimeInMonths,
                isCA);

            // cert generators
            SecureRandom random           = new SecureRandom();
            X509V3CertificateGenerator cg = new X509V3CertificateGenerator();

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

            cg.SetSerialNumber(serialNumber);

            // build name attributes
            var nameOids = new ArrayList();

            nameOids.Add(X509Name.DC);
            nameOids.Add(X509Name.CN);

            var nameValues = new ArrayList();

            nameValues.Add(domainNames[0]);
            nameValues.Add(subjectName);

            // self signed
            X509Name subjectDN = new X509Name(nameOids, nameValues);
            X509Name issuerDN  = subjectDN;

            cg.SetIssuerDN(issuerDN);
            cg.SetSubjectDN(subjectDN);

            // valid for
            cg.SetNotBefore(startTime);
            cg.SetNotAfter(startTime.AddMonths(lifetimeInMonths));

            // Private/Public Key
            AsymmetricCipherKeyPair subjectKeyPair;
            var keyGenerationParameters = new KeyGenerationParameters(random, keySize);
            var keyPairGenerator        = new RsaKeyPairGenerator();

            keyPairGenerator.Init(keyGenerationParameters);
            subjectKeyPair = keyPairGenerator.GenerateKeyPair();
            cg.SetPublicKey(subjectKeyPair.Public);

            // add extensions
            // Subject key identifier
            cg.AddExtension(X509Extensions.SubjectKeyIdentifier.Id, false,
                            new SubjectKeyIdentifier(SubjectPublicKeyInfoFactory.CreateSubjectPublicKeyInfo(subjectKeyPair.Public)));

            // Basic constraints
            cg.AddExtension(X509Extensions.BasicConstraints.Id, true, new BasicConstraints(isCA));

            // Authority Key identifier
            var issuerKeyPair      = subjectKeyPair;
            var issuerSerialNumber = serialNumber;

            cg.AddExtension(X509Extensions.AuthorityKeyIdentifier.Id, false,
                            new AuthorityKeyIdentifier(SubjectPublicKeyInfoFactory.CreateSubjectPublicKeyInfo(subjectKeyPair.Public),
                                                       new GeneralNames(new GeneralName(issuerDN)), issuerSerialNumber));

            if (!isCA)
            {
                // Key usage
                cg.AddExtension(X509Extensions.KeyUsage, true,
                                new KeyUsage(KeyUsage.DataEncipherment | KeyUsage.DigitalSignature |
                                             KeyUsage.NonRepudiation | KeyUsage.KeyCertSign | KeyUsage.KeyEncipherment));

                // Extended Key usage
                cg.AddExtension(X509Extensions.ExtendedKeyUsage, true,
                                new ExtendedKeyUsage(new List <DerObjectIdentifier>()
                {
                    new DerObjectIdentifier("1.3.6.1.5.5.7.3.1"), // server auth
                    new DerObjectIdentifier("1.3.6.1.5.5.7.3.2"), // client auth
                }));

                // subject alternate name
                cg.AddExtension(X509Extensions.SubjectAlternativeName, false,
                                new GeneralNames(new GeneralName[] {
                    new GeneralName(GeneralName.UniformResourceIdentifier, applicationUri),
                    new GeneralName(GeneralName.DnsName, domainNames[0])
                }));
            }
            else
            {
                // Key usage CA
                cg.AddExtension(X509Extensions.KeyUsage, true,
                                new KeyUsage(KeyUsage.CrlSign | KeyUsage.DigitalSignature | KeyUsage.KeyCertSign));
            }

            // sign certificate
            ISignatureFactory signatureFactory =
                new Asn1SignatureFactory((hashSizeInBits < 256) ? "SHA1WITHRSA" : "SHA256WITHRSA", subjectKeyPair.Private, random);

            Org.BouncyCastle.X509.X509Certificate x509 = cg.Generate(signatureFactory);

            // create pkcs12 store for cert and private key
            X509Certificate2 certificate = null;

            using (MemoryStream pfxData = new MemoryStream())
            {
                Pkcs12Store            pkcsStore = new Pkcs12StoreBuilder().Build();
                X509CertificateEntry[] chain     = new X509CertificateEntry[1];
                string passcode = "passcode";
                chain[0] = new X509CertificateEntry(x509);
                pkcsStore.SetKeyEntry(applicationName, new AsymmetricKeyEntry(subjectKeyPair.Private), chain);
                pkcsStore.Save(pfxData, passcode.ToCharArray(), random);

                // merge into X509Certificate2
                certificate = CreateCertificateFromPKCS12(pfxData.ToArray(), passcode);
            }

            Utils.Trace(Utils.TraceMasks.Security, "Created new certificate: {0}", certificate.Thumbprint);

            // add cert to the store.
            if (!String.IsNullOrEmpty(storePath))
            {
                ICertificateStore store = null;
                if (storeType == CertificateStoreType.X509Store)
                {
                    store = new X509CertificateStore();
                }
                else if (storeType == CertificateStoreType.Directory)
                {
                    store = new DirectoryCertificateStore();
                }
                else
                {
                    throw new ArgumentException("Invalid store type");
                }

                store.Open(storePath);
                store.Add(certificate);
                store.Close();
                store.Dispose();
            }

            // note: this cert has a private key!
            return(certificate);
        }
Ejemplo n.º 14
0
 private AsymmetricCipherKeyPair GenerateRsaKeyPair()
 {
     var keyPairGenerator = new RsaKeyPairGenerator();
     keyPairGenerator.Init(new KeyGenerationParameters(GetSecureRandom(), RsaKeySizeBits));
     return keyPairGenerator.GenerateKeyPair();
 }
Ejemplo n.º 15
0
        /// <summary>
        /// Generates a ca certificate
        /// </summary>
        /// <param name="privateKey">The CA private key used to sign certificates</param>
        /// <param name="base64EncodedCer">The cer file used to configure the browser</param>
        /// <returns></returns>
        public static void GenerateCACert(out string privateKey, out string base64EncodedCer)
        {
            string subjectName = CA_NAME;
            int    keyStrength = 1024;

            // 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(Int64.MaxValue), random);

            certificateGenerator.SetSerialNumber(serialNumber);


            // Issuer and Subject Name
            var subjectDN = new X509Name(subjectName);
            var issuerDN  = subjectDN;

            certificateGenerator.SetIssuerDN(issuerDN);
            certificateGenerator.SetSubjectDN(subjectDN);

            // Valid For
            var notBefore = DateTime.UtcNow.Date;
            var notAfter  = notBefore.AddYears(2);

            certificateGenerator.SetNotBefore(notBefore);
            certificateGenerator.SetNotAfter(notAfter);
            certificateGenerator.AddExtension(X509Extensions.BasicConstraints, true, new BasicConstraints(0));

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

            keyPairGenerator.Init(keyGenerationParameters);
            subjectKeyPair = keyPairGenerator.GenerateKeyPair();

            certificateGenerator.SetPublicKey(subjectKeyPair.Public);


            // Generating the Certificate
            var issuerKeyPair = subjectKeyPair;
            ISignatureFactory signatureFactory = new Asn1SignatureFactory("SHA256WithRSA", issuerKeyPair.Private, random);
            var certificate = certificateGenerator.Generate(signatureFactory);


            base64EncodedCer = String.Format("-----BEGIN CERTIFICATE-----\r\n{0}\r\n-----END CERTIFICATE-----",
                                             Convert.ToBase64String(certificate.GetEncoded()));

            //var x509 = new System.Security.Cryptography.X509Certificates.X509Certificate2(certificate.GetEncoded());
            //System.Security.Cryptography.X509Certificates.X509Certificate dotNetCert = DotNetUtilities.ToX509Certificate(certificate);
            //X509Certificate2 dotNetCert2 = new X509Certificate2(dotNetCert);
            // Add CA certificate to Root store
            //AddCertToStore(dotNetCert2, StoreName.Root, StoreLocation.LocalMachine);

            PrivateKeyInfo info = PrivateKeyInfoFactory.CreatePrivateKeyInfo(issuerKeyPair.Private);

            privateKey = Convert.ToBase64String(info.GetEncoded());
        }
Ejemplo n.º 16
0
        /// <summary>
        ///   Creates a new signing key pair
        /// </summary>
        /// <param name="name">The name of the key or zone</param>
        /// <param name="recordClass">The record class of the DnsKeyRecord</param>
        /// <param name="timeToLive">The TTL in seconds to the DnsKeyRecord</param>
        /// <param name="flags">The Flags of the DnsKeyRecord</param>
        /// <param name="protocol">The protocol version</param>
        /// <param name="algorithm">The key algorithm</param>
        /// <param name="keyStrength">The key strength or 0 for default strength</param>
        /// <returns></returns>
        public static DnsKeyRecord CreateSigningKey(DomainName name, RecordClass recordClass, int timeToLive, DnsKeyFlags flags, byte protocol, DnsSecAlgorithm algorithm, int keyStrength = 0)
        {
            byte[] privateKey;
            byte[] publicKey;

            switch (algorithm)
            {
            case DnsSecAlgorithm.RsaSha1:
            case DnsSecAlgorithm.RsaSha1Nsec3Sha1:
            case DnsSecAlgorithm.RsaSha256:
            case DnsSecAlgorithm.RsaSha512:
                if (keyStrength == 0)
                {
                    keyStrength = (flags == (DnsKeyFlags.Zone | DnsKeyFlags.SecureEntryPoint)) ? 2048 : 1024;
                }

                RsaKeyPairGenerator rsaKeyGen = new RsaKeyPairGenerator();
                rsaKeyGen.Init(new KeyGenerationParameters(_secureRandom, keyStrength));
                var rsaKey = rsaKeyGen.GenerateKeyPair();
                privateKey = PrivateKeyInfoFactory.CreatePrivateKeyInfo(rsaKey.Private).GetDerEncoded();
                var rsaPublicKey = (RsaKeyParameters)rsaKey.Public;
                var rsaExponent  = rsaPublicKey.Exponent.ToByteArrayUnsigned();
                var rsaModulus   = rsaPublicKey.Modulus.ToByteArrayUnsigned();

                int offset = 1;
                if (rsaExponent.Length > 255)
                {
                    publicKey = new byte[3 + rsaExponent.Length + rsaModulus.Length];
                    DnsMessageBase.EncodeUShort(publicKey, ref offset, (ushort)publicKey.Length);
                }
                else
                {
                    publicKey    = new byte[1 + rsaExponent.Length + rsaModulus.Length];
                    publicKey[0] = (byte)rsaExponent.Length;
                }
                DnsMessageBase.EncodeByteArray(publicKey, ref offset, rsaExponent);
                DnsMessageBase.EncodeByteArray(publicKey, ref offset, rsaModulus);
                break;

            case DnsSecAlgorithm.Dsa:
            case DnsSecAlgorithm.DsaNsec3Sha1:
                if (keyStrength == 0)
                {
                    keyStrength = 1024;
                }

                DsaParametersGenerator dsaParamsGen = new DsaParametersGenerator();
                dsaParamsGen.Init(keyStrength, 12, _secureRandom);
                DsaKeyPairGenerator dsaKeyGen = new DsaKeyPairGenerator();
                dsaKeyGen.Init(new DsaKeyGenerationParameters(_secureRandom, dsaParamsGen.GenerateParameters()));
                var dsaKey = dsaKeyGen.GenerateKeyPair();
                privateKey = PrivateKeyInfoFactory.CreatePrivateKeyInfo(dsaKey.Private).GetDerEncoded();
                var dsaPublicKey = (DsaPublicKeyParameters)dsaKey.Public;

                var dsaY = dsaPublicKey.Y.ToByteArrayUnsigned();
                var dsaP = dsaPublicKey.Parameters.P.ToByteArrayUnsigned();
                var dsaQ = dsaPublicKey.Parameters.Q.ToByteArrayUnsigned();
                var dsaG = dsaPublicKey.Parameters.G.ToByteArrayUnsigned();
                var dsaT = (byte)((dsaY.Length - 64) / 8);

                publicKey    = new byte[21 + 3 * dsaY.Length];
                publicKey[0] = dsaT;
                dsaQ.CopyTo(publicKey, 1);
                dsaP.CopyTo(publicKey, 21);
                dsaG.CopyTo(publicKey, 21 + dsaY.Length);
                dsaY.CopyTo(publicKey, 21 + 2 * dsaY.Length);
                break;

            case DnsSecAlgorithm.EccGost:
                ECDomainParameters gostEcDomainParameters = ECGost3410NamedCurves.GetByOid(CryptoProObjectIdentifiers.GostR3410x2001CryptoProA);

                var gostKeyGen = new ECKeyPairGenerator();
                gostKeyGen.Init(new ECKeyGenerationParameters(gostEcDomainParameters, _secureRandom));

                var gostKey = gostKeyGen.GenerateKeyPair();
                privateKey = PrivateKeyInfoFactory.CreatePrivateKeyInfo(gostKey.Private).GetDerEncoded();
                var gostPublicKey = (ECPublicKeyParameters)gostKey.Public;

                publicKey = new byte[64];

                gostPublicKey.Q.AffineXCoord.ToBigInteger().ToByteArrayUnsigned().CopyTo(publicKey, 32);
                gostPublicKey.Q.AffineYCoord.ToBigInteger().ToByteArrayUnsigned().CopyTo(publicKey, 0);

                publicKey = publicKey.Reverse().ToArray();
                break;

            case DnsSecAlgorithm.EcDsaP256Sha256:
            case DnsSecAlgorithm.EcDsaP384Sha384:
                int            ecDsaDigestSize;
                X9ECParameters ecDsaCurveParameter;

                if (algorithm == DnsSecAlgorithm.EcDsaP256Sha256)
                {
                    ecDsaDigestSize     = new Sha256Digest().GetDigestSize();
                    ecDsaCurveParameter = NistNamedCurves.GetByOid(SecObjectIdentifiers.SecP256r1);
                }
                else
                {
                    ecDsaDigestSize     = new Sha384Digest().GetDigestSize();
                    ecDsaCurveParameter = NistNamedCurves.GetByOid(SecObjectIdentifiers.SecP384r1);
                }

                ECDomainParameters ecDsaP384EcDomainParameters = new ECDomainParameters(
                    ecDsaCurveParameter.Curve,
                    ecDsaCurveParameter.G,
                    ecDsaCurveParameter.N,
                    ecDsaCurveParameter.H,
                    ecDsaCurveParameter.GetSeed());

                var ecDsaKeyGen = new ECKeyPairGenerator();
                ecDsaKeyGen.Init(new ECKeyGenerationParameters(ecDsaP384EcDomainParameters, _secureRandom));

                var ecDsaKey = ecDsaKeyGen.GenerateKeyPair();
                privateKey = PrivateKeyInfoFactory.CreatePrivateKeyInfo(ecDsaKey.Private).GetDerEncoded();
                var ecDsaPublicKey = (ECPublicKeyParameters)ecDsaKey.Public;

                publicKey = new byte[ecDsaDigestSize * 2];

                ecDsaPublicKey.Q.AffineXCoord.ToBigInteger().ToByteArrayUnsigned().CopyTo(publicKey, 0);
                ecDsaPublicKey.Q.AffineYCoord.ToBigInteger().ToByteArrayUnsigned().CopyTo(publicKey, ecDsaDigestSize);
                break;

            default:
                throw new NotSupportedException();
            }

            return(new DnsKeyRecord(name, recordClass, timeToLive, flags, protocol, algorithm, publicKey, privateKey));
        }
    /// <summary>
    /// Creates a self signed application instance certificate.
    /// </summary>
    /// <param name="storeType">Type of certificate store (Directory) <see cref="CertificateStoreType"/>.</param>
    /// <param name="storePath">The store path (syntax depends on storeType).</param>
    /// <param name="password">The password to use to protect the certificate.</param>
    /// <param name="applicationUri">The application uri (created if not specified).</param>
    /// <param name="applicationName">Name of the application (optional if subjectName is specified).</param>
    /// <param name="subjectName">The subject used to create the certificate (optional if applicationName is specified).</param>
    /// <param name="domainNames">The domain names that can be used to access the server machine (defaults to local computer name if not specified).</param>
    /// <param name="keySize">Size of the key (1024, 2048 or 4096).</param>
    /// <param name="startTime">The start time.</param>
    /// <param name="lifetimeInMonths">The lifetime of the key in months.</param>
    /// <param name="hashSizeInBits">The hash size in bits.</param>
    /// <param name="isCA">if set to <c>true</c> then a CA certificate is created.</param>
    /// <param name="issuerCAKeyCert">The CA cert with the CA private key.</param>
    /// <returns>The certificate with a private key.</returns>
    public static X509Certificate2 CreateCertificate(
        string storeType,
        string storePath,
        string password,
        string applicationUri,
        string applicationName,
        string subjectName,
        IList <String> domainNames,
        ushort keySize,
        DateTime startTime,
        ushort lifetimeInMonths,
        ushort hashSizeInBits,
        bool isCA = false,
        X509Certificate2 issuerCAKeyCert = null,
        byte[] publicKey = null)
    {
        if (issuerCAKeyCert != null)
        {
            if (!issuerCAKeyCert.HasPrivateKey)
            {
                throw new NotSupportedException("Cannot sign with a CA certificate without a private key.");
            }
        }

        if (publicKey != null && issuerCAKeyCert == null)
        {
            throw new NotSupportedException("Cannot use a public key without a CA certificate with a private key.");
        }

        // set default values.
        X509Name subjectDN = SetSuitableDefaults(
            ref applicationUri,
            ref applicationName,
            ref subjectName,
            ref domainNames,
            ref keySize,
            ref lifetimeInMonths);

        using (var cfrg = new CertificateFactoryRandomGenerator())
        {
            // cert generators
            SecureRandom random           = new SecureRandom(cfrg);
            X509V3CertificateGenerator cg = new X509V3CertificateGenerator();

            // Serial Number
            BigInteger serialNumber = BigIntegers.CreateRandomInRange(BigInteger.One, BigInteger.ValueOf(Int64.MaxValue), random);
            cg.SetSerialNumber(serialNumber);

            // subject and issuer DN
            X509Name issuerDN = null;
            if (issuerCAKeyCert != null)
            {
                issuerDN = new CertificateFactoryX509Name(issuerCAKeyCert.Subject);
            }
            else
            {
                // self signed
                issuerDN = subjectDN;
            }
            cg.SetIssuerDN(issuerDN);
            cg.SetSubjectDN(subjectDN);

            // valid for
            cg.SetNotBefore(startTime);
            cg.SetNotAfter(startTime.AddMonths(lifetimeInMonths));

            // set Private/Public Key
            AsymmetricKeyParameter subjectPublicKey;
            AsymmetricKeyParameter subjectPrivateKey;
            if (publicKey == null)
            {
                var keyGenerationParameters = new KeyGenerationParameters(random, keySize);
                var keyPairGenerator        = new RsaKeyPairGenerator();
                keyPairGenerator.Init(keyGenerationParameters);
                AsymmetricCipherKeyPair subjectKeyPair = keyPairGenerator.GenerateKeyPair();
                subjectPublicKey  = subjectKeyPair.Public;
                subjectPrivateKey = subjectKeyPair.Private;
            }
            else
            {
                // special case, if a cert is signed by CA, the private key of the cert is not needed
                subjectPublicKey  = PublicKeyFactory.CreateKey(publicKey);
                subjectPrivateKey = null;
            }
            cg.SetPublicKey(subjectPublicKey);

            // add extensions
            // Subject key identifier
            cg.AddExtension(X509Extensions.SubjectKeyIdentifier.Id, false,
                            new SubjectKeyIdentifier(SubjectPublicKeyInfoFactory.CreateSubjectPublicKeyInfo(subjectPublicKey)));

            // Basic constraints
            cg.AddExtension(X509Extensions.BasicConstraints.Id, true, new BasicConstraints(isCA));

            // Authority Key identifier references the issuer cert or itself when self signed
            AsymmetricKeyParameter issuerPublicKey;
            BigInteger             issuerSerialNumber;
            if (issuerCAKeyCert != null)
            {
                issuerPublicKey    = GetPublicKeyParameter(issuerCAKeyCert);
                issuerSerialNumber = GetSerialNumber(issuerCAKeyCert);
                if (startTime.AddMonths(lifetimeInMonths) > issuerCAKeyCert.NotAfter)
                {
                    cg.SetNotAfter(issuerCAKeyCert.NotAfter);
                }
            }
            else
            {
                issuerPublicKey    = subjectPublicKey;
                issuerSerialNumber = serialNumber;
            }

            cg.AddExtension(X509Extensions.AuthorityKeyIdentifier.Id, false,
                            new AuthorityKeyIdentifier(SubjectPublicKeyInfoFactory.CreateSubjectPublicKeyInfo(issuerPublicKey),
                                                       new GeneralNames(new GeneralName(issuerDN)), issuerSerialNumber));

            if (!isCA)
            {
                // Key usage
                cg.AddExtension(X509Extensions.KeyUsage, true,
                                new KeyUsage(KeyUsage.DataEncipherment | KeyUsage.DigitalSignature |
                                             KeyUsage.NonRepudiation | KeyUsage.KeyCertSign | KeyUsage.KeyEncipherment));

                // Extended Key usage
                cg.AddExtension(X509Extensions.ExtendedKeyUsage, true,
                                new ExtendedKeyUsage(new List <DerObjectIdentifier>()
                {
                    new DerObjectIdentifier("1.3.6.1.5.5.7.3.1"), // server auth
                    new DerObjectIdentifier("1.3.6.1.5.5.7.3.2"), // client auth
                }));

                // subject alternate name
                List <GeneralName> generalNames = new List <GeneralName>();
                generalNames.Add(new GeneralName(GeneralName.UniformResourceIdentifier, applicationUri));
                generalNames.AddRange(CreateSubjectAlternateNameDomains(domainNames));
                cg.AddExtension(X509Extensions.SubjectAlternativeName, false, new GeneralNames(generalNames.ToArray()));
            }
            else
            {
                // Key usage CA
                cg.AddExtension(X509Extensions.KeyUsage, true,
                                new KeyUsage(KeyUsage.CrlSign | KeyUsage.DigitalSignature | KeyUsage.KeyCertSign));
            }

            // sign certificate
            AsymmetricKeyParameter signingKey;
            if (issuerCAKeyCert != null)
            {
                // signed by issuer
                signingKey = GetPrivateKeyParameter(issuerCAKeyCert);
            }
            else
            {
                // self signed
                signingKey = subjectPrivateKey;
            }
            ISignatureFactory signatureFactory =
                new Asn1SignatureFactory(GetRSAHashAlgorithm(hashSizeInBits), signingKey, random);
            Org.BouncyCastle.X509.X509Certificate x509 = cg.Generate(signatureFactory);

            // convert to X509Certificate2
            X509Certificate2 certificate = null;
            if (subjectPrivateKey == null)
            {
                // create the cert without the private key
                certificate = new X509Certificate2(x509.GetEncoded());
            }
            else
            {
                // note: this cert has a private key!
                certificate = CreateCertificateWithPrivateKey(x509, null, subjectPrivateKey, random);
            }

            Utils.Trace(Utils.TraceMasks.Security, "Created new certificate: {0}", certificate.Thumbprint);

            // add cert to the store.
            if (!String.IsNullOrEmpty(storePath) && !String.IsNullOrEmpty(storeType))
            {
                using (ICertificateStore store = CertificateStoreIdentifier.CreateStore(storeType))
                {
                    if (store == null)
                    {
                        throw new ArgumentException("Invalid store type");
                    }

                    store.Open(storePath);
                    store.Add(certificate, password).Wait();
                    store.Close();
                }
            }

            return(certificate);
        }
    }
        /// <summary>
        /// Static method used to create a certificate and return as a .net object
        /// </summary>
        public X509Certificate2 Create(string name, DateTime start, DateTime end, string userPassword, bool addtoStore = false)
        {
            UserPassword = userPassword ?? String.Empty;
            // generate a key pair using RSA
            var generator = new RsaKeyPairGenerator();

            // keys have to be a minimum of 2048 bits for Azure
            generator.Init(new KeyGenerationParameters(new SecureRandom(new CryptoApiRandomGenerator()), 2048));
            KeyPair = generator.GenerateKeyPair();
            // get a copy of the private key
            AsymmetricKeyParameter privateKey = KeyPair.Private;

            // create the CN using the name passed in and create a unique serial number for the cert
            var        certName = new X509Name("CN=" + name);
            BigInteger serialNo = BigInteger.ProbablePrime(120, new Random());

            // start the generator and set CN/DN and serial number and valid period
            var x509Generator = new X509V3CertificateGenerator();

            x509Generator.SetSerialNumber(serialNo);
            x509Generator.SetSubjectDN(certName);
            x509Generator.SetIssuerDN(certName);
            x509Generator.SetNotBefore(start);
            x509Generator.SetNotAfter(end);
            // add the server authentication key usage
            var keyUsage = new KeyUsage(KeyUsage.KeyEncipherment);

            x509Generator.AddExtension(X509Extensions.KeyUsage, false, keyUsage.ToAsn1Object());
            var extendedKeyUsage = new ExtendedKeyUsage(new[] { KeyPurposeID.IdKPServerAuth });

            x509Generator.AddExtension(X509Extensions.ExtendedKeyUsage, true, extendedKeyUsage.ToAsn1Object());
            // algorithm can only be SHA1 ??
            x509Generator.SetSignatureAlgorithm("sha1WithRSA");

            // Set the key pair
            x509Generator.SetPublicKey(KeyPair.Public);
            X509Certificate certificate = x509Generator.Generate(KeyPair.Private);

            // export the certificate bytes
            byte[] certStream = DotNetUtilities.ToX509Certificate(certificate).Export(X509ContentType.Pkcs12, UserPassword);

            // build the key parameter and the certificate entry
            var keyEntry = new AsymmetricKeyEntry(privateKey);
            var entry    = new X509CertificateEntry(certificate);
            // build the PKCS#12 store to encapsulate the certificate
            var builder = new Pkcs12StoreBuilder();

            builder.SetUseDerEncoding(true);
            builder.SetCertAlgorithm(PkcsObjectIdentifiers.Sha1WithRsaEncryption);
            builder.SetKeyAlgorithm(PkcsObjectIdentifiers.Sha1WithRsaEncryption);
            builder.Build();
            // create a memorystream to hold the output
            var stream = new MemoryStream(10000);
            // create the individual store and set two entries for cert and key
            var store = new Pkcs12Store();

            store.SetCertificateEntry("Created by Fluent Management", entry);
            store.SetKeyEntry("Created by Fluent Management", keyEntry, new[] { entry });
            store.Save(stream, UserPassword.ToCharArray(), new SecureRandom());

            // Create the equivalent C# representation
            DerEncodedCertificate = new X509Certificate2(stream.GetBuffer(), userPassword, X509KeyStorageFlags.Exportable | X509KeyStorageFlags.PersistKeySet);

            // if specified then this add this certificate to the store
            if (addtoStore)
            {
                AddToMyStore(DerEncodedCertificate);
            }

            return(DerEncodedCertificate);
        }
Ejemplo n.º 19
0
        private void TestForHighByteError(string label, int keySizeBits)
        {
            // draw a key of the size asked
            BigInteger e = BigInteger.One.ShiftLeft(16).Add(BigInteger.One);

            IAsymmetricCipherKeyPairGenerator kpGen = new RsaKeyPairGenerator();

            kpGen.Init(new RsaKeyGenerationParameters(e, new SecureRandom(), keySizeBits, 100));

            AsymmetricCipherKeyPair kp = kpGen.GenerateKeyPair();

            IAsymmetricBlockCipher cipher = new OaepEncoding(new RsaEngine());

            // obtain a known good ciphertext
            cipher.Init(true, new ParametersWithRandom(kp.Public, new VecRand(seed)));
            byte[] m            = { 42 };
            byte[] c            = cipher.ProcessBlock(m, 0, m.Length);
            int    keySizeBytes = (keySizeBits + 7) / 8;

            if (c.Length != keySizeBytes)
            {
                Fail(label + " failed ciphertext size");
            }

            BigInteger n = ((RsaPrivateCrtKeyParameters)kp.Private).Modulus;

            // decipher
            cipher.Init(false, kp.Private);
            byte[] r = cipher.ProcessBlock(c, 0, keySizeBytes);
            if (r.Length != 1 || r[0] != 42)
            {
                Fail(label + " failed first decryption of test message");
            }

            // decipher again
            r = cipher.ProcessBlock(c, 0, keySizeBytes);
            if (r.Length != 1 || r[0] != 42)
            {
                Fail(label + " failed second decryption of test message");
            }

            // check hapazard incorrect ciphertexts
            for (int i = keySizeBytes * 8; --i >= 0;)
            {
                c[i / 8] ^= (byte)(1 << (i & 7));
                bool ko = true;
                try
                {
                    BigInteger cV = new BigInteger(1, c);

                    // don't pass in c if it will be rejected trivially
                    if (cV.CompareTo(n) < 0)
                    {
                        r = cipher.ProcessBlock(c, 0, keySizeBytes);
                    }
                    else
                    {
                        ko = false; // size errors are picked up at start
                    }
                }
                catch (InvalidCipherTextException)
                {
                    ko = false;
                }
                if (ko)
                {
                    Fail(label + " invalid ciphertext caused no exception");
                }
                c[i / 8] ^= (byte)(1 << (i & 7));
            }
        }
Ejemplo n.º 20
0
        /// <inheritdoc/>
        public async Task <Tuple <X509Certificate, RsaKeyParameters> > GetLocalCertificateAsync(ApplicationDescription applicationDescription, ILogger logger = null)
        {
            string applicationUri = applicationDescription.ApplicationUri;

            if (string.IsNullOrEmpty(applicationUri))
            {
                throw new ArgumentOutOfRangeException(nameof(applicationDescription), "Expecting ApplicationUri in the form of 'http://{hostname}/{appname}' -or- 'urn:{hostname}:{appname}'.");
            }
            string subjectName = null;
            string hostName    = null;
            string appName     = null;

            UriBuilder appUri = new UriBuilder(applicationUri);

            if (appUri.Scheme == "http" && !string.IsNullOrEmpty(appUri.Host))
            {
                var path = appUri.Path.Trim('/');
                if (!string.IsNullOrEmpty(path))
                {
                    hostName    = appUri.Host;
                    appName     = path;
                    subjectName = $"CN={appName},DC={hostName}";
                }
            }

            if (appUri.Scheme == "urn")
            {
                var parts = appUri.Path.Split(new[] { ':' }, 2);
                if (parts.Length == 2)
                {
                    hostName    = parts[0];
                    appName     = parts[1];
                    subjectName = $"CN={appName},DC={hostName}";
                }
            }

            if (subjectName == null)
            {
                throw new ArgumentOutOfRangeException(nameof(applicationDescription), "Expecting ApplicationUri in the form of 'http://{hostname}/{appname}' -or- 'urn:{hostname}:{appname}'.");
            }

            var crt = default(X509Certificate);
            var key = default(RsaKeyParameters);

            // Build 'own/certs' certificate store.
            var ownCerts     = new Org.BouncyCastle.Utilities.Collections.HashSet();
            var ownCertsInfo = new DirectoryInfo(Path.Combine(this.pkiPath, "own", "certs"));

            if (ownCertsInfo.Exists)
            {
                foreach (var info in ownCertsInfo.EnumerateFiles())
                {
                    using (var crtStream = info.OpenRead())
                    {
                        var c = this.certParser.ReadCertificate(crtStream);
                        if (c != null)
                        {
                            ownCerts.Add(c);
                        }
                    }
                }
            }

            IX509Store ownCertStore = X509StoreFactory.Create("Certificate/Collection", new X509CollectionStoreParameters(ownCerts));

            // Select the newest certificate that matches by subject name.
            var selector = new X509CertStoreSelector()
            {
                Subject = new X509Name(subjectName)
            };

            crt = ownCertStore.GetMatches(selector).OfType <X509Certificate>().OrderBy(c => c.NotBefore).LastOrDefault();
            if (crt != null)
            {
                // If certificate found, verify alt-name, and retrieve private key.
                var asn1OctetString = crt.GetExtensionValue(X509Extensions.SubjectAlternativeName);
                if (asn1OctetString != null)
                {
                    var          asn1Object = X509ExtensionUtilities.FromExtensionValue(asn1OctetString);
                    GeneralNames gns        = GeneralNames.GetInstance(asn1Object);
                    if (gns.GetNames().Any(n => n.TagNo == GeneralName.UniformResourceIdentifier && n.Name.ToString() == applicationUri))
                    {
                        var ki = new FileInfo(Path.Combine(this.pkiPath, "own", "private", $"{crt.SerialNumber}.key"));
                        if (ki.Exists)
                        {
                            using (var keyStream = new StreamReader(ki.OpenRead()))
                            {
                                var keyReader = new PemReader(keyStream);
                                var keyPair   = keyReader.ReadObject() as AsymmetricCipherKeyPair;
                                if (keyPair != null)
                                {
                                    key = keyPair.Private as RsaKeyParameters;
                                }
                            }
                        }
                    }
                }
            }

            // If certificate and key are found, return to caller.
            if (crt != null && key != null)
            {
                logger?.LogTrace($"Found certificate with subject alt name '{applicationUri}'.");
                return(new Tuple <X509Certificate, RsaKeyParameters>(crt, key));
            }

            if (!this.CreateLocalCertificateIfNotExist)
            {
                return(null);
            }

            // Create new certificate
            var subjectDN = new X509Name(subjectName);

            // Create a keypair.
            var kp = await Task.Run <AsymmetricCipherKeyPair>(() =>
            {
                RsaKeyPairGenerator kg = new RsaKeyPairGenerator();
                kg.Init(new KeyGenerationParameters(this.rng, 2048));
                return(kg.GenerateKeyPair());
            });

            key = kp.Private as RsaPrivateCrtKeyParameters;

            // Create a certificate.
            X509V3CertificateGenerator cg = new X509V3CertificateGenerator();
            var subjectSN = BigInteger.ProbablePrime(120, this.rng);

            cg.SetSerialNumber(subjectSN);
            cg.SetSubjectDN(subjectDN);
            cg.SetIssuerDN(subjectDN);
            cg.SetNotBefore(DateTime.Now.Date.ToUniversalTime());
            cg.SetNotAfter(DateTime.Now.Date.ToUniversalTime().AddYears(25));
            cg.SetPublicKey(kp.Public);

            cg.AddExtension(
                X509Extensions.BasicConstraints.Id,
                true,
                new BasicConstraints(false));

            cg.AddExtension(
                X509Extensions.SubjectKeyIdentifier.Id,
                false,
                new SubjectKeyIdentifier(SubjectPublicKeyInfoFactory.CreateSubjectPublicKeyInfo(kp.Public)));

            cg.AddExtension(
                X509Extensions.AuthorityKeyIdentifier.Id,
                false,
                new AuthorityKeyIdentifier(SubjectPublicKeyInfoFactory.CreateSubjectPublicKeyInfo(kp.Public), new GeneralNames(new GeneralName(subjectDN)), subjectSN));

            cg.AddExtension(
                X509Extensions.SubjectAlternativeName,
                false,
                new GeneralNames(new[] { new GeneralName(GeneralName.UniformResourceIdentifier, applicationUri), new GeneralName(GeneralName.DnsName, hostName) }));

            cg.AddExtension(
                X509Extensions.KeyUsage,
                true,
                new KeyUsage(KeyUsage.DataEncipherment | KeyUsage.DigitalSignature | KeyUsage.NonRepudiation | KeyUsage.KeyCertSign | KeyUsage.KeyEncipherment));

            cg.AddExtension(
                X509Extensions.ExtendedKeyUsage,
                true,
                new ExtendedKeyUsage(KeyPurposeID.IdKPClientAuth, KeyPurposeID.IdKPServerAuth));

            crt = cg.Generate(new Asn1SignatureFactory("SHA256WITHRSA", key, this.rng));

            logger?.LogTrace($"Created certificate with subject alt name '{applicationUri}'.");

            var keyInfo = new FileInfo(Path.Combine(this.pkiPath, "own", "private", $"{crt.SerialNumber}.key"));

            if (!keyInfo.Directory.Exists)
            {
                Directory.CreateDirectory(keyInfo.DirectoryName);
            }
            else if (keyInfo.Exists)
            {
                keyInfo.Delete();
            }

            using (var keystream = new StreamWriter(keyInfo.OpenWrite()))
            {
                var pemwriter = new PemWriter(keystream);
                pemwriter.WriteObject(key);
            }

            var crtInfo = new FileInfo(Path.Combine(this.pkiPath, "own", "certs", $"{crt.SerialNumber}.crt"));

            if (!crtInfo.Directory.Exists)
            {
                Directory.CreateDirectory(crtInfo.DirectoryName);
            }
            else if (crtInfo.Exists)
            {
                crtInfo.Delete();
            }

            using (var crtstream = new StreamWriter(crtInfo.OpenWrite()))
            {
                var pemwriter = new PemWriter(crtstream);
                pemwriter.WriteObject(crt);
            }

            return(new Tuple <X509Certificate, RsaKeyParameters>(crt, key));
        }
Ejemplo n.º 21
0
        /// <summary>
        /// Creates a cert with the connectionstring (token) and stores it in the given cert store.
        /// </summary>
        public async static Task WriteAsync(string name, string connectionString, string storeType, string storePath)
        {
            if (string.IsNullOrEmpty(connectionString))
            {
                throw new ArgumentException("Token not found in X509Store and no new token provided!");
            }

            SecureRandom random = new SecureRandom();
            KeyGenerationParameters keyGenerationParameters = new KeyGenerationParameters(random, 2048);
            RsaKeyPairGenerator keyPairGenerator = new RsaKeyPairGenerator();
            keyPairGenerator.Init(keyGenerationParameters);
            AsymmetricCipherKeyPair keys = keyPairGenerator.GenerateKeyPair();

            ArrayList nameOids = new ArrayList();
            nameOids.Add(X509Name.CN);
            ArrayList nameValues = new ArrayList();
            nameValues.Add(name);
            X509Name subjectDN = new X509Name(nameOids, nameValues);
            X509Name issuerDN = subjectDN;

            X509V3CertificateGenerator cg = new X509V3CertificateGenerator();
            cg.SetSerialNumber(BigIntegers.CreateRandomInRange(BigInteger.One, BigInteger.ValueOf(Int64.MaxValue), random));
            cg.SetIssuerDN(issuerDN);
            cg.SetSubjectDN(subjectDN);
            cg.SetNotBefore(DateTime.Now);
            cg.SetNotAfter(DateTime.Now.AddMonths(12));
            cg.SetPublicKey(keys.Public);
            cg.AddExtension(X509Extensions.KeyUsage, true, new KeyUsage(KeyUsage.DataEncipherment));

            // encrypt the token with the public key so only the owner of the assoc. private key can decrypt it and
            // "hide" it in the instruction code cert extension
            RSA rsa = RSA.Create();
            RSAParameters rsaParams = new RSAParameters();
            RsaKeyParameters keyParams = (RsaKeyParameters)keys.Public;

            rsaParams.Modulus = new byte[keyParams.Modulus.ToByteArrayUnsigned().Length];
            keyParams.Modulus.ToByteArrayUnsigned().CopyTo(rsaParams.Modulus, 0);

            rsaParams.Exponent = new byte[keyParams.Exponent.ToByteArrayUnsigned().Length];
            keyParams.Exponent.ToByteArrayUnsigned().CopyTo(rsaParams.Exponent, 0);

            rsa.ImportParameters(rsaParams);
            if (rsa != null)
            {
                byte[] bytes = rsa.Encrypt(Encoding.ASCII.GetBytes(connectionString), RSAEncryptionPadding.OaepSHA1);
                if (bytes != null)
                {
                    cg.AddExtension(X509Extensions.InstructionCode, false, bytes);
                }
                else
                {
                    throw new CryptographicException("Can not encrypt IoTHub security token using generated public key!");
                }
            }

            // sign the cert with the private key
            ISignatureFactory signatureFactory = new Asn1SignatureFactory("SHA256WITHRSA", keys.Private, random);
            Org.BouncyCastle.X509.X509Certificate x509 = cg.Generate(signatureFactory);

            // create a PKCS12 store for the cert and its private key
            X509Certificate2 certificate = null;
            using (MemoryStream pfxData = new MemoryStream())
            {
                Pkcs12StoreBuilder builder = new Pkcs12StoreBuilder();
                builder.SetUseDerEncoding(true);
                Pkcs12Store pkcsStore = builder.Build();
                X509CertificateEntry[] chain = new X509CertificateEntry[1];
                string passcode = Guid.NewGuid().ToString();
                chain[0] = new X509CertificateEntry(x509);
                pkcsStore.SetKeyEntry(name, new AsymmetricKeyEntry(keys.Private), chain);
                pkcsStore.Save(pfxData, passcode.ToCharArray(), random);

                // create X509Certificate2 object from PKCS12 file
                certificate = CertificateFactory.CreateCertificateFromPKCS12(pfxData.ToArray(), passcode);

                // handle each store type differently
                switch (storeType)
                {
                    case CertificateStoreType.Directory:
                        {
                            // Add to DirectoryStore
                            using (DirectoryCertificateStore store = new DirectoryCertificateStore())
                            {
                                store.Open(storePath);
                                X509CertificateCollection certificates = await store.Enumerate().ConfigureAwait(false);

                                // remove any existing cert with our name from the store
                                foreach (X509Certificate2 cert in certificates)
                                {
                                    if (cert.SubjectName.Decode(X500DistinguishedNameFlags.None | X500DistinguishedNameFlags.DoNotUseQuotes).Equals("CN=" + name, StringComparison.OrdinalIgnoreCase))
                                    {
                                        await store.Delete(cert.Thumbprint).ConfigureAwait(false);
                                    }
                                }

                                // add new one
                                await store.Add(certificate).ConfigureAwait(false);
                            }
                            break;
                        }
                    case CertificateStoreType.X509Store:
                        {
                            // Add to X509Store
                            using (X509Store store = new X509Store(storePath, StoreLocation.CurrentUser))
                            {
                                store.Open(OpenFlags.ReadWrite);

                                // remove any existing cert with our name from the store
                                foreach (X509Certificate2 cert in store.Certificates)
                                {
                                    if (cert.SubjectName.Decode(X500DistinguishedNameFlags.None | X500DistinguishedNameFlags.DoNotUseQuotes).Equals("CN=" + name, StringComparison.OrdinalIgnoreCase))
                                    {
                                        store.Remove(cert);
                                    }
                                }

                                // add new cert to store
                                try
                                {
                                    store.Add(certificate);
                                }
                                catch (Exception e)
                                {
                                    throw new Exception($"Not able to add cert to the requested store type '{storeType}' (exception message: '{e.Message}'.");
                                }
                            }
                            break;
                        }
                    default:
                        {
                            throw new Exception($"The requested store type '{storeType}' is not supported. Please change.");
                        }
                }
                return;
            }
        }
Ejemplo n.º 22
0
        // Only the ctor should be calling with isAuthority = true
        // if isAuthority, value for isMachineCert doesn't matter
        private X509CertificateContainer CreateCertificate(bool isAuthority, bool isMachineCert, X509Certificate signingCertificate, CertificateCreationSettings certificateCreationSettings)
        {
            if (certificateCreationSettings == null)
            {
                if (isAuthority)
                {
                    certificateCreationSettings = new CertificateCreationSettings();
                }
                else
                {
                    throw new Exception("Parameter certificateCreationSettings cannot be null when isAuthority is false");
                }
            }

            // Set to default cert creation settings if not set
            if (certificateCreationSettings.ValidityNotBefore == default(DateTime))
            {
                certificateCreationSettings.ValidityNotBefore = _defaultValidityNotBefore;
            }
            if (certificateCreationSettings.ValidityNotAfter == default(DateTime))
            {
                certificateCreationSettings.ValidityNotAfter = _defaultValidityNotAfter;
            }

            if (!isAuthority ^ (signingCertificate != null))
            {
                throw new ArgumentException("Either isAuthority == true or signingCertificate is not null");
            }
            string subject = certificateCreationSettings.Subject;

            // If certificateCreationSettings.SubjectAlternativeNames == null, then we should add exactly one SubjectAlternativeName == Subject
            // so that the default certificate generated is compatible with mainline scenarios
            // However, if certificateCreationSettings.SubjectAlternativeNames == string[0], then allow this as this is a legit scenario we want to test out
            if (certificateCreationSettings.SubjectAlternativeNames == null)
            {
                certificateCreationSettings.SubjectAlternativeNames = new string[1] {
                    subject
                };
            }

            string[] subjectAlternativeNames = certificateCreationSettings.SubjectAlternativeNames;

            if (!isAuthority && string.IsNullOrWhiteSpace(subject))
            {
                throw new ArgumentException("Certificate Subject must not be an empty string or only whitespace", "creationSettings.Subject");
            }

            EnsureInitialized();

            s_certGenerator.Reset();
            s_certGenerator.SetSignatureAlgorithm(_signatureAlthorithm);

            // Tag on the generation time to prevent caching of the cert CRL in Linux
            X509Name authorityX509Name = CreateX509Name(string.Format("{0} {1}", _authorityCanonicalName, DateTime.Now.ToString("s")));
            var      serialNum         = new BigInteger(64 /*sizeInBits*/, _random).Abs();

            var keyPair = isAuthority ? _authorityKeyPair : _keyPairGenerator.GenerateKeyPair();

            if (isAuthority)
            {
                s_certGenerator.SetIssuerDN(authorityX509Name);
                s_certGenerator.SetSubjectDN(authorityX509Name);

                var authorityKeyIdentifier = new AuthorityKeyIdentifier(
                    SubjectPublicKeyInfoFactory.CreateSubjectPublicKeyInfo(_authorityKeyPair.Public),
                    new GeneralNames(new GeneralName(authorityX509Name)),
                    serialNum);

                s_certGenerator.AddExtension(X509Extensions.AuthorityKeyIdentifier, false, authorityKeyIdentifier);
                s_certGenerator.AddExtension(X509Extensions.KeyUsage, false, new KeyUsage(X509KeyUsage.DigitalSignature | X509KeyUsage.KeyAgreement | X509KeyUsage.KeyCertSign | X509KeyUsage.KeyEncipherment | X509KeyUsage.CrlSign));
            }
            else
            {
                X509Name subjectName = CreateX509Name(subject);
                s_certGenerator.SetIssuerDN(PrincipalUtilities.GetSubjectX509Principal(signingCertificate));
                s_certGenerator.SetSubjectDN(subjectName);

                s_certGenerator.AddExtension(X509Extensions.AuthorityKeyIdentifier, false, new AuthorityKeyIdentifierStructure(_authorityKeyPair.Public));
                s_certGenerator.AddExtension(X509Extensions.KeyUsage, false, new KeyUsage(X509KeyUsage.DigitalSignature | X509KeyUsage.KeyAgreement | X509KeyUsage.KeyEncipherment));
            }

            s_certGenerator.AddExtension(X509Extensions.SubjectKeyIdentifier, false, new SubjectKeyIdentifierStructure(keyPair.Public));

            s_certGenerator.SetSerialNumber(serialNum);
            s_certGenerator.SetNotBefore(certificateCreationSettings.ValidityNotBefore);
            s_certGenerator.SetNotAfter(certificateCreationSettings.ValidityNotAfter);
            s_certGenerator.SetPublicKey(keyPair.Public);

            s_certGenerator.AddExtension(X509Extensions.BasicConstraints, true, new BasicConstraints(isAuthority));
            s_certGenerator.AddExtension(X509Extensions.ExtendedKeyUsage, false, new ExtendedKeyUsage(KeyPurposeID.IdKPServerAuth, KeyPurposeID.IdKPClientAuth));

            if (!isAuthority)
            {
                if (isMachineCert)
                {
                    List <Asn1Encodable> subjectAlternativeNamesAsAsn1EncodableList = new List <Asn1Encodable>();

                    // All endpoints should also be in the Subject Alt Names
                    for (int i = 0; i < subjectAlternativeNames.Length; i++)
                    {
                        if (!string.IsNullOrWhiteSpace(subjectAlternativeNames[i]))
                        {
                            // Machine certs can have additional DNS names
                            subjectAlternativeNamesAsAsn1EncodableList.Add(new GeneralName(GeneralName.DnsName, subjectAlternativeNames[i]));
                        }
                    }

                    s_certGenerator.AddExtension(X509Extensions.SubjectAlternativeName, true, new DerSequence(subjectAlternativeNamesAsAsn1EncodableList.ToArray()));
                }
                else
                {
                    if (subjectAlternativeNames.Length > 1)
                    {
                        var subjectAlternativeNamesAsAsn1EncodableList = new Asn1EncodableVector();

                        // Only add a SAN for the user if there are any
                        for (int i = 1; i < subjectAlternativeNames.Length; i++)
                        {
                            if (!string.IsNullOrWhiteSpace(subjectAlternativeNames[i]))
                            {
                                Asn1EncodableVector otherNames = new Asn1EncodableVector();
                                otherNames.Add(new DerObjectIdentifier(_upnObjectId));
                                otherNames.Add(new DerTaggedObject(true, 0, new DerUtf8String(subjectAlternativeNames[i])));

                                Asn1Object genName = new DerTaggedObject(false, 0, new DerSequence(otherNames));

                                subjectAlternativeNamesAsAsn1EncodableList.Add(genName);
                            }
                        }
                        s_certGenerator.AddExtension(X509Extensions.SubjectAlternativeName, true, new DerSequence(subjectAlternativeNamesAsAsn1EncodableList));
                    }
                }
            }

            if (isAuthority || certificateCreationSettings.IncludeCrlDistributionPoint)
            {
                var crlDistributionPoints = new DistributionPoint[1]
                {
                    new DistributionPoint(
                        new DistributionPointName(
                            new GeneralNames(
                                new GeneralName(
                                    GeneralName.UniformResourceIdentifier, string.Format("{0}", _crlUri, serialNum.ToString(radix: 16))))),
                        null,
                        null)
                };
                var revocationListExtension = new CrlDistPoint(crlDistributionPoints);
                s_certGenerator.AddExtension(X509Extensions.CrlDistributionPoints, false, revocationListExtension);
            }

            X509Certificate cert = s_certGenerator.Generate(_authorityKeyPair.Private, _random);

            switch (certificateCreationSettings.ValidityType)
            {
            case CertificateValidityType.Revoked:
                RevokeCertificateBySerialNumber(serialNum.ToString(radix: 16));
                break;

            case CertificateValidityType.Expired:
                break;

            default:
                EnsureCertificateIsValid(cert);
                break;
            }

            // For now, given that we don't know what format to return it in, preserve the formats so we have
            // the flexibility to do what we need to

            X509CertificateContainer container = new X509CertificateContainer();

            X509CertificateEntry[] chain = new X509CertificateEntry[1];
            chain[0] = new X509CertificateEntry(cert);

            Pkcs12Store store = new Pkcs12StoreBuilder().Build();

            store.SetKeyEntry(
                certificateCreationSettings.FriendlyName != null ? certificateCreationSettings.FriendlyName : string.Empty,
                new AsymmetricKeyEntry(keyPair.Private),
                chain);

            using (MemoryStream stream = new MemoryStream())
            {
                store.Save(stream, _password.ToCharArray(), _random);
                container.Pfx = stream.ToArray();
            }

            X509Certificate2 outputCert;

            if (isAuthority)
            {
                // don't hand out the private key for the cert when it's the authority
                outputCert = new X509Certificate2(cert.GetEncoded());
            }
            else
            {
                // Otherwise, allow encode with the private key. note that X509Certificate2.RawData will not provide the private key
                // you will have to re-export this cert if needed
                outputCert = new X509Certificate2(container.Pfx, _password, X509KeyStorageFlags.MachineKeySet | X509KeyStorageFlags.Exportable | X509KeyStorageFlags.PersistKeySet);
            }

            container.Subject             = subject;
            container.InternalCertificate = cert;
            container.Certificate         = outputCert;
            container.Thumbprint          = outputCert.Thumbprint;

            Trace.WriteLine("[CertificateGenerator] generated a certificate:");
            Trace.WriteLine(string.Format("    {0} = {1}", "isAuthority", isAuthority));
            if (!isAuthority)
            {
                Trace.WriteLine(string.Format("    {0} = {1}", "Signed by", signingCertificate.SubjectDN));
                Trace.WriteLine(string.Format("    {0} = {1}", "Subject (CN) ", subject));
                Trace.WriteLine(string.Format("    {0} = {1}", "Subject Alt names ", string.Join(", ", subjectAlternativeNames)));
                Trace.WriteLine(string.Format("    {0} = {1}", "Friendly Name ", certificateCreationSettings.FriendlyName));
            }
            Trace.WriteLine(string.Format("    {0} = {1}", "HasPrivateKey:", outputCert.HasPrivateKey));
            Trace.WriteLine(string.Format("    {0} = {1}", "Thumbprint", outputCert.Thumbprint));
            Trace.WriteLine(string.Format("    {0} = {1}", "CertificateValidityType", certificateCreationSettings.ValidityType));

            return(container);
        }
Ejemplo n.º 23
0
        private static void RsaKeyGeneratorTest()
        {
            //RSA密钥对的构造器
            RsaKeyPairGenerator keyGenerator = new RsaKeyPairGenerator();
            //RSA密钥构造器的参数
            RsaKeyGenerationParameters param = new RsaKeyGenerationParameters(
                Org.BouncyCastle.Math.BigInteger.ValueOf(3),
                new Org.BouncyCastle.Security.SecureRandom(),
                1024,   //密钥长度
                25);

            //用参数初始化密钥构造器
            keyGenerator.Init(param);
            //产生密钥对
            AsymmetricCipherKeyPair keyPair = keyGenerator.GenerateKeyPair();
            //获取公钥和私钥
            AsymmetricKeyParameter publicKey  = keyPair.Public;
            AsymmetricKeyParameter privateKey = keyPair.Private;

            if (((RsaKeyParameters)publicKey).Modulus.BitLength < 1024)
            {
                Console.WriteLine("failed key generation (1024) length test");
            }
            savetheKey(publicKey, privateKey);



            //一个测试……………………
            //输入,十六进制的字符串,解码为byte[]
            //string input = "4e6f77206973207468652074696d6520666f7220616c6c20676f6f64206d656e";
            //byte[] testData = Org.BouncyCastle.Utilities.Encoders.Hex.Decode(input);
            string input = "popozh RSA test";

            byte[] testData = Encoding.UTF8.GetBytes(input);
            //非对称加密算法,加解密用
            IAsymmetricBlockCipher engine = new RsaEngine();
            //公钥加密
            //从保存在本地的磁盘文件中读取公钥
            Asn1Object             aobject       = Asn1Object.FromStream(new FileStream(pubKeyFile, FileMode.Open, FileAccess.Read)); //a.puk??
            SubjectPublicKeyInfo   pubInfo       = SubjectPublicKeyInfo.GetInstance(aobject);
            AsymmetricKeyParameter testpublicKey = (RsaKeyParameters)PublicKeyFactory.CreateKey(pubInfo);
            FileStream             fs;

            engine.Init(true, testpublicKey);
            try
            {
                //Console.WriteLine("加密前:" + Convert.ToBase64String(testData) + Environment.NewLine);
                testData = engine.ProcessBlock(testData, 0, testData.Length);
                Console.WriteLine("加密完成!" + Environment.NewLine);
                fs = new FileStream(ecyFile, FileMode.Create, FileAccess.Write);
                fs.Write(testData, 0, testData.Length);
                fs.Close();
                Console.WriteLine("保存密文成功" + Environment.NewLine);
            }
            catch (Exception ex)
            {
                Console.WriteLine("failed - exception " + Environment.NewLine + ex.ToString());
            }
            //私钥解密
            //获取加密的私钥,进行解密,获得私钥
            fs = new FileStream(ecyFile, FileMode.Open, FileAccess.Read);
            byte[] anothertestdata = new byte[1024];
            fs.Read(anothertestdata, 0, anothertestdata.Length);
            fs.Close();
            Asn1Object aobj = Asn1Object.FromStream(new FileStream(priKeyFile, FileMode.Open, FileAccess.Read));   //a.pvk??
            EncryptedPrivateKeyInfo enpri = EncryptedPrivateKeyInfo.GetInstance(aobj);

            char[]                 password          = "******".ToCharArray();
            PrivateKeyInfo         priKey            = PrivateKeyInfoFactory.CreatePrivateKeyInfo(password, enpri); //解密
            AsymmetricKeyParameter anotherprivateKey = PrivateKeyFactory.CreateKey(priKey);                         //私钥

            engine.Init(false, anotherprivateKey);
            try
            {
                anothertestdata = engine.ProcessBlock(anothertestdata, 0, testData.Length);
                Console.WriteLine("解密后密文为:" + Encoding.UTF8.GetString(anothertestdata) + Environment.NewLine);
            }
            catch (Exception e)
            {
                Console.WriteLine("failed - exception " + e.ToString());
            }

            Console.Read();
        }
        /// <summary>
        ///     Generates the certificate.
        /// </summary>
        /// <param name="subjectName">Name of the subject.</param>
        /// <param name="issuerName">Name of the issuer.</param>
        /// <param name="validFrom">The valid from.</param>
        /// <param name="validTo">The valid to.</param>
        /// <param name="keyStrength">The key strength.</param>
        /// <param name="signatureAlgorithm">The signature algorithm.</param>
        /// <param name="issuerPrivateKey">The issuer private key.</param>
        /// <param name="hostName">The host name</param>
        /// <returns>X509Certificate2 instance.</returns>
        /// <exception cref="PemException">Malformed sequence in RSA private key</exception>
        private static X509Certificate2 generateCertificate(string hostName,
                                                            string subjectName,
                                                            string issuerName, DateTime validFrom,
                                                            DateTime validTo, int keyStrength       = 2048,
                                                            string signatureAlgorithm               = "SHA256WithRSA",
                                                            AsymmetricKeyParameter issuerPrivateKey = null)
        {
            // Generating Random Numbers
            var randomGenerator = new CryptoApiRandomGenerator();
            var secureRandom    = new SecureRandom(randomGenerator);

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

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

            certificateGenerator.SetSerialNumber(serialNumber);

            // Issuer and Subject Name
            var subjectDn = new X509Name(subjectName);
            var issuerDn  = new X509Name(issuerName);

            certificateGenerator.SetIssuerDN(issuerDn);
            certificateGenerator.SetSubjectDN(subjectDn);

            certificateGenerator.SetNotBefore(validFrom);
            certificateGenerator.SetNotAfter(validTo);

            if (hostName != null)
            {
                // add subject alternative names
                var subjectAlternativeNames = new Asn1Encodable[] { new GeneralName(GeneralName.DnsName, hostName) };

                var subjectAlternativeNamesExtension = new DerSequence(subjectAlternativeNames);
                certificateGenerator.AddExtension(X509Extensions.SubjectAlternativeName.Id, false,
                                                  subjectAlternativeNamesExtension);
            }

            // Subject Public Key
            var keyGenerationParameters = new KeyGenerationParameters(secureRandom, keyStrength);
            var keyPairGenerator        = new RsaKeyPairGenerator();

            keyPairGenerator.Init(keyGenerationParameters);
            var subjectKeyPair = keyPairGenerator.GenerateKeyPair();

            certificateGenerator.SetPublicKey(subjectKeyPair.Public);

            // Set certificate intended purposes to only Server Authentication
            certificateGenerator.AddExtension(X509Extensions.ExtendedKeyUsage.Id, false,
                                              new ExtendedKeyUsage(KeyPurposeID.IdKPServerAuth));
            if (issuerPrivateKey == null)
            {
                certificateGenerator.AddExtension(X509Extensions.BasicConstraints.Id, true, new BasicConstraints(true));
            }

            var signatureFactory = new Asn1SignatureFactory(signatureAlgorithm,
                                                            issuerPrivateKey ?? subjectKeyPair.Private, secureRandom);

            // Self-sign the certificate
            var certificate = certificateGenerator.Generate(signatureFactory);

            // Corresponding private key
            var privateKeyInfo = PrivateKeyInfoFactory.CreatePrivateKeyInfo(subjectKeyPair.Private);

            var seq = (Asn1Sequence)Asn1Object.FromByteArray(privateKeyInfo.ParsePrivateKey().GetDerEncoded());

            if (seq.Count != 9)
            {
                throw new PemException("Malformed sequence in RSA private key");
            }

            var rsa       = RsaPrivateKeyStructure.GetInstance(seq);
            var rsaparams = new RsaPrivateCrtKeyParameters(rsa.Modulus, rsa.PublicExponent, rsa.PrivateExponent,
                                                           rsa.Prime1, rsa.Prime2, rsa.Exponent1,
                                                           rsa.Exponent2, rsa.Coefficient);

#if NET45
            // Set private key onto certificate instance
            var x509Certificate = new X509Certificate2(certificate.GetEncoded());
            x509Certificate.PrivateKey = DotNetUtilities.ToRSA(rsaparams);
#else
            var x509Certificate = withPrivateKey(certificate, rsaparams);
#endif

            if (!doNotSetFriendlyName)
            {
                try
                {
                    x509Certificate.FriendlyName = ProxyConstants.CNRemoverRegex.Replace(subjectName, string.Empty);
                }
                catch (PlatformNotSupportedException)
                {
                    doNotSetFriendlyName = true;
                }
            }

            return(x509Certificate);
        }
Ejemplo n.º 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);
        }
Ejemplo n.º 26
0
        private void button1_Click(object sender, EventArgs e)
        {
            string signatureAlgorithm = algtxt.Text;
            var    rsaGenerator       = new RsaKeyPairGenerator();
            var    randomGenerator    = new CryptoApiRandomGenerator();
            var    secureRandom       = new SecureRandom(randomGenerator);
            var    keyParameters      = new KeyGenerationParameters(secureRandom, 1024);

            rsaGenerator.Init(keyParameters);
            var keyPair    = rsaGenerator.GenerateKeyPair();
            var attributes = new System.Collections.Hashtable();

            attributes[X509Name.E]  = emailtxt.Text;  //设置dn信息的邮箱地址
            attributes[X509Name.CN] = towhomtxt.Text; //设置证书的用户,也就是颁发给谁
            attributes[X509Name.O]  = Issuertxt.Text; //设置证书的办法者
            attributes[X509Name.C]  = "Zh";           //证书的语言
            var ordering = new System.Collections.ArrayList();

            ordering.Add(X509Name.E);
            ordering.Add(X509Name.CN);
            ordering.Add(X509Name.O);
            ordering.Add(X509Name.C);
            var generater = new X509V3CertificateGenerator();

            //设置证书序列化号
            generater.SetSerialNumber(BigInteger.ProbablePrime(120, new Random()));
            //设置颁发者dn信息
            generater.SetIssuerDN(new X509Name(ordering, attributes));
            //设置证书生效时间
            generater.SetNotBefore(DateTime.Today.Subtract(new TimeSpan(1, 0, 0, 0)));
            //设置证书失效时间
            generater.SetNotAfter(DateTime.Today.AddDays(365));
            //设置接受者dn信息
            generater.SetSubjectDN(new X509Name(ordering, attributes));
            //设置证书的公钥
            generater.SetPublicKey(keyPair.Public);
            //设置证书的加密算法
            generater.SetSignatureAlgorithm(signatureAlgorithm);
            generater.AddExtension(X509Extensions.BasicConstraints,
                                   true,
                                   new BasicConstraints(false));
            generater.AddExtension(X509Extensions.AuthorityKeyIdentifier,
                                   true,
                                   new AuthorityKeyIdentifier(SubjectPublicKeyInfoFactory.CreateSubjectPublicKeyInfo(keyPair.Public)));
            // Key usage: Client authentication
            generater.AddExtension(X509Extensions.ExtendedKeyUsage.Id,
                                   false,
                                   new ExtendedKeyUsage(new System.Collections.ArrayList()
            {
                new DerObjectIdentifier("1.3.6.1.5.5.7.3.2")
            }));

            Castle = generater.Generate(keyPair.Private);
            var    store        = new Org.BouncyCastle.Pkcs.Pkcs12Store();
            string friendlyname = Castle.SubjectDN.ToString();
            var    ccentry      = new Org.BouncyCastle.Pkcs.X509CertificateEntry(Castle);

            store.SetCertificateEntry(friendlyname, ccentry);
            store.SetKeyEntry(friendlyname, new Org.BouncyCastle.Pkcs.AsymmetricKeyEntry(keyPair.Private), new[] { ccentry });

            certificate.Text = "-----BEGIN CERTIFICATE-----\r\n" + Convert.ToBase64String(Castle.GetEncoded()) + "\r\n-----END CERTIFICATE-----";

            string password = pswtxt.Text;

            Castlekey = keyPair.Private;
            var stream = new MemoryStream();

            store.Save(stream, password.ToCharArray(), secureRandom);
            nametxt.Text = Castle.IssuerDN.ToString();
            TextWriter textWriter = new StringWriter();
            PemWriter  pemWriter  = new PemWriter(textWriter);

            pemWriter.WriteObject(Castle.GetPublicKey());
            pemWriter.Writer.Flush();
            pubtxt.Text = textWriter.ToString();
            SaveFileDialog output = new SaveFileDialog();

            output.Filter           = "pfx file|*.pfx";
            output.RestoreDirectory = true;
            output.InitialDirectory = Environment.CurrentDirectory;
            output.FilterIndex      = 1;
            if (output.ShowDialog() == DialogResult.OK)
            {
                File.WriteAllBytes(output.FileName, stream.ToArray());
            }
            else
            {
                MessageBox.Show("pfx证书不导出!");
            }
            output.Filter = "cer file|*.cer";
            if (output.ShowDialog() == DialogResult.OK)
            {
                File.WriteAllText(output.FileName, certificate.Text);
            }
            else
            {
                MessageBox.Show("cer证书没导出!");
            }
        }
Ejemplo n.º 27
0
        public static X509Certificate2 GenerateSelfSignedCertificate(string subjectName, string issuerName, int keyStrength)
        {
            try
            {
                // Generating Random Numbers
                var randomGenerator = new VmpcRandomGenerator();
                var random          = new SecureRandom(randomGenerator);

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

                // Serial Number
                var serialNumber = BigInteger.ProbablePrime(128, new Random());
                certificateGenerator.SetSerialNumber(serialNumber);

                // Signature Algorithm
                var signatureAlgorithm = "SHA512WithRSA";
                certificateGenerator.SetSignatureAlgorithm(signatureAlgorithm);

                // Issuer and Subject Name
                var subjectDN = new X509Name(subjectName);
                var issuerDN  = new X509Name(issuerName);
                certificateGenerator.SetIssuerDN(issuerDN);
                certificateGenerator.SetSubjectDN(subjectDN);

                // Valid For
                var notBefore = DateTime.UtcNow.Date.AddYears(-1);
                var notAfter  = notBefore.AddYears(10);
                certificateGenerator.SetNotBefore(notBefore);
                certificateGenerator.SetNotAfter(notAfter);

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

                if (userKeyPair == null)
                {
                    userKeyPair = keyPairGenerator.GenerateKeyPair();
                }

                certificateGenerator.SetPublicKey(userKeyPair.Public);

                //Extented
                certificateGenerator.AddExtension(X509Extensions.SubjectKeyIdentifier, false,
                                                  new SubjectKeyIdentifierStructure(userKeyPair.Public));
                certificateGenerator.AddExtension(X509Extensions.AuthorityKeyIdentifier, false,
                                                  new AuthorityKeyIdentifier(SubjectPublicKeyInfoFactory
                                                                             .CreateSubjectPublicKeyInfo(userKeyPair.Public)));
                var valueData = Encoding.ASCII.GetBytes("Client");
                certificateGenerator.AddExtension("1.3.6.1.5.5.7.13.3", false, valueData);

                // Generating the Certificate
                var issuerKeyPair = userKeyPair;

                // selfsign certificate
                var certificate = certificateGenerator.Generate(userKeyPair.Private, random);

                // correcponding private key
                var info = PrivateKeyInfoFactory.CreatePrivateKeyInfo(userKeyPair.Private);

                // merge into X509Certificate2
                var x509 = new X509Certificate2(certificate.GetEncoded());

                var seq = (Asn1Sequence)Asn1Object.FromByteArray(info.ParsePrivateKey().GetDerEncoded());
                if (seq.Count != 9)
                {
                    throw new Exception("malformed sequence in RSA private key");
                }

                var rsa       = RsaPrivateKeyStructure.GetInstance(seq);
                var rsaparams = new RsaPrivateCrtKeyParameters(rsa.Modulus, rsa.PublicExponent, rsa.PrivateExponent,
                                                               rsa.Prime1, rsa.Prime2, rsa.Exponent1, rsa.Exponent2,
                                                               rsa.Coefficient);
#if NETCOREAPP2_0 || NETCOREAPP2_1
                x509 = x509.CopyWithPrivateKey(PemUtils.ToRSA(rsaparams));
#endif
                return(x509);
            }
            catch (Exception ex)
            {
                logger.Error(ex, $"The Method \"{nameof(GenerateSelfSignedCertificate)}\" has failed.");
                return(null);
            }
        }
Ejemplo n.º 28
0
        /// <summary>
        /// Generates a certificate signed by the CA
        /// </summary>
        /// <param name="subjectName"></param>
        /// <param name="issuerName"></param>
        /// <param name="issuerPrivKey"></param>
        /// <param name="keyStrength"></param>
        /// <returns></returns>
        public static X509Certificate2 GenerateCertificate(string subjectName, string issuerName, AsymmetricKeyParameter issuerPrivKey, int keyStrength = 1024)
        {
            // Generating Random Numbers
            CryptoApiRandomGenerator randomGenerator  = new CryptoApiRandomGenerator();
            SecureRandom             random           = new SecureRandom(randomGenerator);
            ISignatureFactory        signatureFactory = new Asn1SignatureFactory("SHA256WITHRSA", issuerPrivKey, random);
            // The Certificate Generator
            X509V3CertificateGenerator certificateGenerator = new X509V3CertificateGenerator();

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

            certificateGenerator.SetSerialNumber(serialNumber);


            // Issuer and Subject Name
            X509Name subjectDN = new X509Name(subjectName);
            X509Name issuerDN  = new X509Name(issuerName);

            certificateGenerator.SetIssuerDN(issuerDN);
            certificateGenerator.SetSubjectDN(subjectDN);

            // Valid For
            DateTime notBefore = DateTime.UtcNow.Date;
            DateTime notAfter  = notBefore.AddYears(2);

            certificateGenerator.SetNotBefore(notBefore);
            certificateGenerator.SetNotAfter(notAfter);

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

            keyPairGenerator.Init(keyGenerationParameters);
            subjectKeyPair = keyPairGenerator.GenerateKeyPair();

            certificateGenerator.SetPublicKey(subjectKeyPair.Public);
            // Generating the Certificate
            AsymmetricCipherKeyPair issuerKeyPair = subjectKeyPair;

            // selfsign certificate
            Org.BouncyCastle.X509.X509Certificate certificate = certificateGenerator.Generate(signatureFactory);

            // correcponding private key
            PrivateKeyInfo info = PrivateKeyInfoFactory.CreatePrivateKeyInfo(subjectKeyPair.Private);


            // merge into X509Certificate2
            X509Certificate2 x509 = new X509Certificate2(certificate.GetEncoded());

            Asn1Sequence seq = (Asn1Sequence)Asn1Object.FromByteArray(info.ParsePrivateKey().GetDerEncoded());

            if (seq.Count != 9)
            {
                throw new PemException("malformed sequence in RSA private key");
            }

            RsaPrivateKeyStructure     rsa       = RsaPrivateKeyStructure.GetInstance(seq);
            RsaPrivateCrtKeyParameters rsaparams = new RsaPrivateCrtKeyParameters(
                rsa.Modulus, rsa.PublicExponent, rsa.PrivateExponent, rsa.Prime1, rsa.Prime2, rsa.Exponent1, rsa.Exponent2, rsa.Coefficient);

            x509.PrivateKey = DotNetUtilities.ToRSA(rsaparams);
            return(x509);
        }
Ejemplo n.º 29
0
            public override void HandlePacket(LobbyClient client, ServerPacket packet)
            {
                var reader = packet.Reader;

                string realTag            = reader.ReadUnicodeString(50);
                uint   accountPremium     = reader.ReadUInt32();
                ulong  timeStamp          = reader.ReadUInt64();
                ulong  accountPermissions = reader.ReadUInt64();

                Log.Debug($"m_szRealTag = {realTag}");
                Log.Debug($"m_nAccountPremium = {accountPremium}");
                Log.Debug($"m_nTimestamp = {timeStamp}");
                Log.Debug($"m_nAccountPermissions = {accountPermissions}");

                for (int i = 0; i < 5; i++)
                {
                    Log.Debug($"m_nConfigFileVersion[{i}] = {reader.ReadInt32()}");
                }

                ushort voicePortMin   = reader.ReadUInt16();
                ushort voicePortMax   = reader.ReadUInt16();
                uint   voiceAccountId = reader.ReadUInt32();
                string voiceUsername  = reader.ReadASCIIString(17);
                string voiceKey       = reader.ReadASCIIString(17);

                Log.Debug($"m_nVoicePortMin = {voicePortMin}");
                Log.Debug($"m_nVoicePortMax = {voicePortMax}");
                Log.Debug($"m_nVoiceAccountID = {voiceAccountId}");
                Log.Debug($"m_szVoiceUsername = {voiceUsername}");
                Log.Debug($"m_szUnknownVoiceKey = {voiceKey}");

                // Read the server's public key
                RsaKeyParameters serverPub = WindowsRSA.ReadPublicKeyBlob(reader);

                // Read the rest of the packet data
                string countryCode = reader.ReadUnicodeString();
                string voiceURL    = reader.ReadASCIIString();

                Log.Debug($"m_nCountryCode = {countryCode}");
                Log.Debug($"m_szVoiceURL = {voiceURL}");

                // Create a new random RSA 1024 bit keypair for the client
                var generator = new RsaKeyPairGenerator();

                generator.Init(new KeyGenerationParameters(new SecureRandom(), 1024));
                AsymmetricCipherKeyPair clientKeyPair = generator.GenerateKeyPair();
                RsaKeyParameters        clientPub     = (RsaKeyParameters)clientKeyPair.Public;

                // Create the decryption engine for later
                client._clientDecryptEngine = new Pkcs1Encoding(new RsaEngine());
                client._clientDecryptEngine.Init(false, clientKeyPair.Private);

                // Put the client public key into the Microsoft Crypto API format
                byte[] clientPubBlob = WindowsRSA.CreatePublicKeyBlob(clientPub);

                // Create encryption engine with the server's public key
                client._serverEncryptEngine = new Pkcs1Encoding(new RsaEngine());
                client._serverEncryptEngine.Init(true, serverPub);

                // Encrypt the client key blob to send to the server
                byte[] encryptedClientKey = WindowsRSA.EncryptData(client._serverEncryptEngine, clientPubBlob);

                // Use the SRP key we calculated before
                client.SetEncryptionKey(client._srpKey);

                var keyExchange = new GC2LS_KEY_EXCHANGE(encryptedClientKey);

                client.SendPacket(keyExchange);

                client.OnLoginSuccess(client, null);
            }
Ejemplo n.º 30
0
        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        // ReSharper disable once InconsistentNaming
        public void Configure(IApplicationBuilder app, IApplicationLifetime applicationLifetime,
                              IHostingEnvironment env, ILoggerFactory loggerFactory)
        {
            // create default configuration
            var serverConfig = new SConfiguration();

            // bind configuration
            _fileConfig.Bind(serverConfig);

            // build context
            var context = SConfigurator.createContext(serverConfig);

            // import crypto keys
            var privateKeySource = context.configuration.privateKey;

            if (string.IsNullOrEmpty(privateKeySource))
            {
                // generate crypto keys
                var defaultKeySize = 2048;
                context.log.writeLine($"Private key not provided, generating new keypair of size {defaultKeySize}",
                                      SLogger.LogLevel.Information);
                var gen = new RsaKeyPairGenerator();
                gen.Init(new KeyGenerationParameters(new SecureRandom(), defaultKeySize));
                var keyPair        = gen.GenerateKeyPair();
                var privateKeyInfo = PrivateKeyInfoFactory.CreatePrivateKeyInfo(keyPair.Private);
                var publicKeyInfo  = SubjectPublicKeyInfoFactory.CreateSubjectPublicKeyInfo(keyPair.Public);
                privateKeySource = Convert.ToBase64String(privateKeyInfo.ToAsn1Object().GetDerEncoded());
                var encodedPublicKey = Convert.ToBase64String(publicKeyInfo.ToAsn1Object().GetDerEncoded());
                context.log.writeLine($"private key:\n{privateKeySource}", SLogger.LogLevel.Information);
                context.log.writeLine($"public key:\n{encodedPublicKey}", SLogger.LogLevel.Information);
            }

            // import key pair
            var privateKey =
                (RsaPrivateCrtKeyParameters)PrivateKeyFactory.CreateKey(Convert.FromBase64String(privateKeySource));

            context.configuration.crypto = DotNetUtilities.ToRSA(privateKey);
            context.log.writeLine($"Imported private key from configuration", SLogger.LogLevel.Information);

            context.log.writeLine("Server context created", SLogger.LogLevel.Information);

            // load persistent state
            SConfigurator.loadState(context, state_storage_database_file_name);
            context.log.writeLine($"Persistent state loaded from {state_storage_database_file_name}",
                                  SLogger.LogLevel.Information);

            // load database
            context.connectDatabase();
            context.log.writeLine($"Database connected", SLogger.LogLevel.Information);

            // register application stop handler
            // AssemblyLoadContext.Default.Unloading += (c) => OnUnload(context);
            applicationLifetime.ApplicationStopping.Register(() => onUnload(context));
            context.log.writeLine($"Application interrupt handler registered", SLogger.LogLevel.Information);

            // add aspnet developer exception page
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }

            // add aspnet logger
            if (env.IsDevelopment() && serverConfig.aspnetVerboseLogging)
            {
                loggerFactory.AddConsole(LogLevel.Information);
            }
            else
            {
                loggerFactory.AddConsole(LogLevel.Warning);
            }

            // add wwwroot/
            app.UseStaticFiles();

            // set up Nancy OWIN hosting
            app.UseOwin(x => x.UseNancy(options => {
                options.PassThroughWhenStatusCodesAre(
                    HttpStatusCode.NotFound,
                    HttpStatusCode.InternalServerError
                    );
                options.Bootstrapper = new AppBootstrapper(context);
            }));

            context.log.writeLine($"Web services mapped successfully", SLogger.LogLevel.Information);
        }