GetKey() public méthode

public GetKey ( string alias ) : AsymmetricKeyEntry
alias string
Résultat AsymmetricKeyEntry
Exemple #1
2
    public Startup()
    {
        Pkcs12Store pkcs12 = new Pkcs12Store(new FileStream(pfxFile, FileMode.Open, FileAccess.Read), pfxPassword.ToArray());
        string keyAlias = null;

        foreach (string name in pkcs12.Aliases)
        {
            if (pkcs12.IsKeyEntry(name))
            {
                keyAlias = name;
                break;
            }
        }

        AsymmetricKeyParameter key = pkcs12.GetKey(keyAlias).Key;
        X509CertificateEntry[] ce = pkcs12.GetCertificateChain(keyAlias);
        List<X509Certificate> chain = new List<X509Certificate>(ce.Length);
        foreach (var c in ce)
        {
            chain.Add(c.Certificate);
        }

        stamper = new Stamper()
        {
            CertChain = chain,
            PrivateKey = key,
            Stamp = iTextSharp.text.Image.GetInstance(stampImage)
        };
    }
        public void ProcessCert(string certificado, string password)
        {
            //First we'll read the certificate file
            Stream fs = new FileStream(certificado, FileMode.Open, FileAccess.Read);
            Pkcs12Store pk12 = new Pkcs12Store(fs, (password ?? "").ToCharArray());

            //then Iterate throught certificate entries to find the private key entry
            /*foreach (string al in pk12.Aliases) {
                if (pk12.IsKeyEntry(al) && pk12.GetKey(al).Key.IsPrivate) {
                    alias = al;
                    break;
                }
            }*/

            string alias = pk12.Aliases.Cast<string>().FirstOrDefault(al => pk12.IsKeyEntry(al) && pk12.GetKey(al).Key.IsPrivate);

            //IEnumerator i = pk12.Aliases.GetEnumerator();
            //while (i.MoveNext())
            //{
            //    alias = ((string)i.Current);
            //    if (pk12.IsKeyEntry(alias))
            //        break;
            //}
            fs.Close();

            Akp = pk12.GetKey(alias).Key;
            X509CertificateEntry[] ce = pk12.GetCertificateChain(alias);
            //X509Certificate[] chain = new Org.BouncyCastle.X509.X509Certificate[ce.Length];
            Chain = new Org.BouncyCastle.X509.X509Certificate[ce.Length];
            for (int k = 0; k < ce.Length; ++k)
                Chain[k] = ce[k].Certificate;
        }
Exemple #3
1
        public static void SignPdfCert(String SRC, String DEST, String Reason, String Location, String certPassword, String certFile, String llx, String lly, String urx, String ury, int fontSize)
        {
            Pkcs12Store p12ks = new Pkcs12Store();
            FileStream fs = new FileStream(certFile, FileMode.Open);
            p12ks.Load(fs, certPassword.ToCharArray());
            String alias = "";
            foreach (String al in p12ks.Aliases)
            {
                if (p12ks.IsKeyEntry(al) && p12ks.GetKey(al).Key.IsPrivate)
                {
                    alias = al;
                    break;
                }
            }
            AsymmetricKeyParameter pk = p12ks.GetKey(alias).Key;
            ICollection<X509Certificate> chain = new List<X509Certificate>();
            foreach (X509CertificateEntry entry in p12ks.GetCertificateChain(alias))
            {
                chain.Add(entry.Certificate);
            }

            fs.Close();
            //Org.BouncyCastle.X509.X509CertificateParser cp = new Org.BouncyCastle.X509.X509CertificateParser();
            //Org.BouncyCastle.X509.X509Certificate[] chain = new Org.BouncyCastle.X509.X509Certificate[] { cp.ReadCertificate(cert.RawData) };

            IExternalSignature externalSignature = new PrivateKeySignature(pk, DigestAlgorithms.SHA512);
            PdfReader pdfReader = new PdfReader(SRC);
            FileStream signedPdf = new FileStream(DEST, FileMode.Create);  //the output pdf file
            Program.logLine("page size" + pdfReader.GetPageSize(1));

            PdfStamper pdfStamper = PdfStamper.CreateSignature(pdfReader, signedPdf, '\0');
            PdfSignatureAppearance signatureAppearance = pdfStamper.SignatureAppearance;
            //here set signatureAppearance at your will
            signatureAppearance.Reason = Reason;
            signatureAppearance.Location = Location;
            BaseFont bf = BaseFont.CreateFont();
            signatureAppearance.Layer2Font = new Font(bf, fontSize);
            signatureAppearance.SetVisibleSignature(new Rectangle(float.Parse(llx), float.Parse(lly), float.Parse(urx), float.Parse(ury)), 1, "sig");
            //signatureAppearance.SignatureRenderingMode = PdfSignatureAppearance.RenderingMode.DESCRIPTION;
            MakeSignature.SignDetached(signatureAppearance, externalSignature, chain, null, null, null, 0, CryptoStandard.CMS);
            //MakeSignature.SignDetached(signatureAppearance, externalSignature, chain, null, null, null, 0, CryptoStandard.CADES);
        }
Exemple #4
0
 /// <summary>
 /// Reads A Personal Information Exchange File.
 /// </summary>
 /// <param name="pfxPath">Certificate file's path</param>
 /// <param name="pfxPassword">Certificate file's password</param>
 public static PfxData ReadCertificate(string pfxPath, string pfxPassword)
 {
     using (var stream = new FileStream(pfxPath, FileMode.Open, FileAccess.Read, FileShare.Read))
     {
         var pkcs12Store = new Pkcs12Store(stream, pfxPassword.ToCharArray());
         var alias = findThePublicKey(pkcs12Store);
         var asymmetricKeyParameter = pkcs12Store.GetKey(alias).Key;
         var chain = constructChain(pkcs12Store, alias);
         return new PfxData { X509PrivateKeys = chain, PublicKey = asymmetricKeyParameter };
     }
 }
        public void XmlDSigRsaKS()
        {
            Directory.CreateDirectory(DestDir);

            String filename = "xfa.signed.pdf";
            String output = DestDir + filename;

            MemoryStream ks = new MemoryStream();
            using(FileStream reader = new FileStream(KEYSTORE, FileMode.Open)) {
                byte[] buffer = new byte[reader.Length];
                reader.Read(buffer, 0, (int)reader.Length);
                ks.Write(buffer, 0, buffer.Length);
                ks.Position = 0;
            }
            Pkcs12Store store = new Pkcs12Store(ks, PASSWORD.ToCharArray());
            String alias = "";
            List<X509Certificate> chain = new List<X509Certificate>();
            // searching for private key

            foreach(string al in store.Aliases) {
                if(store.IsKeyEntry(al) && store.GetKey(al).Key.IsPrivate) {
                    alias = al;
                    break;
                }
            }

            AsymmetricKeyEntry pk = store.GetKey(alias);
            foreach(X509CertificateEntry c in store.GetCertificateChain(alias))
                chain.Add(c.Certificate);

            RsaPrivateCrtKeyParameters parameters = pk.Key as RsaPrivateCrtKeyParameters;
            SignWithCertificate(Src, output, parameters, chain.ToArray(), DigestAlgorithms.SHA1);

            String cmp = SaveXmlFromResult(output);

            Assert.IsTrue(VerifySignature(cmp), "XmlDSig Verification");

            Assert.IsTrue(CompareXmls(cmp, CmpDir + filename.Replace(".pdf", ".xml")));
        }
Exemple #6
0
        private static string findThePublicKey(Pkcs12Store pkcs12Store)
        {
            var alias = string.Empty;
            foreach (var entry in pkcs12Store.Aliases.Cast<string>().Where(entry => pkcs12Store.IsKeyEntry(entry) && pkcs12Store.GetKey(entry).Key.IsPrivate))
            {
                alias = entry;
                break;
            }

            if (string.IsNullOrEmpty(alias))
                throw new InvalidOperationException("Provided certificate is invalid.");

            return alias;
        }
Exemple #7
0
        public void XadesBesRsaPackage() {

            Directory.CreateDirectory(DestDir);

            String filename = "xfa.signed.bes.package.pdf";
            String output = DestDir + filename;

            MemoryStream ks = new MemoryStream();
            using(FileStream reader = new FileStream(KEYSTORE, FileMode.Open)) {
                byte[] buffer = new byte[reader.Length];
                reader.Read(buffer, 0, (int)reader.Length);
                ks.Write(buffer, 0, buffer.Length);
                ks.Position = 0;
            }
            Pkcs12Store store = new Pkcs12Store(ks, PASSWORD.ToCharArray());
            String alias = "";
            List<X509Certificate> chain = new List<X509Certificate>();
            // searching for private key

            foreach(string al in store.Aliases) {
                if(store.IsKeyEntry(al) && store.GetKey(al).Key.IsPrivate) {
                    alias = al;
                    break;
                }
            }

            AsymmetricKeyEntry pk = store.GetKey(alias);
            foreach(X509CertificateEntry c in store.GetCertificateChain(alias)) {
                chain.Add(c.Certificate);
            }

            RsaPrivateCrtKeyParameters parameters = pk.Key as RsaPrivateCrtKeyParameters;

            SignBesPackage(Src, output, XfaXpathConstructor.XdpPackage.Template, parameters, chain.ToArray(), DigestAlgorithms.SHA1);

            String cmp = SaveXmlFromResult(output);
        }
Exemple #8
0
        public static void Main(String[] args) {
            Properties properties = new Properties();
            properties.Load(new FileStream("c:/home/blowagie/key.properties", FileMode.Open));
            String path = properties["PRIVATE"];
            char[] pass = properties["PASSWORD"].ToCharArray();

            Pkcs12Store ks = new Pkcs12Store();
            ks.Load(new FileStream(path, FileMode.Open), pass);
            String alias = "";
            foreach (string al in ks.Aliases) {
                if (ks.IsKeyEntry(al) && ks.GetKey(al).Key.IsPrivate) {
                    alias = al;
                    break;
                }
            }
            AsymmetricKeyParameter pk = ks.GetKey(alias).Key;
            ICollection<X509Certificate> chain = new List<X509Certificate>();
            foreach (X509CertificateEntry entry in ks.GetCertificateChain(alias)) {
                chain.Add(entry.Certificate);
            }
            IOcspClient ocspClient = new OcspClientBouncyCastle();
            C3_01_SignWithCAcert.Sign(DEST, chain, pk, DigestAlgorithms.SHA256, CryptoStandard.CMS, "Test", "Ghent",
                     null, ocspClient, null, 0);
        }
Exemple #9
0
    static void Cert(string path, string password, out AsymmetricKeyParameter akp, out Org.BouncyCastle.X509.X509Certificate[] chain) {
      string alias = null;
      Pkcs12Store pk12;
      //First we'll read the certificate file
      pk12 = new Pkcs12Store(new FileStream(path, FileMode.Open, FileAccess.Read), password.ToCharArray());

      //then Iterate throught certificate entries to find the private key entry
      IEnumerator i = pk12.Aliases.GetEnumerator();
      while (i.MoveNext()) {
        alias = ((string)i.Current);
        if (pk12.IsKeyEntry(alias)) break;
      }

      akp = pk12.GetKey(alias).Key;
      X509CertificateEntry[] ce = pk12.GetCertificateChain(alias);
      chain = new Org.BouncyCastle.X509.X509Certificate[ce.Length];
      for (int k = 0; k < ce.Length; ++k)
        chain[k] = ce[k].Certificate;
    }
        /// <summary>
        /// Sets the private key.
        /// </summary>
        /// <param name="fs">The fs.</param>
        /// <param name="passWord">The pass word.</param>
        private void SetPrivateKey(Stream fs, string passWord)
        {
            Pkcs12Store store = new Pkcs12Store(fs, passWord.ToCharArray());

            foreach (string n in store.Aliases)
            {
                if (store.IsKeyEntry(n))
                {
                    AsymmetricKeyEntry asymmetricKey = store.GetKey(n);

                    if (asymmetricKey.Key.IsPrivate)
                    {
                        _ecPrivateKeyParameters = asymmetricKey.Key as ECPrivateKeyParameters;
                    }
                    else
                    {
                        _ecPublicKeyParameters = asymmetricKey.Key as ECPublicKeyParameters;
                    }
                }
            }
        }
Exemple #11
0
        private void processCert()
        {
            string alias = null;
            Pkcs12Store pk12;

            //First we'll read the certificate file
            Stream fs;

            if (this.path != null) fs = new FileStream(this.Path, FileMode.Open, FileAccess.Read);
            else fs = new MemoryStream(this.rawData);
            pk12 = new Pkcs12Store(fs, this.password.ToCharArray());

            //then Iterate throught certificate entries to find the private key entry
            foreach (string al in pk12.Aliases)
            {
                if (pk12.IsKeyEntry(al) && pk12.GetKey(al).Key.IsPrivate)
                {
                    alias = al;
                    break;
                }
            }

            //IEnumerator i = pk12.Aliases.GetEnumerator();
            //while (i.MoveNext())
            //{
            //    alias = ((string)i.Current);
            //    if (pk12.IsKeyEntry(alias))
            //        break;
            //}
            fs.Close();

            this.akp = pk12.GetKey(alias).Key;
            X509CertificateEntry[] ce = pk12.GetCertificateChain(alias);
            this.chain = new Org.BouncyCastle.X509.X509Certificate[ce.Length];
            for (int k = 0; k < ce.Length; ++k)
                chain[k] = ce[k].Certificate;

            //this.tsc = new TSAClientBouncyCastle("http://www.ca-soft.com/request.aspx", TSA_ACCNT, TSA_PASSW);
            //this.tsc = new TSAClientBouncyCastle("http://www.ca-soft.com/request.aspx");
        }
        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();
        }
Exemple #13
0
        public IList<CmsSigner> GetAllCmsSigners()
        {
            if (disposed)
                throw new ObjectDisposedException ("SecKeychain");

            var signers = new List<CmsSigner> ();
            IntPtr searchRef, itemRef, dataRef;
            OSStatus status;

            status = SecIdentitySearchCreate (Handle, CssmKeyUse.Sign, out searchRef);
            if (status != OSStatus.Ok)
                return signers;

            while (SecIdentitySearchCopyNext (searchRef, out itemRef) == OSStatus.Ok) {
                if (SecItemExport (itemRef, SecExternalFormat.PKCS12, SecItemImportExportFlags.None, IntPtr.Zero, out dataRef) == OSStatus.Ok) {
                    var data = new CFData (dataRef, true);
                    var rawData = data.GetBuffer ();
                    data.Dispose ();

                    try {
                        using (var memory = new MemoryStream (rawData, false)) {
                            var pkcs12 = new Pkcs12Store (memory, new char[0]);

                            foreach (string alias in pkcs12.Aliases) {
                                if (!pkcs12.IsKeyEntry (alias))
                                    continue;

                                var chain = pkcs12.GetCertificateChain (alias);
                                var key = pkcs12.GetKey (alias);

                                signers.Add (new CmsSigner (chain, key));
                            }
                        }
                    } catch (Exception ex) {
                        Debug.WriteLine ("Failed to decode keychain pkcs12 data: {0}", ex);
                    }
                }

                CFRelease (itemRef);
            }

            CFRelease (searchRef);

            return signers;
        }
        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);
            }
        }
        /// <summary>
        /// Método que carga un almacén. Solicita la contraseña del almacén seleccionado y carga los alias de dicho 
        /// alamacén en la lista de alias si la contraseña proporcionada fuera correcta.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private async void ComboBox_Stores_Selection_Changed(object sender, SelectionChangedEventArgs e)
        {
            if (pfxList.SelectedItem != null)
            {
                // Si no se ha seleccionado el elemento "dummy"...
                if (!pfxList.SelectedItem.Equals(labels.GetString("Etiqueta_seleccion_almacen")))
                {
                    IReadOnlyList<StorageFile> files = await ApplicationData.Current.LocalFolder.GetFilesAsync();
                    StorageFile fileSelected = null;
                    foreach (StorageFile file in files)
                    {
                        if (file.Name.Equals((String)pfxList.SelectedItem))
                        {
                            fileSelected = file;
                            break;
                        }
                    }
                    if (fileSelected != null)
                    {
                        using (StreamReader reader = new StreamReader(await fileSelected.OpenStreamForReadAsync()))
                        {
                            // Pedimos el PIN del almacén al usuario
                            CredentialPanel2 cp2 = new CredentialPanel2(pfxList.SelectedItem.ToString());
                            cp2.Focus(Windows.UI.Xaml.FocusState.Programmatic);
                            CustomDialog customDialog = new CustomDialog(cp2, labels.GetString("Etiqueta_peticion_pass"));
                            customDialog.Commands.Add(new UICommand(labels.GetString("Boton_aceptar")));
                            customDialog.Commands.Add(new UICommand(labels.GetString("Boton_cancelar")));
                            customDialog.DefaultCommandIndex = 0;
                            customDialog.CancelCommandIndex = 1;
                            IUICommand com = await customDialog.ShowAsync();
                            // El usuario ha cancelado, si solo no estaba el elemento "dummy" 
                            // hay que añadirlo en la posición cero y seleccionarlo, para permitirle reintentar
                            if (com.Label.Equals(labels.GetString("Boton_cancelar")))
                            {
                                if (!pfxList.Items.Contains(labels.GetString("Etiqueta_seleccion_almacen")))
                                {
                                    pfxList.Items.Insert(0, labels.GetString("Etiqueta_seleccion_almacen"));
                                }
                                pfxList.SelectedIndex = 0;
                            }
                            // El usuario ha aceptado en el diálogo de PIN
                            if (com.Label.Equals(labels.GetString("Boton_aceptar")))
                            {
                                aliasList.Items.Clear();
                                try
                                {
                                    store = new Pkcs12Store(reader.BaseStream, cp2.getPassword().ToCharArray());
                                    foreach (string n in store.Aliases)
                                    {
                                        if (store.IsKeyEntry(n))
                                        {
                                            AsymmetricKeyEntry key = store.GetKey(n);

                                            if (key.Key.IsPrivate)
                                            {
                                                aliasList.Items.Clear();
                                                aliasList.IsEnabled = true;
                                                RsaPrivateCrtKeyParameters parameters = key.Key as RsaPrivateCrtKeyParameters;
                                                rsaKeyParameter = (RsaKeyParameters)key.Key;
                                                foreach (object s in store.Aliases)
                                                {
                                                    aliasList.Items.Add((string)s);
                                                }

                                            }
                                        }
                                    }
                                }
                                catch
                                {
                                    AfirmaMetroUtils.showMessage(labels.GetString("Error_carga_almacen"), "Error en el almacén de claves" + " (" + pfxList.SelectedItem + ")");
                                    // Para permitirle reintentar insertamos el elemento "dummy" como primer elemento
                                    // y lo seleccionamos
                                    if (!pfxList.Items.Contains(labels.GetString("Etiqueta_seleccion_almacen")))
                                    {
                                        pfxList.Items.Insert(0, labels.GetString("Etiqueta_seleccion_almacen"));
                                    }
                                    pfxList.SelectedIndex = 0;
                                    return;
                                }

                                // Se ha seleccionado correctamente un almacén, eliminamos el componente "dummy"
                                if (pfxList.Items.Contains(labels.GetString("Etiqueta_seleccion_almacen")))
                                {
                                    pfxList.Items.Remove(labels.GetString("Etiqueta_seleccion_almacen"));
                                }

                                aliasList.SelectedIndex = 0;
                            }
                        }
                    }

                }
                else
                {
                    disableComboAlias();
                }
            }
        }
        /// <summary>
        /// Open the certificate
        /// </summary>
        private  void LoadPfx(out X509Certificate[] certificates, out AsymmetricKeyEntry privateKey)
        {
            if (!string.IsNullOrEmpty(pfxFile))
            {
                // Load PFX directly
                using (var pfxStream = new FileStream(pfxFile, FileMode.Open, FileAccess.Read))
                {
                    var pfx = new Pkcs12Store(pfxStream, pfxPassword.ToCharArray());
                    var alias = pfx.Aliases.Cast<string>().FirstOrDefault(pfx.IsKeyEntry);
                    if (alias == null)
                        throw new ArgumentException("Cannot find a certificate with a key");
                    certificates = pfx.GetCertificateChain(alias).Select(x => x.Certificate).ToArray();
                    privateKey = pfx.GetKey(alias);                    
                }
            }
            else if (!string.IsNullOrEmpty(certificateThumbprint))
            {
                // Load thumbprint
                var x509 = CertificateSupport.GetCertByThumbprint(certificateThumbprint);
                if (x509 == null)
                    throw new ArgumentException("Failed to load certificate by thumbprint");
                if (!x509.HasPrivateKey)
                    throw new ArgumentException("Certificate has no private key");

                // Gets the certificates
                var parser = new X509CertificateParser();
                certificates = new[] { parser.ReadCertificate(x509.RawData) };

                // Get the private key
                var netPrivateKey = x509.PrivateKey as RSACryptoServiceProvider;
                if (netPrivateKey == null)
                    throw new ArgumentException("Private key is not an RSA crypto service provider");
                var parameters = netPrivateKey.ExportParameters(true);
                var keyParameters = new RsaPrivateCrtKeyParameters(
                    new BigInteger(1, parameters.Modulus),
                    new BigInteger(1, parameters.Exponent),
                    new BigInteger(1, parameters.D),
                    new BigInteger(1, parameters.P),
                    new BigInteger(1, parameters.Q),
                    new BigInteger(1, parameters.DP),
                    new BigInteger(1, parameters.DQ),
                    new BigInteger(1, parameters.InverseQ));
                privateKey = new AsymmetricKeyEntry(keyParameters);
            }
            else
            {
                throw new ArgumentException("No certificate specified");
            }
        }
Exemple #17
0
		void LoadPkcs12 (Stream stream, string password)
		{
			var pkcs12 = new Pkcs12Store (stream, password.ToCharArray ());

			foreach (string alias in pkcs12.Aliases) {
				if (!pkcs12.IsKeyEntry (alias))
					continue;

				var chain = pkcs12.GetCertificateChain (alias);
				var key = pkcs12.GetKey (alias);

				if (!key.Key.IsPrivate || chain.Length == 0)
					continue;

				var flags = chain[0].Certificate.GetKeyUsageFlags ();

				if (flags != X509KeyUsageFlags.None && (flags & SecureMimeContext.DigitalSignatureKeyUsageFlags) == 0)
					continue;

				CheckCertificateCanBeUsedForSigning (chain[0].Certificate);

				CertificateChain = new X509CertificateChain ();
				Certificate = chain[0].Certificate;
				PrivateKey = key.Key;

				foreach (var entry in chain)
					CertificateChain.Add (entry.Certificate);

				break;
			}

			if (PrivateKey == null)
				throw new ArgumentException ("The stream did not contain a private key.", nameof (stream));
		}
		/// <summary>
		/// Imports certificates and keys from a pkcs12-encoded stream.
		/// </summary>
		/// <remarks>
		/// Imports all of the certificates and keys from the pkcs12-encoded stream.
		/// </remarks>
		/// <param name="stream">The raw certificate and key data.</param>
		/// <param name="password">The password to unlock the data.</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>
		/// <exception cref="Org.BouncyCastle.Cms.CmsException">
		/// An error occurred in the cryptographic message syntax subsystem.
		/// </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 ());
			var enabledAlgorithms = EnabledEncryptionAlgorithms;
			X509CertificateRecord record;

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

					if (entry.Key.IsPrivate) {
						if ((record = dbase.Find (chain[0].Certificate, ImportPkcs12Fields)) == null) {
							record = new X509CertificateRecord (chain[0].Certificate, entry.Key);
							record.AlgorithmsUpdated = DateTime.UtcNow;
							record.Algorithms = enabledAlgorithms;
							record.IsTrusted = true;
							dbase.Add (record);
						} else {
							record.AlgorithmsUpdated = DateTime.UtcNow;
							record.Algorithms = enabledAlgorithms;
							if (record.PrivateKey == null)
								record.PrivateKey = entry.Key;
							record.IsTrusted = true;
							dbase.Update (record, ImportPkcs12Fields);
						}

						startIndex = 1;
					}

					for (int i = startIndex; i < chain.Length; i++) {
						if ((record = dbase.Find (chain[i].Certificate, X509CertificateRecordFields.Id)) == null)
							dbase.Add (new X509CertificateRecord (chain[i].Certificate));
					}
				} else if (pkcs12.IsCertificateEntry (alias)) {
					var entry = pkcs12.GetCertificate (alias);

					if ((record = dbase.Find (entry.Certificate, X509CertificateRecordFields.Id)) == null)
						dbase.Add (new X509CertificateRecord (entry.Certificate));
				}
			}
		}
		/// <summary>
		/// Imports certificates and private keys from the specified stream.
		/// </summary>
		/// <remarks>
		/// <para>Imports certificates and private keys from the specified pkcs12 stream.</para>
		/// </remarks>
		/// <param name="stream">The stream to import.</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>
		/// <exception cref="System.IO.IOException">
		/// An error occurred reading the stream.
		/// </exception>
		public 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++) {
						if (unique.Add (chain[i].Certificate))
							certs.Add (chain[i].Certificate);
					}

					if (entry.Key.IsPrivate)
						keys.Add (chain[0].Certificate, entry.Key);
				} else if (pkcs12.IsCertificateEntry (alias)) {
					var entry = pkcs12.GetCertificate (alias);

					if (unique.Add (entry.Certificate))
						certs.Add (entry.Certificate);
				}
			}
		}
        private void ProcessCert()
        {
            string alias = null;

            //First we'll read the certificate file
            Pkcs12Store pk12 = new Pkcs12Store(new FileStream(Path, FileMode.Open, FileAccess.Read), _password.ToCharArray());

            //then Iterate throught certificate entries to find the private key entry

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

            _akp = pk12.GetKey(alias).Key;
            X509CertificateEntry[] ce = pk12.GetCertificateChain(alias);
            _chain = new X509Certificate[ce.Length];
            for (int k = 0; k < ce.Length; ++k)
                _chain[k] = ce[k].Certificate;
        }