Esempio n. 1
0
        public static Pkcs12Store CreateCert(string commonName, DateTime notBefore, DateTime notAfter,
                                             IEnumerable <string> dnsAltNames, IEnumerable <string> ipAddressAltNames, Pkcs12Store signBy)
        {
            var keyPairGen = new RsaKeyPairGenerator();

            keyPairGen.Init(new KeyGenerationParameters(new SecureRandom(), 2048));

            var keyPair = keyPairGen.GenerateKeyPair();

            var certGenerator = new X509V3CertificateGenerator();

            certGenerator.SetSubjectDN(new X509Name("CN=" + commonName));
            if (signBy == null)
            {
                certGenerator.SetIssuerDN(new X509Name("CN=" + commonName));
            }
            else
            {
                certGenerator.SetIssuerDN(signBy.GetCertificate().SubjectDN);
            }

            certGenerator.SetSerialNumber(BigInteger.ProbablePrime(64, new Random()));
            certGenerator.SetNotBefore(notBefore);
            certGenerator.SetNotAfter(notAfter);
            certGenerator.SetPublicKey(keyPair.Public);

            if ((dnsAltNames?.Any() ?? false) || (ipAddressAltNames?.Any() ?? false))
            {
                var alternativeNames = new List <Asn1Encodable>();
                alternativeNames.AddRange(dnsAltNames?.Select(name => new GeneralName(GeneralName.DnsName, name)) ??
                                          Enumerable.Empty <Asn1Encodable>());
                alternativeNames.AddRange(ipAddressAltNames?.Select(ip => new GeneralName(GeneralName.IPAddress, ip)) ??
                                          Enumerable.Empty <Asn1Encodable>());

                certGenerator.AddExtension(
                    X509Extensions.SubjectAlternativeName,
                    false,
                    new DerSequence(alternativeNames.ToArray())
                    );
            }

            var signatureKeyPair = signBy != null
                ? new AsymmetricCipherKeyPair(signBy.GetCertificate().GetPublicKey(), signBy.GetKey())
                : keyPair;
            var signer      = new Asn1SignatureFactory("SHA256WITHRSA", signatureKeyPair.Private);
            var certificate = certGenerator.Generate(signer);

            return(ToPkcs12(certificate, keyPair.Private));
        }
        /// <summary>
        /// Extracts the cryptographic objects contained in a PFX file.
        /// </summary>
        /// <param name="input">A stream with the PFX.</param>
        /// <param name="unsecurePassword">The PFX password in clear-text.</param>
        /// <returns>
        /// The cryptographic objects contained in the specified PFX file.
        /// </returns>
        /// <exception cref="ArgumentNullException"><paramref name="input"/> is null.</exception>
        /// <exception cref="ArgumentException"><paramref name="input"/> is not readable.</exception>
        /// <exception cref="ArgumentNullException"><paramref name="unsecurePassword"/> is null.</exception>
        /// <exception cref="ArgumentException"><paramref name="unsecurePassword"/> is white space.</exception>
        public static ExtractedPfxFile ExtractCryptographicObjectsFromPfxFile(
            Stream input,
            string unsecurePassword)
        {
            new { input }.Must().NotBeNull();
            new { input.CanRead }.Must().BeTrue();
            new { unsecurePassword }.Must().NotBeNullNorWhiteSpace();

            var store   = new Pkcs12Store(input, unsecurePassword.ToCharArray());
            var aliases = store.Aliases;

            var certificateChain = new List <X509Certificate>();

            foreach (var alias in aliases)
            {
                var certEntry = store.GetCertificate(alias.ToString());
                certificateChain.Add(certEntry.Certificate);
            }

            var endUserCertificate = certificateChain.GetEndUserCertFromCertChain();
            var subjectAttributes  = endUserCertificate.GetX509SubjectAttributes();
            var storeKey           = store.GetKey(subjectAttributes[X509SubjectAttributeKind.CommonName]);
            var privateKey         = storeKey.Key;

            var result = new ExtractedPfxFile(certificateChain, privateKey);

            return(result);
        }
Esempio n. 3
0
        public static X509Certificate GetCertificateAndKeyFromBytes(byte[] certificateBytes, string password, out AsymmetricKeyEntry privateKey)
        {
            privateKey = null;
            MemoryStream certificateStream = new MemoryStream(certificateBytes);
            Pkcs12Store  certificateStore;

            try
            {
                certificateStore = new Pkcs12Store(certificateStream, password.ToCharArray());
            }
            catch (IOException)
            {
                return(null);
            }

            foreach (string alias in certificateStore.Aliases)
            {
                AsymmetricKeyEntry   key = certificateStore.GetKey(alias);
                X509CertificateEntry certificateEntry = certificateStore.GetCertificate(alias);
                X509Certificate      certificate      = certificateEntry.Certificate;
                if (key != null)
                {
                    privateKey = key;
                    return(certificate);
                }
            }
            return(null);
        }
Esempio n. 4
0
        private X509Certificate2 GetAsDotNet(string entryAlias, X509KeyStorageFlags flags)
        {
            Org.BouncyCastle.Pkcs.X509CertificateEntry certificateEntry = store.GetCertificate(entryAlias);
            if (store.IsKeyEntry(entryAlias))
            {
                //Get the org key entry
                AsymmetricKeyEntry orgKeyEntry = store.GetKey(entryAlias);

                //Copy it into a new key attribute with the windows CSP defined
                IDictionary newKeyEntryAttributes = new Hashtable();
                foreach (String attribute in orgKeyEntry.BagAttributeKeys)
                {
                    newKeyEntryAttributes.Add(attribute, orgKeyEntry[attribute]);
                }
                if (!newKeyEntryAttributes.Contains("1.3.6.1.4.1.311.17.1"))
                {
                    newKeyEntryAttributes.Add("1.3.6.1.4.1.311.17.1", new DerBmpString("Microsoft Enhanced RSA and AES Cryptographic Provider"));
                }
                AsymmetricKeyEntry newKeyEntry = new AsymmetricKeyEntry(orgKeyEntry.Key, newKeyEntryAttributes);

                //Make a new P12 in memory
                Pkcs12Store newP12 = new Pkcs12Store();
                newP12.SetKeyEntry(entryAlias, newKeyEntry, store.GetCertificateChain(entryAlias));
                MemoryStream buffer = new MemoryStream();
                newP12.Save(buffer, password.ToCharArray(), new SecureRandom());

                //Read this P12 as X509Certificate with private key
                return(new X509Certificate2(buffer.ToArray(), password, flags));
            }
            else
            {
                return(new X509Certificate2(certificateEntry.Certificate.GetEncoded()));
            }
        }
Esempio n. 5
0
        public static (AsymmetricKeyParameter PubKey, AsymmetricKeyParameter PrivKey) PKCS12ToAsymmetricCipherKeyPair(Pkcs12Store pkstore)
        {
            AsymmetricKeyParameter pub  = null;
            AsymmetricKeyParameter priv = null;

            foreach (string s in pkstore.Aliases.Cast <string>())
            {
                X509CertificateEntry entry = pkstore.GetCertificate(s);
                if (entry != null)
                {
                    pub = entry.Certificate.GetPublicKey();
                }
                AsymmetricKeyEntry kentry = pkstore.GetKey(s);
                if (kentry != null)
                {
                    priv = kentry.Key;
                }
            }

            if (pub == null)
            {
                throw new CryptoException("Certificate not found");
            }
            return(pub, priv);
        }
        static IList <Org.BouncyCastle.X509.X509Certificate> GetCertificatesToImport(byte[] pfxBytes, string password)
        {
            using (var memoryStream = new MemoryStream(pfxBytes))
            {
                var pkcs12Store = new Pkcs12Store(memoryStream, password?.ToCharArray() ?? "".ToCharArray());

                if (pkcs12Store.Count < 1)
                {
                    throw new Exception("No certificates were found in PFX");
                }

                var aliases = pkcs12Store.Aliases.Cast <string>().ToList();

                // Find the first bag which contains a private-key
                var keyAlias = aliases.FirstOrDefault(alias => pkcs12Store.IsKeyEntry(alias));

                if (keyAlias != null)
                {
                    return(pkcs12Store.GetCertificateChain(keyAlias).Select(x => x.Certificate).ToList());
                }

                return(new List <Org.BouncyCastle.X509.X509Certificate>
                {
                    pkcs12Store.GetCertificate(aliases.First()).Certificate
                });
            }
        }
Esempio n. 7
0
                private (string certificate, string key) TransformPfx(IPasswordFinder passwordFinder)
                {
                    var certOutput = new StringWriter();
                    var keyOutput  = new StringWriter();

                    using (var input = File.OpenRead(CertificatePath))
                    {
                        var certWriter = new PemWriter(certOutput);
                        var keyWriter  = new PemWriter(keyOutput);
                        var store      = new Pkcs12Store(input, passwordFinder.GetPassword());
                        foreach (string alias in store.Aliases)
                        {
                            var cert = store.GetCertificate(alias);
                            if (cert != null)
                            {
                                certWriter.WriteObject(cert.Certificate);
                            }

                            var key = store.GetKey(alias);
                            if (key != null && key.Key.IsPrivate)
                            {
                                keyWriter.WriteObject(key.Key);
                            }
                        }
                    }

                    return(certOutput.ToString(), keyOutput.ToString());
                }
        public static void WriteCertificateAsPem(byte[] rawBytes, string exportPassword, Stream s)
        {
            var a = new Pkcs12Store();

            a.Load(new MemoryStream(rawBytes), Array.Empty <char>());
            var entry = a.GetCertificate(a.Aliases.Cast <string>().First());
            var key   = a.Aliases.Cast <string>().Select(a.GetKey).First(x => x != null);

            using (var writer = new StreamWriter(s, Encoding.ASCII, 1024, leaveOpen: true))
            {
                var pw = new PemWriter(writer);
                pw.WriteObject(entry.Certificate);

                object privateKey;
                if (exportPassword != null)
                {
                    privateKey = new MiscPemGenerator(
                        key.Key,
                        "AES-128-CBC",
                        exportPassword.ToCharArray(),
                        CertificateUtils.GetSeededSecureRandom())
                                 .Generate();
                }
                else
                {
                    privateKey = key.Key;
                }
                pw.WriteObject(privateKey);

                writer.Flush();
            }
        }
        /// <summary>
        /// In windows 7 work with X509Certificate2 class properties like PrivateKey and PublicKey leads to start random UPD port listening.
        /// This method gets private key with help of Bouncy castle. It helps prevent UDP port starting
        /// </summary>
        /// <param name="filePath"></param>
        /// <returns></returns>
        public AsymmetricKeyParameter ExtractSigningKey(string filePath)
        {
            var pkcs    = new Pkcs12Store(File.Open(filePath, FileMode.Open), GetCertPassword().ToCharArray());
            var aliases = pkcs.Aliases;
            var name    = string.Empty;

            foreach (var a in aliases)
            {
                name = a.ToString();
                break;
            }
            if (String.IsNullOrEmpty(name))
            {
                throw new Exception("Can not retrieve certificate alias name from PFX file");
            }

            // get certificate
            var certEntry = pkcs.GetCertificate(name.ToString());

            if (certEntry == null)
            {
                throw new Exception("Can not get certificate from pfx file by alias name");
            }
            // get certificate private key
            var issuerKey = pkcs.GetKey(name.ToString()).Key;

            return(issuerKey);
        }
        /// <summary>
        /// Imports certificates and keys from a pkcs12-encoded stream.
        /// </summary>
        /// <remarks>
        /// Imports certificates and keys from a pkcs12-encoded stream.
        /// </remarks>
        /// <param name="stream">The raw certificate and key data.</param>
        /// <param name="password">The password to unlock the stream.</param>
        /// <exception cref="System.ArgumentNullException">
        /// <para><paramref name="stream"/> is <c>null</c>.</para>
        /// <para>-or-</para>
        /// <para><paramref name="password"/> is <c>null</c>.</para>
        /// </exception>
        public override void Import(Stream stream, string password)
        {
            if (stream == null)
            {
                throw new ArgumentNullException("stream");
            }

            if (password == null)
            {
                throw new ArgumentNullException("password");
            }

            var pkcs12 = new Pkcs12Store(stream, password.ToCharArray());

            foreach (string alias in pkcs12.Aliases)
            {
                if (pkcs12.IsKeyEntry(alias))
                {
                    var chain = pkcs12.GetCertificateChain(alias);
                    var entry = pkcs12.GetKey(alias);

                    for (int i = 0; i < chain.Length; i++)
                    {
                        certificates.Add(chain[i].Certificate);
                    }

                    keys.Add(chain[0].Certificate, entry.Key);
                }
                else if (pkcs12.IsCertificateEntry(alias))
                {
                    var entry = pkcs12.GetCertificate(alias);
                    certificates.Add(entry.Certificate);
                }
            }
        }
Esempio n. 11
0
        private void init(string aPfxFilePath, string aPassword)
        {
            FileStream         fin          = new FileStream(aPfxFilePath, FileMode.Open, FileAccess.Read);
            Pkcs12StoreBuilder storeBuilder = new Pkcs12StoreBuilder();
            Pkcs12Store        pkcs12Store  = storeBuilder.Build();

            pkcs12Store.Load(fin, aPassword.ToCharArray());
            fin.Close();
            IEnumerable aliases           = pkcs12Store.Aliases;
            IEnumerator aliasesEnumerator = aliases.GetEnumerator();

            while (aliasesEnumerator.MoveNext())
            {
                string alias = (string)aliasesEnumerator.Current;
                signingBouncyCert = pkcs12Store.GetCertificate(alias);
                X509Certificate x509Certificate    = signingBouncyCert.Certificate;
                ECertificate    cert               = new ECertificate(x509Certificate.GetEncoded());
                EKeyUsage       eKeyUsage          = cert.getExtensions().getKeyUsage();
                bool            isDigitalSignature = eKeyUsage.isDigitalSignature();
                if (isDigitalSignature)
                {
                    signingBouncyKeyEntry = pkcs12Store.GetKey(alias);
                    signingCertificate    = cert;
                    break;
                }
            }
        }
Esempio n. 12
0
        public static X509Certificate ReadCertFromFile(string strCertificatePath, string strCertificatePassword)
        {
            try
            {
                // Create file stream object to read certificate
                var keyStream = new FileStream(strCertificatePath, FileMode.Open, FileAccess.Read);

                // Read certificate using BouncyCastle component
                var inputKeyStore = new Pkcs12Store();
                inputKeyStore.Load(keyStream, strCertificatePassword.ToCharArray());

                //Close File stream
                keyStream.Close();

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

                // Read Key from Alieases
                if (keyAlias == null)
                {
                    throw new NotImplementedException("Alias");
                }

                //Read certificate into 509 format
                return((X509Certificate)inputKeyStore.GetCertificate(keyAlias).Certificate);
            }
            catch (Exception ex)
            {
                Console.WriteLine("So, you wanna make an exception huh! : " + ex.ToString());
                Console.ReadKey();
                return(null);
            }
        }
Esempio n. 13
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())));
            }
        }
Esempio n. 14
0
        /// <summary>
        /// Construct a CA object
        /// </summary>
        /// <param name="ConfigFile">Full pathname to config file</param>
        /// <param name="Password">Password for key file</param>
        public simpleCA(string ConfigFile, string Password)
        {
            this.configFile = ConfigFile;
            this.password   = Password.ToCharArray();

            // Read in the configuration
            XDocument config;

            if (XmlSigning.VerifyXmlFile(configFile))
            {
                config = XDocument.Load(configFile);
            }
            else
            {
                throw new GeneralSecurityException("Signature failed on CA config file");
            }

            XElement ca = config.Element("OSCA").Element("CA");

            this.name               = ca.Element("name").Value;
            this.type               = ca.Element("type").Value;
            this.dbFileLocation     = ca.Element("dbFileLocation").Value;
            this.publicKeyAlgorithm = ca.Element("publicKeyAlgorithm").Value;
            this.publicKeySize      = ca.Element("publicKeySize").Value;
            this.signatureAlgorithm = ca.Element("signatureAlgorithm").Value;
            this.fips140            = Convert.ToBoolean(ca.Element("fips140").Value);
            this.lastSerial         = ca.Element("lastSerial").Value;
            this.crlFileLocation    = ca.Element("crlFileLocation").Value;
            this.lastCRL            = ca.Element("lastCRL").Value;
            this.crlInterval        = Convert.ToDouble(ca.Element("crlInterval").Value);
            this.profilesLocation   = ca.Element("profilesLocation").Value;

            //Read in the private key and certificate
            MemoryStream p12stream = new MemoryStream(Convert.FromBase64String(ca.Element("caKey").Value));
            Pkcs12Store  p12       = new Pkcs12Store(p12stream, password);

            this.privateKey    = p12.GetKey(this.name).Key;
            this.caCertificate = p12.GetCertificate(this.name).Certificate;

            if (ca.Element("policyEnforcement") != null)
            {
                policyEnforcement = PolicyEnforcementFactory.initialise(caCertificate, ca.Element("policyEnforcement"));
            }

            // Create CspParameters to support XML signing
            cspParam = SysKeyManager.LoadCsp(privateKey);

            // Setup the Event Logger
            eventLog = new Logger(ca.Element("logFileLocation").Value, caCertificate, cspParam);

            // Check our certificate is valid
            // --- TODO

            // Log startup event
            logEvent(LogEvent.EventType.StartCA, "CA Started");

            // Expire any old certificates
            Database.ExpireCertificate(dbFileLocation, caCertificate, cspParam);
        }
Esempio n. 15
0
        public static string X509Certificate2ToPEM(X509Certificate2 cert)
        {
            try
            {
                if (cert.HasPrivateKey)
                {
                    byte[] pkcsarray = cert.Export(X509ContentType.Pkcs12);
                    if (pkcsarray.Length == 0)
                    {
                        throw new CryptoException("Empty PKCS12 Array");
                    }
                    X509Certificate        certout = null;
                    AsymmetricKeyParameter priv    = null;
                    using (MemoryStream ms = new MemoryStream(pkcsarray))
                    {
                        Pkcs12Store pkstore = new Pkcs12Store();
                        pkstore.Load(ms, new char[] { });
                        foreach (string s in pkstore.Aliases.Cast <string>())
                        {
                            X509CertificateEntry entry = pkstore.GetCertificate(s);
                            if (entry != null)
                            {
                                certout = entry.Certificate;
                            }
                            AsymmetricKeyEntry kentry = pkstore.GetKey(s);
                            if (kentry != null)
                            {
                                priv = kentry.Key;
                            }
                        }

                        if (certout == null)
                        {
                            throw new CryptoException("Certificate not found");
                        }
                    }

                    using (StringWriter sw = new StringWriter())
                    {
                        PemWriter pemWriter = new PemWriter(sw);
                        pemWriter.WriteObject(certout);
                        if (priv != null)
                        {
                            pemWriter.WriteObject(priv);
                        }
                        sw.Flush();
                        return(sw.ToString());
                    }
                }

                X509Certificate c = DotNetUtilities.FromX509Certificate(cert);
                return(DumpOnePEM(c, null));
                // return cert.Export(X509ContentType.SerializedCert).ToUTF8String();
            }
            catch (Exception e)
            {
                throw new CryptoException($"Unable to open pkcs12, wrong password?. {e.Message}", e);
            }
        }
        public CertContainer(Pkcs12Store privateKeyStore, params CertContainer[] issuerCerts)
        {
            string certAlias = GetCertAlias(privateKeyStore);

            this.PrivateKey  = privateKeyStore.GetKey(certAlias).Key;
            this.Certificate = privateKeyStore.GetCertificate(certAlias).Certificate;
            this.IssuerChain = issuerCerts ?? new CertContainer[0];
        }
Esempio n. 17
0
        public static void WriteCertificateAsPem(string name, byte[] rawBytes, string exportPassword, ZipArchive s)
        {
            var a = new Pkcs12Store();

            a.Load(new MemoryStream(rawBytes), Array.Empty <char>());

            X509CertificateEntry entry = null;
            AsymmetricKeyEntry   key   = null;

            foreach (var alias in a.Aliases)
            {
                var aliasKey = a.GetKey(alias.ToString());
                if (aliasKey != null)
                {
                    entry = a.GetCertificate(alias.ToString());
                    key   = aliasKey;
                    break;
                }
            }

            if (entry == null)
            {
                throw new InvalidOperationException("Could not find private key.");
            }

            using (var stream = s.CreateEntry(name + ".crt").Open())
                using (var writer = new StreamWriter(stream))
                {
                    var pw = new PemWriter(writer);
                    pw.WriteObject(entry.Certificate);
                }
            using (var stream = s.CreateEntry(name + ".key").Open())
                using (var writer = new StreamWriter(stream))
                {
                    var pw = new PemWriter(writer);

                    object privateKey;
                    if (exportPassword != null)
                    {
                        privateKey = new MiscPemGenerator(
                            key.Key,
                            "DES-EDE3-CBC",
                            exportPassword.ToCharArray(),
                            CertificateUtils.GetSeededSecureRandom())
                                     .Generate();
                    }
                    else
                    {
                        privateKey = key.Key;
                    }

                    pw.WriteObject(privateKey);

                    writer.Flush();
                }
        }
Esempio n. 18
0
        public void LoadPfx(string path, string password)
        {
            var    store = new Pkcs12Store(new FileStream(path, FileMode.Open, FileAccess.Read), password.ToCharArray());
            string alias = store.Aliases.Cast <string>().First();

            certificate = store.GetCertificate(alias).Certificate;
            privateKey  = store.GetKey(alias).Key;

            X509Certificate = new System.Security.Cryptography.X509Certificates.X509Certificate2(path, password);
        }
Esempio n. 19
0
        private void UpdateKeyPairType(char[] password)
        {
            Pkcs12Store store = LoadCAPfx(password);

            if (store.ContainsAlias(CaAlias) && store.IsEntryOfType(CaAlias, typeof(AsymmetricKeyEntry)))
            {
                AsymmetricKeyEntry keyEntry = store.GetKey(CaAlias);
                CaCertificate = store.GetCertificate(CaAlias).Certificate;
                KeyPairType   = KeyPairUtils.QueryKeyType(keyEntry.Key);
            }
        }
Esempio n. 20
0
        public static Tuple <X509.X509Certificate, AsymmetricKeyParameter> GetSampleX509Certificate()
        {
            var store = new Pkcs12Store();

            using (var ms = new MemoryStream(SamplePfx))
                store.Load(ms, "mono".ToCharArray());
            var alias   = store.Aliases.Cast <string>().First();
            var cert    = store.GetCertificate(alias).Certificate;
            var privKey = store.GetKey(alias).Key;

            return(Tuple.Create(cert, privKey));
        }
Esempio n. 21
0
        internal static void SignWithPkcs12KeyStore(string keyStore, string password, string input, string output)
        {
            if (String.IsNullOrEmpty(keyStore))
            {
                throw new ArgumentNullException("keyStore");
            }
            if (String.IsNullOrEmpty(password))
            {
                throw new ArgumentNullException("password");
            }
            if (String.IsNullOrEmpty(input))
            {
                throw new ArgumentNullException("input");
            }
            if (String.IsNullOrEmpty(output))
            {
                throw new ArgumentNullException("output");
            }
            if (!File.Exists(keyStore))
            {
                throw new FileNotFoundException("Keystore is not found or is not a file: " + keyStore, keyStore);
            }
            if (!File.Exists(input))
            {
                throw new FileNotFoundException("Input pdf not found: " + input, input);
            }

            try
            {
                var store = new Pkcs12Store(File.OpenRead(keyStore), password.ToCharArray());
                var pKey  = store.Aliases
                            .Cast <string>()
                            .FirstOrDefault(store.IsKeyEntry);
                var key = store.GetKey(pKey).Key;

                var chain = new[] { store.GetCertificate(pKey).Certificate };

                var reader = new PdfReader(input);
                using (var stamper = PdfStamper.CreateSignature(reader, File.OpenWrite(output), '\0', null, true))
                {
                    var sigAppearance = stamper.SignatureAppearance;
                    //Note:note the order of things here
                    SetSigPosition(sigAppearance, reader.AcroFields.GetSignatureNames().Count);
                    SetSigText(sigAppearance, chain);
                    SetSigCryptoFromCipherParam(sigAppearance, key, chain);
                }
            }
            catch (Exception exception)
            {
                throw new Exception("Error while signing pdf file: " + exception.Message, exception);
            }
        }
Esempio n. 22
0
        public static X509Certificate GetCertificate(this Pkcs12Store store)
        {
            foreach (string alias in store.Aliases)
            {
                var keyEntry = store.GetKey(alias);
                if (keyEntry.Key.IsPrivate)
                {
                    return(store.GetCertificate(alias).Certificate);
                }
            }

            throw new ArgumentException("Invalid store.");
        }
Esempio n. 23
0
        public ClientCertificateWithKey(byte[] pkcs12data, string password)
        {
            if (pkcs12data == null || pkcs12data.Length == 0)
            {
                throw new ArgumentException("No PKCS#12 data specified", nameof(pkcs12data));
            }

            var inputKeyStore = new Pkcs12Store();

            try
            {
                using (var ms = new MemoryStream(pkcs12data))
                {
                    inputKeyStore.Load(ms, string.IsNullOrEmpty(password) ? new char[0] : password.ToCharArray());
                }
            }
            catch (IOException ex)
            {
                throw new AuthenticationException("Parsing of the PKCS#12 data failed", ex);
            }
            catch (Exception)
            {
                throw;
            }

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

            if (keyAlias == null)
            {
                throw new InvalidDataException("No private key found in PKCS12 data");
            }

            var bcert = inputKeyStore.GetCertificate(keyAlias);

            this.Certificate = new X509Certificate2(bcert.Certificate.GetEncoded());

            var ck   = inputKeyStore.GetKey(keyAlias);
            var ecpk = ck.Key as ECPrivateKeyParameters;

            this.Key = ecpk.D.ToByteArrayUnsigned();

            var        sb = new StringBuilder();
            TextWriter tw = new StringWriter(sb);

            var pw = new Org.BouncyCastle.OpenSsl.PemWriter(tw);

            pw.WriteObject(ecpk);

            this.Key = Encoding.ASCII.GetBytes(sb.ToString());
        }
        public static Tuple <X509Certificate, AsymmetricKeyParameter> GetSampleX509Certificate()
        {
            Pkcs12Store store = new Pkcs12Store();

            char[] password = "******".ToCharArray();
            using (MemoryStream ms = new MemoryStream(SamplePfx))
                store.Load(ms, password);

            string                 alias   = store.Aliases.Cast <string>().First();
            X509Certificate        cert    = store.GetCertificate(alias).Certificate;
            AsymmetricKeyParameter privKey = store.GetKey(alias).Key;

            return(Tuple.Create(cert, privKey));
        }
 private void RefreshStore()
 {
     _listItems.Clear();
     foreach (String alias in _store.Aliases)
     {
         KeyStoreEntryType entryType;
         if (_store.IsCertificateEntry(alias))
         {
             entryType = KeyStoreEntryType.TrustCertEntry;
         }
         else if (_store.IsKeyEntry(alias) && _store.GetCertificateChain(alias) != null &&
                  _store.GetCertificateChain(alias).Length != 0)
         {
             entryType = KeyStoreEntryType.KeyPairEntry;
         }
         else
         {
             entryType = KeyStoreEntryType.KeyEntry;
         }
         X509Certificate cert = _store.GetCertificate(alias).Certificate;
         _listItems.Add(new ListItemEntry(entryType, alias, cert,
                                          Repository.Instance.IsRevokedCertificate(cert.SerialNumber.ToString())));
     }
 }
Esempio n. 26
0
        public bool Init(string authentication_certificate_path, string authentication_certificate_password)
        {
            AuthenticationCertificatePrivateKey  = null;
            AuthenticationCertificateCertificate = null;


            try
            {
                FileStream Cert = new FileStream(authentication_certificate_path, FileMode.Open, FileAccess.Read);
                var        p12  = new Pkcs12Store();
                p12.Load(Cert, authentication_certificate_password.ToCharArray());

                foreach (string alias in p12.Aliases)
                {
                    if (p12.IsKeyEntry(alias))
                    {
                        AuthenticationCertificatePrivateKey = p12.GetKey(alias).Key;
                        break;
                    }
                }

                foreach (string alias in p12.Aliases)
                {
                    X509CertificateEntry entry = p12.GetCertificate(alias);
                    if (VerifyPivateAndPublicKey(entry.Certificate.GetPublicKey(), AuthenticationCertificatePrivateKey))
                    {
                        AuthenticationCertificateCertificate = p12.GetCertificate(alias).Certificate;
                    }
                }
            }
            catch (Exception ex)
            {
                return(false);
            }
            return(true);
        }
Esempio n. 27
0
        public static List <X509Certificate> InitStore(String p12FileName, char[] ksPass)
        {
            List <X509Certificate> certStore = new List <X509Certificate>();
            string      alias = null;
            Pkcs12Store pk12  = new Pkcs12Store(new FileStream(p12FileName, FileMode.Open, FileAccess.Read), ksPass);

            foreach (var a in pk12.Aliases)
            {
                alias = ((string)a);
                if (pk12.IsCertificateEntry(alias))
                {
                    certStore.Add(pk12.GetCertificate(alias).Certificate);
                }
            }
            return(certStore);
        }
        protected static X509Certificate LoadCertificateFromKeyStore(String keystorePath, char[] ksPass)
        {
            string      alias = null;
            Pkcs12Store pk12  = new Pkcs12Store(new FileStream(keystorePath, FileMode.Open, FileAccess.Read), ksPass);

            foreach (var a in pk12.Aliases)
            {
                alias = ((string)a);
                if (pk12.IsKeyEntry(alias))
                {
                    break;
                }
            }

            return(pk12.GetCertificate(alias).Certificate);
        }
        private static byte[] SignData(byte[] data, Pkcs12Store signCertificate, DateTime?requestTimestamp = null)
        {
            var    signCertAlias = signCertificate.Aliases.Cast <string>().First(signCertificate.IsKeyEntry);
            var    signCertEntry = signCertificate.GetCertificate(signCertAlias);
            var    signCert      = signCertEntry.Certificate;
            var    signPkEntry   = signCertificate.GetKey(signCertAlias);
            var    signPk        = signPkEntry.Key;
            string digestName;

            if (signCert.SigAlgOid == PkcsObjectIdentifiers.Sha1WithRsaEncryption.Id)
            {
                digestName = "SHA1";
            }
            else if (signCert.SigAlgOid == PkcsObjectIdentifiers.Sha256WithRsaEncryption.Id)
            {
                digestName = "SHA256";
            }
            else
            {
                throw new ExtraException($"Unsupported digest algorithm {signCert.SigAlgName}");
            }

            var digestOid = DigestUtilities.GetObjectIdentifier(digestName).Id;
            var digest    = DigestUtilities.CalculateDigest(digestName, data);

            var signedAttrs = new Dictionary <object, object>()
            {
                { CmsAttributeTableParameter.Digest, digest }
            };

            if (requestTimestamp.HasValue)
            {
                var signTimestamp = new Org.BouncyCastle.Asn1.Cms.Attribute(CmsAttributes.SigningTime, new DerSet(new Time(requestTimestamp.Value.ToUniversalTime())));
                signedAttrs.Add(signTimestamp.AttrType, signTimestamp);
            }

            var signedAttrGen   = new DefaultSignedAttributeTableGenerator();
            var signedAttrTable = signedAttrGen.GetAttributes(signedAttrs);

            var generator = new CmsSignedDataGenerator();

            generator.AddSigner(signPk, signCert, digestOid, new DefaultSignedAttributeTableGenerator(signedAttrTable), null);

            var signedData = generator.Generate(new CmsProcessableByteArray(data), true);

            return(signedData.GetEncoded());
        }
        public static X509Certificate getCertificadoX509(string arquivoCertificado, string senha, out AsymmetricKeyParameter chavePrivada)
        {
            chavePrivada = null;
            using (FileStream certificadoStream = new FileStream(arquivoCertificado, FileMode.Open, FileAccess.Read))
            {
                Pkcs12Store armazemPkcs12 = new Pkcs12Store();
                armazemPkcs12.Load(certificadoStream, senha.ToCharArray());

                string certificadoCN = armazemPkcs12.Aliases.Cast <string>().FirstOrDefault(n => armazemPkcs12.IsKeyEntry(n));

                //Console.WriteLine("keyAlias => " + certificadoCN);

                chavePrivada = armazemPkcs12.GetKey(certificadoCN).Key;

                return((X509Certificate)armazemPkcs12.GetCertificate(certificadoCN).Certificate);
            }
        }