Beispiel #1
0
        public void Export(Container container, Stream output)
        {
            var rawCert    = container.GetRawCertificate();
            var privateKey = container.GetPrivateKey();

            var cert      = new X509CertificateParser().ReadCertificate(rawCert);
            var certEntry = new X509CertificateEntry(cert);

            string friendlyName = "alias";
            var    store        = new Pkcs12Store();

            store.SetCertificateEntry(friendlyName, certEntry);
            store.SetKeyEntry(friendlyName, new AsymmetricKeyEntry(privateKey), new[] { certEntry });

            var password = _password.ToCharArray();

            using (var ms = new MemoryStream()) {
                store.Save(ms, password, new SecureRandom());

                // Save дописывает в конец какой-то мусор
                ms.Position = 0;
                var    asn1   = new Asn1InputStream(ms);
                var    result = asn1.ReadObject();
                byte[] buf    = Pkcs12Utilities.ConvertToDefiniteLength(result.GetEncoded(), password);

                output.Write(buf, 0, buf.Length);
            }
        }
Beispiel #2
0
        public static X509Certificate2 GenerateSelfSignedCert()
        {
            var randomGenerator      = new CryptoApiRandomGenerator();
            var random               = new SecureRandom(randomGenerator);
            var certificateGenerator = new X509V3CertificateGenerator();
            var serialNumber         =
                BigIntegers.CreateRandomInRange(
                    BigInteger.One, BigInteger.ValueOf(Int64.MaxValue), random);

            certificateGenerator.SetSerialNumber(serialNumber);
            const string signatureAlgorithm = "SHA1WithRSA";

            certificateGenerator.SetSignatureAlgorithm(signatureAlgorithm);
            var subjectDN = new X509Name("CN=simpletorrent");
            var issuerDN  = subjectDN;

            certificateGenerator.SetIssuerDN(issuerDN);
            certificateGenerator.SetSubjectDN(subjectDN);
            var notBefore = DateTime.UtcNow.Date.AddHours(-24);
            var notAfter  = notBefore.AddYears(1000);

            certificateGenerator.SetNotBefore(notBefore);
            certificateGenerator.SetNotAfter(notAfter);
            const int strength = 4096;
            var       keyGenerationParameters = new KeyGenerationParameters(random, strength);

            var keyPairGenerator = new RsaKeyPairGenerator();

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

            certificateGenerator.SetPublicKey(subjectKeyPair.Public);

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

            var    store            = new Pkcs12Store();
            string friendlyName     = certificate.SubjectDN.ToString();
            var    certificateEntry = new X509CertificateEntry(certificate);

            store.SetCertificateEntry(friendlyName, certificateEntry);

            store.SetKeyEntry(friendlyName, new AsymmetricKeyEntry(subjectKeyPair.Private), new[] { certificateEntry });

            string password = "******";

            var stream = new MemoryStream();

            store.Save(stream, password.ToCharArray(), random);

            //mono bug #1660 fix -> convert to definite-length encoding
            byte[] pfx = Pkcs12Utilities.ConvertToDefiniteLength(stream.ToArray(), password.ToCharArray());

            var convertedCertificate =
                new X509Certificate2(
                    pfx, password,
                    X509KeyStorageFlags.PersistKeySet | X509KeyStorageFlags.Exportable);

            return(convertedCertificate);
        }
        private static byte[] CreatePfxFile(Org.BouncyCastle.X509.X509Certificate certificate, AsymmetricKeyParameter privateKey, string password = null)
        {
            // create certificate entry
            var    certEntry    = new X509CertificateEntry(certificate);
            string friendlyName = certificate.SubjectDN.ToString();

            // get bytes of private key.
            PrivateKeyInfo keyInfo = PrivateKeyInfoFactory.CreatePrivateKeyInfo(privateKey);

            byte[] keyBytes = keyInfo.ToAsn1Object().GetEncoded();

            var builder = new Pkcs12StoreBuilder();

            builder.SetUseDerEncoding(true);
            var store = builder.Build();

            // create store entry
            store.SetKeyEntry("", new AsymmetricKeyEntry(privateKey), new X509CertificateEntry[] { certEntry });
            byte[] pfxBytes = null;
            using (MemoryStream stream = new MemoryStream())
            {
                store.Save(stream, password?.ToCharArray(), new SecureRandom());
                pfxBytes = stream.ToArray();
            }
            var result = Pkcs12Utilities.ConvertToDefiniteLength(pfxBytes);

            return(result);
        }
Beispiel #4
0
        public static X509Certificate2 Load(Stream stream, string password)
        {
            var loadStore = new Pkcs12Store();

            loadStore.Load(stream, password?.ToCharArray());

            string keyAlias = loadStore.Aliases.Cast <string> ().FirstOrDefault(loadStore.IsKeyEntry);

            if (keyAlias == null)
            {
                throw new NotImplementedException("Alias");
            }

            var builder = new Pkcs12StoreBuilder();

            builder.SetUseDerEncoding(true);
            var saveStore = builder.Build();

            var chain = new X509CertificateEntry(loadStore.GetCertificate(keyAlias).Certificate);

            saveStore.SetCertificateEntry("Alias", chain);
            saveStore.SetKeyEntry("Alias", new AsymmetricKeyEntry((RsaPrivateCrtKeyParameters)loadStore.GetKey(keyAlias).Key), new [] { chain });

            using (var saveStream = new MemoryStream())
            {
                saveStore.Save(saveStream, new char[0], new SecureRandom());
                return(new X509Certificate2(Pkcs12Utilities.ConvertToDefiniteLength(saveStream.ToArray())));
            }
        }
        /// <summary>
        /// Genera el archivo pfx y devuelve el resultado con su contraseña
        /// </summary>
        /// <param name="rutaArchivoCer"></param>
        /// <param name="rutaArchivoKey"></param>
        /// <param name="secretArchivoKey"></param>
        /// <param name="rutaGuardado"></param>
        /// <param name="nombreArchivoPfx"></param>
        /// <param name="secretArchivoPfx"></param>
        /// <param name="conservarArchivo"></param>
        /// <returns>Pfx</returns>
        public static CfdiPfx generarArchivoPfx(string rutaArchivoCer, string rutaArchivoKey, string secretArchivoKey, string rutaGuardado, string nombreArchivoPfx, string secretArchivoPfx, Boolean conservarArchivo)
        {
            try
            {
                string rutaArchivoPfx = Path.Combine(rutaGuardado, nombreArchivoPfx);

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

                if (File.Exists(rutaArchivoPfx))
                {
                    File.Delete(rutaArchivoPfx);
                }

                X509Certificate2 certificado = new X509Certificate2(rutaArchivoCer);
                Org.BouncyCastle.X509.X509Certificate certificate = DotNetUtilities.FromX509Certificate(certificado);

                byte[] bytesArchivoKey            = File.ReadAllBytes(rutaArchivoKey);
                AsymmetricKeyParameter privateKey = PrivateKeyFactory.DecryptKey(secretArchivoKey.ToCharArray(), bytesArchivoKey);

                var    certEntry    = new X509CertificateEntry(certificate);
                string friendlyName = certificate.SubjectDN.ToString();

                PrivateKeyInfo keyInfo  = PrivateKeyInfoFactory.CreatePrivateKeyInfo(privateKey);
                byte[]         keyBytes = keyInfo.ToAsn1Object().GetEncoded();

                var builder = new Pkcs12StoreBuilder();
                builder.SetUseDerEncoding(true);
                var store = builder.Build();

                store.SetKeyEntry("PrivateKeyAlias", new AsymmetricKeyEntry(privateKey), new X509CertificateEntry[] { certEntry });

                byte[] pfxBytes = null;

                using (MemoryStream stream = new MemoryStream())
                {
                    store.Save(stream, secretArchivoPfx.ToCharArray(), new SecureRandom());
                    pfxBytes = stream.ToArray(); // Este sirve para la cancelacion
                }

                var result = Pkcs12Utilities.ConvertToDefiniteLength(pfxBytes);

                if (conservarArchivo)
                {
                    File.WriteAllBytes(rutaArchivoPfx, result);
                }

                return(new CfdiPfx(result, secretArchivoPfx));
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
Beispiel #6
0
        public static X509Certificate2 LoadFromUnencryptedPEM(string pem)
        {
            //Extract certificate
            var pattern     = new Regex(@"^[-]{5}BEGIN CERTIFICATE[-]{5}(?<certificate>([^-]*))[-]{5}END CERTIFICATE[-]{5}", RegexOptions.Multiline);
            var pvk_pattern = new Regex(@"[-]{5}BEGIN(?<encrypted>( ENCRYPTED)?) PRIVATE KEY[-]{5}(?<key>([^-]*))[-]{5}END( ENCRYPTED)? PRIVATE KEY[-]{5}", RegexOptions.Multiline);

            if (!pattern.IsMatch(pem))
            {
                throw new ArgumentException("Certificate malformed. (No certitficates found)");
            }
            if (!pvk_pattern.IsMatch(pem))
            {
                throw new ArgumentException("Certificate malformed. (No private key found)");
            }

            //Read all certificates to a jagged byte array
            MatchCollection mc           = pattern.Matches(pem);
            var             certificates = new byte[mc.Count][];
            var             index        = 0;

            foreach (Match match in mc)
            {
                certificates[index] = Convert.FromBase64String(match.Groups["certificate"].ToString().Trim(Environment.NewLine.ToCharArray()));
                index++;
            }
            //If the private key is encrypted (check on "encrypted" group) then that need to be handled in future, probably never.
            Match  pvk_match = pvk_pattern.Match(pem);
            string pvk       = pvk_match.Groups["key"].ToString();

            var parser            = new X509CertificateParser();
            var parsedCertificate = parser.ReadCertificate(Combine(certificates));

            var builder = new Pkcs12StoreBuilder();

            builder.SetUseDerEncoding(true);
            var inputKeyStore = builder.Build();

            inputKeyStore.SetCertificateEntry("Alias", new X509CertificateEntry(parsedCertificate));
            inputKeyStore.SetKeyEntry("Alias", new AsymmetricKeyEntry((RsaPrivateCrtKeyParameters)PrivateKeyFactory.CreateKey(Convert.FromBase64String(pvk))), new [] { new X509CertificateEntry(parsedCertificate) });

            string keyAlias = inputKeyStore.Aliases.Cast <string> ().FirstOrDefault(inputKeyStore.IsKeyEntry);

            if (keyAlias == null)
            {
                throw new InvalidKeyException("Alias");
            }

            using (var stream = new MemoryStream())
            {
                //There is no password
                inputKeyStore.Save(stream, new char[0], new SecureRandom());
                return(new X509Certificate2(Pkcs12Utilities.ConvertToDefiniteLength(stream.ToArray())));
            }
        }
Beispiel #7
0
        /// <summary>
        /// Loads the X.509 certificate with private key.
        /// </summary>
        /// <param name="options">The options used to load the certificate.</param>
        /// <returns>The certificate.</returns>
        public static X509Certificate2?GetCertificate(this FtpOptions options)
        {
            if (string.IsNullOrEmpty(options.Ftps.Certificate))
            {
                return(null);
            }

            var cert = new X509Certificate2(options.Ftps.Certificate, options.Ftps.Password);

            if (cert.HasPrivateKey)
            {
                return(cert);
            }

            cert.Dispose();

            var certCollection = new X509Certificate2Collection();

            certCollection.Import(options.Ftps.Certificate, options.Ftps.Password, X509KeyStorageFlags.Exportable);

            var passwordFinder = string.IsNullOrEmpty(options.Ftps.Password)
                ? (IPasswordFinder?)null
                : new BcStaticPassword(options.Ftps.Password);

            AsymmetricKeyParameter keyParameter;

            using (var pkReader = File.OpenText(options.Ftps.PrivateKey))
            {
                keyParameter = (AsymmetricKeyParameter) new PemReader(pkReader, passwordFinder).ReadObject();
            }

            var store = new Pkcs12StoreBuilder()
                        .SetUseDerEncoding(true)
                        .Build();

            var chain = certCollection.Cast <X509Certificate2>()
                        .Select(DotNetUtilities.FromX509Certificate)
                        .Select(x => new X509CertificateEntry(x))
                        .ToArray();

            store.SetKeyEntry("0", new AsymmetricKeyEntry(keyParameter), chain);

            byte[] data;
            using (var output = new MemoryStream())
            {
                store.Save(output, Array.Empty <char>(), new SecureRandom());
                data = output.ToArray();
            }

            var result = Pkcs12Utilities.ConvertToDefiniteLength(data);

            return(new X509Certificate2(result));
        }
Beispiel #8
0
        internal byte[] CreatePfxContainer(X509Certificate cert, AsymmetricCipherKeyPair keys)
        {
            var certEntry = new X509CertificateEntry(cert);

            var pkcs12Store = new Pkcs12StoreBuilder()
                              .SetUseDerEncoding(true)
                              .Build();
            var keyEntry = new AsymmetricKeyEntry(keys.Private);

            pkcs12Store.SetKeyEntry("ServerInstance", keyEntry, new X509CertificateEntry[] { certEntry });

            using (MemoryStream stream = new MemoryStream())
            {
                pkcs12Store.Save(stream, null, new SecureRandom());
                var bytes = stream.ToArray();
                return(Pkcs12Utilities.ConvertToDefiniteLength(bytes));
            }
        }
Beispiel #9
0
        private static byte[] CreatePfxFile(X509Certificate certificate, AsymmetricKeyParameter privateKey, string name, string password)
        {
            var certEntry = new X509CertificateEntry(certificate);

            var builder = new Pkcs12StoreBuilder();

            builder.SetUseDerEncoding(true);
            var store = builder.Build();

            store.SetKeyEntry(name, new AsymmetricKeyEntry(privateKey), new X509CertificateEntry[] { certEntry });

            using MemoryStream stream = new MemoryStream();
            store.Save(stream, password.ToCharArray(), new SecureRandom());
            var pfxBytes = stream.ToArray();
            var result   = Pkcs12Utilities.ConvertToDefiniteLength(pfxBytes);

            return(result);
        }
Beispiel #10
0
        public static byte[] CreatePKCS12(X509Certificate certificate, AsymmetricKeyParameter privateKey, string password)
        {
            var builder = new Pkcs12StoreBuilder();

            builder.SetUseDerEncoding(true);
            var store = builder.Build();

            var certEntry = new X509CertificateEntry(certificate);

            store.SetKeyEntry("some_alias",
                              new AsymmetricKeyEntry(privateKey),
                              new X509CertificateEntry[] { certEntry });

            byte[] pfxBytes;
            using (MemoryStream stream = new MemoryStream()) {
                store.Save(stream, password.ToCharArray(), new SecureRandom());
                pfxBytes = stream.ToArray();
            }

            return(Pkcs12Utilities.ConvertToDefiniteLength(pfxBytes));
        }
        private byte[] CreatePfxContainer(X509Certificate certificate, AsymmetricCipherKeyPair keys)
        {
            var certEntry = new X509CertificateEntry(certificate);

            var pkcs12Store = new Pkcs12StoreBuilder()
                              .SetUseDerEncoding(true)
                              .Build();

            if (keys != null)
            {
                var keyEntry = new AsymmetricKeyEntry(keys.Private);
                pkcs12Store.SetKeyEntry("ServerInstance", keyEntry, new [] { certEntry });
            }
            using (MemoryStream stream = new MemoryStream())
            {
                pkcs12Store.Save(stream, string.Empty.ToCharArray(), new SecureRandom()); // linux will not like certs null password as they have no signature
                var bytes = stream.ToArray();
                return(Pkcs12Utilities.ConvertToDefiniteLength(bytes));

                return(bytes);
            }
        }
        /// <summary>
        /// Create pfx
        /// </summary>
        /// <param name="certificate"></param>
        /// <param name="privateKey"></param>
        /// <param name="password"></param>
        internal static byte[] ToPfx(this X509Certificate certificate,
                                     AsymmetricKeyParameter privateKey, string password = null)
        {
            var builder = new Pkcs12StoreBuilder();

            builder.SetUseDerEncoding(true);
            var store = builder.Build();

            // create store entry
            var friendlyName = certificate.SubjectDN.ToString();

            store.SetKeyEntry(friendlyName, new AsymmetricKeyEntry(privateKey),
                              new X509CertificateEntry[] {
                new X509CertificateEntry(certificate)
            });
            using (var stream = new MemoryStream()) {
                using (var cfrg = new RandomGeneratorAdapter()) {
                    store.Save(stream, (password ?? string.Empty).ToCharArray(),
                               new SecureRandom(cfrg));
                }
                return(Pkcs12Utilities.ConvertToDefiniteLength(stream.ToArray()));
            }
        }
Beispiel #13
0
        private byte[] CreatePfxFile(Org.BouncyCastle.X509.X509Certificate cert, AsymmetricKeyParameter privateKey, string password, string keyFriendlyName)
        {
            var certEntry    = new X509CertificateEntry(cert);
            var friendlyName = cert.SubjectDN.ToString();

            var keyInfo  = PrivateKeyInfoFactory.CreatePrivateKeyInfo(privateKey);
            var keyBytes = keyInfo.ToAsn1Object().GetEncoded();

            var builder = new Pkcs12StoreBuilder();

            builder.SetUseDerEncoding(true);
            var store = builder.Build();

            store.SetKeyEntry(keyFriendlyName, new AsymmetricKeyEntry(privateKey), new[] { certEntry });
            byte[] pfxBytes;

            using (var ms = new MemoryStream())
            {
                store.Save(ms, password.ToCharArray(), new SecureRandom());
                pfxBytes = ms.ToArray();
            }

            return(Pkcs12Utilities.ConvertToDefiniteLength(pfxBytes));
        }
Beispiel #14
0
        //
        // Summary:
        //     /// Method responsible for generate certificate. ///
        //
        // Parameters:
        //   request:
        //     The request param.
        //
        public CreateCertificateResult Generate(CreateCertificateCommand request)
        {
            AsymmetricKeyParameter caPrivateKey = null;

            var caCert = GenerateCACertificate("CN=MyROOTCA", ref caPrivateKey);


            SecureRandom random = new SecureRandom();

            RsaKeyPairGenerator keyPairGenerator = new RsaKeyPairGenerator();

            keyPairGenerator.Init(new KeyGenerationParameters(random, 2048));

            AsymmetricCipherKeyPair subjectKeyPair = keyPairGenerator.GenerateKeyPair();

            IDictionary issuerAttrs  = FactoryIssuerAttrs();
            IDictionary subjectAttrs = FactorySubjectAttrs(request);

            BigInteger serialNumber = BigInteger.ProbablePrime(120, new Random());

            X509V3CertificateGenerator certificateGenerator = new X509V3CertificateGenerator();

            certificateGenerator.SetSerialNumber(serialNumber);
            certificateGenerator.SetIssuerDN(new X509Name(new ArrayList(issuerAttrs.Keys), issuerAttrs));
            certificateGenerator.SetSubjectDN(new X509Name(new ArrayList(subjectAttrs.Keys), subjectAttrs));
            certificateGenerator.SetNotBefore(DateTime.UtcNow.Date);
            certificateGenerator.SetNotAfter(DateTime.UtcNow.Date.AddYears(3));
            certificateGenerator.SetPublicKey(subjectKeyPair.Public);

            certificateGenerator.AddExtension(X509Extensions.KeyUsage, true,
                                              new KeyUsage(KeyUsage.DigitalSignature | KeyUsage.KeyAgreement | KeyUsage.NonRepudiation));

            certificateGenerator.AddExtension(X509Extensions.ExtendedKeyUsage.Id, false,
                                              new ExtendedKeyUsage(new[] { KeyPurposeID.IdKPServerAuth }));

            GeneralNames subjectAltName = new GeneralNames(new GeneralName(GeneralName.DnsName, "SAN"));

            certificateGenerator.AddExtension(X509Extensions.SubjectAlternativeName, false, subjectAltName);

            Asn1SignatureFactory signatureFactory =
                new Asn1SignatureFactory(HashType.SHA256WithRSA.ToString(), subjectKeyPair.Private);

            X509Certificate certificate = certificateGenerator.Generate(signatureFactory);

            X509CertificateEntry certEntry = new X509CertificateEntry(certificate);

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

            store.SetCertificateEntry(certificate.SubjectDN.ToString(), certEntry);
            store.SetKeyEntry(certificate.SubjectDN + "_key", new AsymmetricKeyEntry(subjectKeyPair.Private),
                              new[] { certEntry });

            MemoryStream p12Stream = new MemoryStream();

            store.Save(p12Stream, request.Pin.ToCharArray(), random);

            byte[] pfx = Pkcs12Utilities.ConvertToDefiniteLength(p12Stream.ToArray(), request.Pin.ToCharArray());

            X509Certificate2 x509Certificate2 =
                new X509Certificate2(pfx, request.Pin, X509KeyStorageFlags.PersistKeySet | X509KeyStorageFlags.Exportable);


            CreateCrl(caCert, caPrivateKey, serialNumber);

            return(FactoryResponse(x509Certificate2));
        }