public GetCertificateChain ( string alias ) : Org.BouncyCastle.Pkcs.X509CertificateEntry[] | ||
alias | string | |
return | Org.BouncyCastle.Pkcs.X509CertificateEntry[] |
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 X509Certificate[] constructChain(Pkcs12Store pkcs12Store, string alias) { var certificateChains = pkcs12Store.GetCertificateChain(alias); var chain = new X509Certificate[certificateChains.Length]; for (var k = 0; k < certificateChains.Length; ++k) chain[k] = certificateChains[k].Certificate; return chain; }
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 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"))); }
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)); }
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; }
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)); } } }
virtual public void XadesEpesRsaPackage() { Directory.CreateDirectory(DestDirEpes); String filename = "xfa.signed.epes.package.pdf"; String output = DestDirEpes + 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; SignXadesPackage(Src, output, XfaXpathConstructor.XdpPackage.Template, parameters, chain.ToArray(), DigestAlgorithms.SHA1, true); String cmp = SaveXmlFromResult(output); Assert.IsTrue(VerifyPackageSignature(cmp), "XmlDSig Verification"); }
/// <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"); } }
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"); }