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; }
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); }
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; }
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; }
public void XmlDSigRsaKSPackage() { Directory.CreateDirectory(DestDir); String filename = "xfa.signed.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; SignPackageWithCertificate(Src, output, XfaXpathConstructor.XdpPackage.Template, parameters, chain.ToArray(), DigestAlgorithms.SHA1); String cmp = SaveXmlFromResult(output); Assert.IsTrue(VerifyPackageSignature(cmp), "XmlDSig Verification"); Assert.IsTrue(CompareXmls(cmp, CmpDir + filename.Replace(".pdf", ".xml"))); }
public void XadesBesRsa() { Directory.CreateDirectory(DestDirBes); String filename = "xfa.signed.bes.pdf"; String output = DestDirBes + 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; SignXades(Src, output, parameters, chain.ToArray(), DigestAlgorithms.SHA1, false); String cmp = SaveXmlFromResult(output); Assert.IsTrue(VerifySignature(cmp), "XmlDSig Verification"); }
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); }
/// <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); } } }
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> /// 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; } } } }
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; }
/// <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(); } } }
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; }
/// <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)); } } }
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"); }