static void Main(string[] args) { Pkcs12Store store = new Pkcs12Store(new FileStream(KEYSTORE, FileMode.Open), PASSWORD); String alias = ""; ICollection <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; C2_06_SignatureAppearance app = new C2_06_SignatureAppearance(); app.Sign1(SRC, "Signature1", String.Format(DEST, 1), chain, parameters, DigestAlgorithms.SHA256, CryptoStandard.CMS, "Custom appearance example", "Ghent"); app.Sign2(SRC, "Signature1", String.Format(DEST, 2), chain, parameters, DigestAlgorithms.SHA256, CryptoStandard.CMS, "Custom appearance example", "Ghent"); app.Sign3(SRC, "Signature1", String.Format(DEST, 3), chain, parameters, DigestAlgorithms.SHA256, CryptoStandard.CMS, "Custom appearance example", "Ghent"); app.Sign4(SRC, "Signature1", String.Format(DEST, 4), chain, parameters, DigestAlgorithms.SHA256, CryptoStandard.CMS, "Custom appearance example", "Ghent"); }
public static void Main(String[] args) { DirectoryInfo directory = new DirectoryInfo(DEST); directory.Create(); C2_04_CreateEmptyField appCreate = new C2_04_CreateEmptyField(); appCreate.CreatePdf(DEST + RESULT_FILES[0]); appCreate.AddField(SRC, DEST + RESULT_FILES[1]); Pkcs12Store pk12 = new Pkcs12Store(new FileStream(KEYSTORE, FileMode.Open, FileAccess.Read), PASSWORD); string alias = null; foreach (var a in pk12.Aliases) { alias = ((string)a); if (pk12.IsKeyEntry(alias)) { break; } } ICipherParameters pk = pk12.GetKey(alias).Key; X509CertificateEntry[] ce = pk12.GetCertificateChain(alias); X509Certificate[] chain = new X509Certificate[ce.Length]; for (int k = 0; k < ce.Length; ++k) { chain[k] = ce[k].Certificate; } new C2_04_CreateEmptyField().Sign(DEST + RESULT_FILES[0], SIGNAME, DEST + RESULT_FILES[2], chain, pk, DigestAlgorithms.SHA256, PdfSigner.CryptoStandard.CMS, "Test", "Ghent"); }
public static void Main(String[] args) { Properties properties = new Properties(); // Specify the correct path to the certificate properties.Load(new FileStream("c:/home/blowagie/key.properties", FileMode.Open, FileAccess.Read)); String path = properties.GetProperty("PRIVATE"); char[] pass = properties.GetProperty("PASSWORD").ToCharArray(); Pkcs12Store pk12 = new Pkcs12Store(new FileStream(path, FileMode.Open, FileAccess.Read), pass); string alias = null; foreach (var a in pk12.Aliases) { alias = ((string)a); if (pk12.IsKeyEntry(alias)) { break; } } X509CertificateEntry[] ce = pk12.GetCertificateChain(alias); X509Certificate[] chain = new X509Certificate[ce.Length]; for (int k = 0; k < ce.Length; ++k) { chain[k] = ce[k].Certificate; } for (int i = 0; i < chain.Length; i++) { X509Certificate cert = chain[i]; Console.WriteLine("[{0}] {1}", i, cert.SubjectDN); Console.WriteLine(CertificateUtil.GetOCSPURL(cert)); } }
private ActionResult SignPdfFile(PdfStamper stamper, IJob job) { Signing s = job.Profile.PdfSettings.Signing; //Leave without signing //WEG!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! if (!s.Enable) { if (stamper != null) { stamper.Close(); return(new ActionResult()); } Logger.Error("Could not create Stamper for Encryption, without Signing"); return(new ActionResult(ActionId, 104)); } //Continue for Signing s.CertificationFile = Path.GetFullPath(s.CertificationFile); if (IsValidCertificatePassword(s.CertificationFile, job.Passwords.PdfSignaturePassword) == false) { Logger.Error("Canceled signing. The password for certificate '" + s.CertificationFile + "' is wrong."); stamper.Close(); return(new ActionResult(ActionId, 105)); } if (CertificateHasPrivateKey(s.CertificationFile, job.Passwords.PdfSignaturePassword) == false) { Logger.Error("Canceled signing. The certificate '" + s.CertificationFile + "' has no private key."); stamper.Close(); return(new ActionResult(ActionId, 106)); } var fsCert = new FileStream(s.CertificationFile, FileMode.Open); var ks = new Pkcs12Store(fsCert, job.Passwords.PdfSignaturePassword.ToCharArray()); string alias = null; foreach (string al in ks.Aliases) { if (ks.IsKeyEntry(al) && ks.GetKey(al).Key.IsPrivate) { alias = al; break; } } fsCert.Close(); ICipherParameters pk = ks.GetKey(alias).Key; X509CertificateEntry[] x = ks.GetCertificateChain(alias); var chain = new X509Certificate[x.Length]; for (int k = 0; k < x.Length; ++k) { chain[k] = x[k].Certificate; } ITSAClient tsc = null; if (s.TimeServerUrl.Trim() != "") //Timeserver with LogIn? { tsc = new TSAClientBouncyCastle(s.TimeServerUrl /*, TimeServerLogonName, TimeServerLogonPassword*/); } PdfSignatureAppearance sap = stamper.SignatureAppearance; if (tsc == null) { sap.SetCrypto(pk, chain, null, PdfSignatureAppearance.WINCER_SIGNED); } else { sap.SetCrypto(null, chain, null, PdfSignatureAppearance.SELF_SIGNED); } sap.Reason = s.SignReason; sap.Contact = s.SignContact; sap.Location = s.SignLocation; if (s.DisplaySignatureInPdf) { int signPage = SignPageNr(job); sap.SetVisibleSignature(new Rectangle(s.LeftX, s.LeftY, s.RightX, s.RightY), signPage, null); } var dic = new PdfSignature(PdfName.ADOBE_PPKLITE, new PdfName("adbe.pkcs7.detached")); dic.Reason = sap.Reason; dic.Location = sap.Location; dic.Contact = sap.Contact; dic.Date = new PdfDate(sap.SignDate); sap.CryptoDictionary = dic; const int contentEstimated = 15000; // Preallocate excluded byte-range for the signature content (hex encoded) var exc = new Dictionary <PdfName, int>(); exc[PdfName.CONTENTS] = contentEstimated * 2 + 2; sap.PreClose(exc); const string hashAlgorithm = "SHA1"; //Always use HashAlgorithm "SHA1" var sgn = new PdfPKCS7(pk, chain, null, hashAlgorithm, false); IDigest messageDigest = DigestUtilities.GetDigest(hashAlgorithm); Stream data = sap.GetRangeStream(); var buf = new byte[8192]; int n; while ((n = data.Read(buf, 0, buf.Length)) > 0) { messageDigest.BlockUpdate(buf, 0, n); } var hash = new byte[messageDigest.GetDigestSize()]; messageDigest.DoFinal(hash, 0); byte[] ocsp = null; if (chain.Length >= 2) { String url = PdfPKCS7.GetOCSPURL(chain[0]); if (!string.IsNullOrEmpty(url)) { ocsp = new OcspClientBouncyCastle().GetEncoded(chain[0], chain[1], url); } } DateTime cal = sap.SignDate; byte[] sh = sgn.GetAuthenticatedAttributeBytes(hash, cal, ocsp); sgn.Update(sh, 0, sh.Length); var paddedSig = new byte[contentEstimated]; if (tsc != null) { byte[] encodedSigTsa = sgn.GetEncodedPKCS7(hash, cal, tsc, ocsp); Array.Copy(encodedSigTsa, 0, paddedSig, 0, encodedSigTsa.Length); if (contentEstimated + 2 < encodedSigTsa.Length) { Logger.Error("Not enough space for signature"); return(new ActionResult(ActionId, 107)); } } else { byte[] encodedSig = sgn.GetEncodedPKCS7(hash, cal); Array.Copy(encodedSig, 0, paddedSig, 0, encodedSig.Length); if (contentEstimated + 2 < encodedSig.Length) { Logger.Error("Not enough space for signature"); return(new ActionResult(ActionId, 107)); } } var dic2 = new PdfDictionary(); dic2.Put(PdfName.CONTENTS, new PdfString(paddedSig).SetHexWriting(true)); sap.Close(dic2); return(new ActionResult()); }
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); } }
static bool Gen(string summoner, string region, string password, string file) { try { //Later in your Code //Requested Certificate Name X509Name name = new X509Name("CN=" + summoner + " - " + region + ", OU=Ghostblade Replays, O=Arsslensoft"); //Key generation 2048bits RsaKeyPairGenerator rkpg = new RsaKeyPairGenerator(); rkpg.Init(new KeyGenerationParameters(new SecureRandom(), 2048)); AsymmetricCipherKeyPair ackp = rkpg.GenerateKeyPair(); X509Certificate2 caCert = new X509Certificate2(GBReplay.Properties.Resources.GBSGN, "KGPAQW7894Q129D7Q1456W9A47897a9s7r5d6"); //PKCS #10 Certificate Signing Request Pkcs10CertificationRequest csr = new Pkcs10CertificationRequest("SHA256WITHRSA", name, ackp.Public, null, ackp.Private); AsymmetricKeyParameter publicKey = csr.GetPublicKey(); // Build a Version1 (No Extensions) Certificate DateTime startDate = DateTime.Now.Subtract(new TimeSpan(1, 0, 0)); DateTime expiryDate = startDate.AddYears(5); BigInteger serialNumber = new BigInteger(32, new Random()); X509V3CertificateGenerator certGen = new X509V3CertificateGenerator(); X509Name dnName = new X509Name(caCert.Subject); certGen.SetSerialNumber(serialNumber); certGen.SetIssuerDN(dnName); certGen.SetNotBefore(startDate); certGen.SetNotAfter(expiryDate); certGen.SetSubjectDN(name); certGen.SetSignatureAlgorithm("SHA256WITHRSA"); certGen.SetPublicKey(publicKey); UserNotice unotice = new UserNotice(null, "This certificate must be only used with Ghostblade replays files. This certificate is a property of Arsslensoft any usage of its content without prior request is prohibited."); PolicyQualifierInfo pqiunotice = new PolicyQualifierInfo(PolicyQualifierID.IdQtUnotice, unotice); PolicyInformation p = new PolicyInformation(new DerObjectIdentifier("1.3.6.1.4.1.44215.1.3"), new DerSequence(new PolicyQualifierInfo[1] { pqiunotice })); certGen.AddExtension(X509Extensions.BasicConstraints, true, new BasicConstraints(false)); certGen.AddExtension(X509Extensions.AuthorityKeyIdentifier, false, new AuthorityKeyIdentifierStructure(DotNetUtilities.FromX509Certificate(caCert).GetPublicKey())); certGen.AddExtension(X509Extensions.SubjectKeyIdentifier, false, new SubjectKeyIdentifierStructure(publicKey)); certGen.AddExtension(X509Extensions.KeyUsage, false, new KeyUsage(KeyUsage.DigitalSignature)); certGen.AddExtension(X509Extensions.ExtendedKeyUsage, false, new ExtendedKeyUsage(new KeyPurposeID[] { KeyPurposeID.IdKPCodeSigning })); certGen.AddExtension(X509Extensions.CertificatePolicies, false, new DerSequence(p)); Pkcs12Store pfx = new Pkcs12Store(new MemoryStream(GBReplay.Properties.Resources.GBSGN), "KGPAQW7894Q129D7Q1456W9A47897a9s7r5d6".ToCharArray()); string alias = null; foreach (string al in pfx.Aliases) { if (pfx.IsKeyEntry(al) && pfx.GetKey(al).Key.IsPrivate) { alias = al; break; } } //get our Private Key to Sign with // AsymmetricCipherKeyPair caPair = DotNetUtilities.GetKeyPair(caCert.PrivateKey); AsymmetricKeyParameter caPair = pfx.GetKey(alias).Key; Al.Security.X509.X509Certificate cert = certGen.Generate(caPair); Pkcs12Store pk = new Pkcs12StoreBuilder().Build(); // Add a Certificate entry X509CertificateEntry certEntry = new X509CertificateEntry(cert); pk.SetCertificateEntry(cert.SubjectDN.ToString(), certEntry); // use DN as the Alias. AsymmetricKeyEntry keyEntry = new AsymmetricKeyEntry(ackp.Private); pk.SetKeyEntry(cert.SubjectDN.ToString(), keyEntry, new X509CertificateEntry[] { certEntry }); // Note that we only have 1 cert in the 'chain' using (var filestream = new FileStream(file, FileMode.Create, FileAccess.ReadWrite)) pk.Save(filestream, password.ToCharArray(), new SecureRandom()); X509Certificate2 cer = new X509Certificate2(File.ReadAllBytes(file), password); cer.Verify(); } catch { return(false); } return(true); }
public void Save(CertificateInfo input) { _log.Information("Exporting .pem files to {folder}", _path); try { // Determine name var name = input.SubjectName.Replace("*", "_"); // Base certificate var certificateExport = input.Certificate.Export(X509ContentType.Cert); var exportString = _pemService.GetPem("CERTIFICATE", certificateExport); File.WriteAllText(Path.Combine(_path, $"{name}-crt.pem"), exportString); // Rest of the chain var chain = new X509Chain(); chain.Build(input.Certificate); for (var i = 1; i < chain.ChainElements.Count; i++) { var chainCertificate = chain.ChainElements[i].Certificate; // Do not include self-signed certificates, root certificates // are supposed to be known already by the client. if (chainCertificate.Subject != chainCertificate.Issuer) { var chainCertificateExport = chainCertificate.Export(X509ContentType.Cert); exportString += _pemService.GetPem("CERTIFICATE", chainCertificateExport); } } // Save complete chain File.WriteAllText(Path.Combine(_path, $"{name}-chain.pem"), exportString); // Private key var pkPem = ""; var store = new Pkcs12Store(input.CacheFile.OpenRead(), input.CacheFilePassword.ToCharArray()); var alias = store.Aliases.OfType <string>().FirstOrDefault(p => store.IsKeyEntry(p)); var entry = store.GetKey(alias); var key = entry.Key; if (key.IsPrivate) { pkPem = _pemService.GetPem(entry.Key); } if (!string.IsNullOrEmpty(pkPem)) { File.WriteAllText(Path.Combine(_path, $"{name}-key.pem"), pkPem); } else { _log.Warning("No private key found"); } input.StoreInfo.Add(GetType(), new StoreInfo() { Name = PemFilesOptions.PluginName, Path = _path }); } catch (Exception ex) { _log.Error(ex, "Error exporting .pem files to folder"); } }
public static void Main(String[] args) { DirectoryInfo directory = new DirectoryInfo(DEST); directory.Create(); Properties properties = new Properties(); // Specify the correct path to the certificate properties.Load(new FileStream("c:/home/blowagie/key.properties", FileMode.Open, FileAccess.Read)); String path = properties.GetProperty("PRIVATE"); char[] pass = properties.GetProperty("PASSWORD").ToCharArray(); Pkcs12Store pk12 = new Pkcs12Store(new FileStream(path, FileMode.Open, FileAccess.Read), pass); string alias = null; foreach (var a in pk12.Aliases) { alias = ((string)a); if (pk12.IsKeyEntry(alias)) { break; } } ICipherParameters pk = pk12.GetKey(alias).Key; X509CertificateEntry[] ce = pk12.GetCertificateChain(alias); X509Certificate[] chain = new X509Certificate[ce.Length]; for (int k = 0; k < ce.Length; ++k) { chain[k] = ce[k].Certificate; } FileStream fileStream = new FileStream(CRLURL, FileMode.Open, FileAccess.Read); MemoryStream baos = new MemoryStream(); byte[] buf = new byte[1024]; while (fileStream.Read(buf, 0, buf.Length) != 0) { baos.Write(buf, 0, buf.Length); } /* Create a CrlClientOffline instance with the read CRL file's data. * Given CRL file is specific to the CAcert provider and was downloaded long time ago. * Make sure that you have the CRL specific for your certificate and CRL is up to date * (by checking NextUpdate properties as seen below). */ ICrlClient crlClient = new CrlClientOffline(baos.ToArray()); X509Crl crl = new X509CrlParser().ReadCrl(new FileStream(CRLURL, FileMode.Open, FileAccess.Read)); Console.WriteLine("CRL valid until: " + crl.NextUpdate); Console.WriteLine("Certificate revoked: " + crl.IsRevoked(chain[0])); IList <ICrlClient> crlList = new List <ICrlClient>(); crlList.Add(crlClient); new C3_05_SignWithCRLOffline().Sign(SRC, DEST + RESULT_FILES[0], chain, pk, DigestAlgorithms.SHA256, PdfSigner.CryptoStandard.CMS, "Test", "Ghent", crlList, null, null, 0); }
public async Task Save(CertificateInfo input) { _log.Information("Exporting .pem files to {folder}", _path); try { // Determine name var name = input.CommonName.Replace("*", "_"); // Base certificate var certificateExport = input.Certificate.Export(X509ContentType.Cert); var certString = _pemService.GetPem("CERTIFICATE", certificateExport); var chainString = ""; await File.WriteAllTextAsync(Path.Combine(_path, $"{name}-crt.pem"), certString); // Rest of the chain foreach (var chainCertificate in input.Chain) { // Do not include self-signed certificates, root certificates // are supposed to be known already by the client. if (chainCertificate.Subject != chainCertificate.Issuer) { var chainCertificateExport = chainCertificate.Export(X509ContentType.Cert); chainString += _pemService.GetPem("CERTIFICATE", chainCertificateExport); } } // Save complete chain await File.WriteAllTextAsync(Path.Combine(_path, $"{name}-chain.pem"), certString + chainString); await File.WriteAllTextAsync(Path.Combine(_path, $"{name}-chain-only.pem"), chainString); input.StoreInfo.TryAdd( GetType(), new StoreInfo() { Name = PemFilesOptions.PluginName, Path = _path }); // Private key if (input.CacheFile != null) { var pkPem = ""; var store = new Pkcs12Store(input.CacheFile.OpenRead(), input.CacheFilePassword?.ToCharArray()); var alias = store.Aliases.OfType <string>().FirstOrDefault(p => store.IsKeyEntry(p)); if (alias == null) { _log.Warning("No key entries found"); return; } var entry = store.GetKey(alias); var key = entry.Key; if (key.IsPrivate) { pkPem = _pemService.GetPem(entry.Key, _password); } if (!string.IsNullOrEmpty(pkPem)) { await File.WriteAllTextAsync(Path.Combine(_path, $"{name}-key.pem"), pkPem); } else { _log.Warning("No private key found in Pkcs12Store"); } } else { _log.Warning("No private key found in cache"); } } catch (Exception ex) { _log.Error(ex, "Error exporting .pem files to folder"); } }
/// <summary> /// Sign (fill) named field in the document hard way (touch file descriptor, create and close stamper) /// </summary> /// <param name="fileName">PDF file</param> /// <param name="fieldName">Field to be signed</param> /// <param name="reason">Sign reason</param> /// <param name="location">Sign location</param> /// <param name="graphics">Sign graphic</param> /// <param name="certFile">PFX certificate</param> /// <param name="certPassword">password of certificate</param> /// <param name="renderingMode">SignatureRender renderingMode</param> /// <param name="certificationLevel">PdfSignatureAppearance Certification Level</param> /// <returns>Successfull or not</returns> public static bool SignField(string fileName, string fieldName, string reason, string location, Bitmap graphics, string certFile, string certPassword, PdfSignatureAppearance.SignatureRender renderingMode = PdfSignatureAppearance.SignatureRender.GraphicAndDescription, int certificationLevel = PdfSignatureAppearance.CERTIFIED_NO_CHANGES_ALLOWED) { bool result = false; try { PdfReader reader = new PdfReader(fileName); if (reader.AcroFields.Fields.ContainsKey(fieldName)) { string tempFile = Path.GetTempFileName(); FileStream fs = new FileStream(tempFile, FileMode.Create); PdfStamper stamper = PdfStamper.CreateSignature(reader, fs, '\0'); PdfSignatureAppearance psa = GetPSA(fieldName, stamper, graphics, reason, location, renderingMode, certificationLevel); Pkcs12Store store = new Pkcs12Store(new FileStream(certFile, FileMode.Open), certPassword.ToCharArray()); string alias = ""; ICollection <X509Certificate> chain = new List <X509Certificate>(); foreach (string al in store.Aliases) { if (store.IsKeyEntry(al) && store.GetKey(al).Key.IsPrivate) { alias = al; break; } } AsymmetricKeyEntry ake = store.GetKey(alias); foreach (X509CertificateEntry c in store.GetCertificateChain(alias)) { chain.Add(c.Certificate); } RsaPrivateCrtKeyParameters parameters = ake.Key as RsaPrivateCrtKeyParameters; psa.SetCrypto(parameters, chain.ToArray(), null, PdfSignatureAppearance.WINCER_SIGNED); stamper.Close(); reader.Close(); File.Copy(tempFile, fileName, true); result = true; } else { result = false; } } catch (Exception e) { Console.WriteLine(e.Message); result = false; } return(result); }
public byte[] GenerirajPotpisaniDokument(byte[] document, string documentName, string signingReason, string signingLocation) { try { string alias = ""; List <Org.BouncyCastle.X509.X509Certificate> chain = new List <Org.BouncyCastle.X509.X509Certificate>(); var location = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, AppDomain.CurrentDomain.RelativeSearchPath ?? ""); //var destinationPath = $@"Data\{documentName}"; //destinationPath = Path.Combine(location, destinationPath); var destinationPath = iConfig["DocumentDestinationPath"] + documentName; var certPath = @"C:\Users\Crega\Source\Repos\PdfSigner\PdfSigner\bin\Debug\netcoreapp3.0\certifikat.pfx"; certPath = Path.Combine(location, certPath); var cert = File.ReadAllBytes(certPath); Stream certStream = new MemoryStream(cert); Pkcs12Store store = new Pkcs12Store(certStream, "12345".ToCharArray()); // 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; Stream documentStream = new MemoryStream(document); PdfReader reader = new PdfReader(documentStream); FileStream os = new FileStream(destinationPath, FileMode.Create); StampingProperties sp = new StampingProperties(); iText.Signatures.PdfSigner signer = new iText.Signatures.PdfSigner(reader, os, sp); PdfSignatureAppearance appearance = signer.GetSignatureAppearance(); appearance.SetReason(signingReason); appearance.SetLocation(signingLocation); appearance.SetContact("*****@*****.**"); //appearance.SetPageRect(new iText.Kernel.Geom.Rectangle(36, 748, 144, 780)); appearance.SetPageNumber(1); appearance.SetCertificate(chain[0]); // Creating the signature IExternalSignature pks = new PrivateKeySignature(parameters, DigestAlgorithms.SHA256); signer.SignDetached(pks, chain.ToArray(), null, null, null, 0, iText.Signatures.PdfSigner.CryptoStandard.CADES); //MakeSignature.SignDetached(appearance, pks, chain, null, null, null, 0, PdfSigner.CryptoStandard.CADES); os.Close(); certStream.Close(); var documentToReturn = File.ReadAllBytes(destinationPath); File.Delete(destinationPath); return(documentToReturn); } catch (Exception ex) { } return(null); }
public static void Main(String[] args) { DirectoryInfo directory = new DirectoryInfo(DEST); directory.Create(); Pkcs12Store pk12 = new Pkcs12Store(new FileStream(KEYSTORE, FileMode.Open, FileAccess.Read), PASSWORD); string alias = null; foreach (var a in pk12.Aliases) { alias = ((string)a); if (pk12.IsKeyEntry(alias)) { break; } } ICipherParameters pk = pk12.GetKey(alias).Key; X509CertificateEntry[] ce = pk12.GetCertificateChain(alias); X509Certificate[] chain = new X509Certificate[ce.Length]; for (int k = 0; k < ce.Length; ++k) { chain[k] = ce[k].Certificate; } C2_09_SignatureTypes app = new C2_09_SignatureTypes(); app.Sign(SRC, DEST + RESULT_FILES[0], chain, pk, DigestAlgorithms.SHA256, PdfSigner.CryptoStandard.CMS, PdfSigner.NOT_CERTIFIED, "Test 1", "Ghent"); app.Sign(SRC, DEST + RESULT_FILES[1], chain, pk, DigestAlgorithms.SHA256, PdfSigner.CryptoStandard.CMS, PdfSigner.CERTIFIED_FORM_FILLING_AND_ANNOTATIONS, "Test 1", "Ghent"); app.Sign(SRC, DEST + RESULT_FILES[2], chain, pk, DigestAlgorithms.SHA256, PdfSigner.CryptoStandard.CMS, PdfSigner.CERTIFIED_FORM_FILLING, "Test 1", "Ghent"); app.Sign(SRC, DEST + RESULT_FILES[3], chain, pk, DigestAlgorithms.SHA256, PdfSigner.CryptoStandard.CMS, PdfSigner.CERTIFIED_NO_CHANGES_ALLOWED, "Test 1", "Ghent"); app.AddAnnotation(DEST + RESULT_FILES[0], DEST + RESULT_FILES[4]); app.AddAnnotation(DEST + RESULT_FILES[1], DEST + RESULT_FILES[5]); app.AddAnnotation(DEST + RESULT_FILES[2], DEST + RESULT_FILES[6]); app.AddAnnotation(DEST + RESULT_FILES[3], DEST + RESULT_FILES[7]); app.AddWrongAnnotation(DEST + RESULT_FILES[0], DEST + RESULT_FILES[8]); app.AddText(DEST + RESULT_FILES[0], DEST + RESULT_FILES[9]); app.SignAgain(DEST + RESULT_FILES[0], DEST + RESULT_FILES[10], chain, pk, DigestAlgorithms.SHA256, PdfSigner.CryptoStandard.CMS, "Second signature test", "Gent"); app.SignAgain(DEST + RESULT_FILES[1], DEST + RESULT_FILES[11], chain, pk, DigestAlgorithms.SHA256, PdfSigner.CryptoStandard.CMS, "Second signature test", "Gent"); app.SignAgain(DEST + RESULT_FILES[2], DEST + RESULT_FILES[12], chain, pk, DigestAlgorithms.SHA256, PdfSigner.CryptoStandard.CMS, "Second signature test", "Gent"); app.SignAgain(DEST + RESULT_FILES[3], DEST + RESULT_FILES[13], chain, pk, DigestAlgorithms.SHA256, PdfSigner.CryptoStandard.CMS, "Second signature test", "Gent"); }
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); } }
public virtual ImportedKeySet Pkcs12Keys(KeyPurpose purpose, Stream input, Func <string> passwordPrompt = null, bool official = false, KeyType hint = null) { using (var password = CachedPrompt.Password(passwordPrompt)) { var keyStore = new Pkcs12Store(input, password.Prompt().ToCharArray()); var keys = new List <Key>(); foreach (string n in keyStore.Aliases) { if (keyStore.IsKeyEntry(n)) { AsymmetricKeyEntry key = keyStore.GetKey(n); if (key.Key.IsPrivate) { switch (key.Key) { case RsaPrivateCrtKeyParameters rsa: keys.Add(KeyFromBouncyCastle(rsa, purpose, official, hint)); break; case DsaPrivateKeyParameters dsa: if (purpose == KeyPurpose.SignAndVerify) { keys.Add(KeyFromBouncyCastle(dsa)); } break; } } } } if (!keys.Any()) { foreach (string n in keyStore.Aliases) { if (keyStore.IsCertificateEntry(n)) { var entry = keyStore.GetCertificate(n); var pubKey = entry.Certificate.GetPublicKey(); switch (pubKey) { case RsaKeyParameters rsa: keys.Add(KeyFromBouncyCastle(rsa, purpose, official, hint)); break; case DsaPublicKeyParameters dsa: if (purpose == KeyPurpose.SignAndVerify) { keys.Add(KeyFromBouncyCastle(dsa)); } break; } } } } if (keys.Any()) { return(new ImportedKeySet(keys, purpose, "imported keys")); } throw new InvalidKeySetException("couldn't find any keys in file"); } }
public static void Main(String[] args) { // we make a connection to a PreSign servlet HttpWebRequest request = (HttpWebRequest)WebRequest.Create(PRE); request.Method = "POST"; // we upload our self-signed certificate Stream os = request.GetRequestStream(); FileStream fis = new FileStream(CERT, FileMode.Open); int read; byte[] data = new byte[0x100]; while ((read = fis.Read(data, 0, data.Length)) != 0) { os.Write(data, 0, read); } os.Flush(); os.Close(); HttpWebResponse response = (HttpWebResponse)request.GetResponse(); // we use cookies to maintain a session String cookies = response.Headers["Set-Cookie"]; // we receive a hash that needs to be signed Stream istream = response.GetResponseStream(); MemoryStream baos = new MemoryStream(); data = new byte[0x100]; while ((read = istream.Read(data, 0, data.Length)) != 0) { baos.Write(data, 0, read); } istream.Close(); byte[] hash = baos.ToArray(); // we load our private key from the key store Pkcs12Store store = new Pkcs12Store(new FileStream(KEYSTORE, FileMode.Open), PASSWORD); String alias = ""; // 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); // we sign the hash received from the server ISigner sig = SignerUtilities.GetSigner("SHA256withRSA"); sig.Init(true, pk.Key); sig.BlockUpdate(hash, 0, hash.Length); data = sig.GenerateSignature(); // we make a connection to the PostSign Servlet request = (HttpWebRequest)WebRequest.Create(POST); request.Headers.Add(HttpRequestHeader.Cookie, cookies.Split(";".ToCharArray(), 2)[0]); request.Method = "POST"; // we upload the signed bytes os = request.GetRequestStream(); os.Write(data, 0, data.Length); os.Flush(); os.Close(); // we receive the signed document response = (HttpWebResponse)request.GetResponse(); istream = response.GetResponseStream(); FileStream fos = new FileStream(DEST, FileMode.Create); data = new byte[0x100]; while ((read = istream.Read(data, 0, data.Length)) != 0) { fos.Write(data, 0, read); } istream.Close(); fos.Flush(); fos.Close(); }
public async Task <byte[]> Sign(byte[] source, SigningProperties signingProperties) { using (var inputStream = new MemoryStream(source)) using (var reader = new PdfReader(inputStream)) using (var outputStream = new MemoryStream()) { var stampProps = new StampingProperties(); var signer = new PdfSigner(reader, outputStream, stampProps); signer.SetCertificationLevel(PdfSigner.CERTIFIED_NO_CHANGES_ALLOWED); var sap = signer.GetSignatureAppearance(); sap.SetLocation(signingProperties.Location); sap.SetReason(signingProperties.Reason); sap.SetReuseAppearance(false); var certData = await s3Repository.GetDocument(signingProperties.Bucket, signingProperties.Key); // code from https://stackoverflow.com/questions/12470498/how-to-read-the-pfx-file using (var keyStream = new MemoryStream(certData)) { var passphrase = signingProperties.Password; if (signingProperties.KMSData != null) { // key is encrypted with KSM var key = await kSMRepository.GetKey(signingProperties.KMSData); passphrase = kSMRepository.DecryptData(passphrase, key); } var store = new Pkcs12Store(keyStream, signingProperties.Password.ToCharArray()); string alias = store.Aliases.OfType <string>().First(x => store.IsKeyEntry(x)); var privateKey = store.GetKey(alias).Key; var keyChain = store.GetCertificateChain(alias) .Select(x => x.Certificate).ToArray(); IExternalSignature externalSignature = new PrivateKeySignature(privateKey, DigestAlgorithms.SHA256); signer.SignDetached(externalSignature, keyChain, null, null, null, 0, PdfSigner.CryptoStandard.CADES); return(outputStream.ToArray()); } } }
public static void Main(String[] args) { DirectoryInfo directory = new DirectoryInfo(DEST); directory.Create(); // Make a connection to a PreSign servlet to ask to create a document, // then calculate its hash and send it to us HttpWebRequest request = (HttpWebRequest)WebRequest.Create(PRE); request.Method = "POST"; // Upload our self-signed certificate Stream os = request.GetRequestStream(); byte[] data = new byte[256]; int read; using (FileStream fis = new FileStream(CERT, FileMode.Open)) { while ((read = fis.Read(data, 0, data.Length)) != 0) { os.Write(data, 0, read); } } os.Flush(); os.Close(); HttpWebResponse response = (HttpWebResponse)request.GetResponse(); // Use cookies to maintain a session String cookies = response.Headers["Set-Cookie"]; // Receive a hash that needs to be signed Stream istream = response.GetResponseStream(); MemoryStream memoryStream = new MemoryStream(); istream.CopyTo(memoryStream); istream.Close(); byte[] hash = memoryStream.ToArray(); // Load our private key from the key store Pkcs12Store store = new Pkcs12Store(new FileStream(KEYSTORE, FileMode.Open, FileAccess.Read), PASSWORD); // Searching for private key String alias = null; foreach (string al in store.Aliases) { if (store.IsKeyEntry(al) && store.GetKey(al).Key.IsPrivate) { alias = al; break; } } AsymmetricKeyEntry pk = store.GetKey(alias); // Sign the hash received from the server ISigner sig = SignerUtilities.GetSigner("SHA256withRSA"); sig.Init(true, pk.Key); sig.BlockUpdate(hash, 0, hash.Length); data = sig.GenerateSignature(); // Make a connection to the PostSign Servlet request = (HttpWebRequest)WebRequest.Create(POST); request.Headers.Add(HttpRequestHeader.Cookie, cookies.Split(";".ToCharArray(), 2)[0]); request.Method = "POST"; // Upload the signed bytes os = request.GetRequestStream(); os.Write(data, 0, data.Length); os.Flush(); os.Close(); // Receive the signed document response = (HttpWebResponse)request.GetResponse(); istream = response.GetResponseStream(); using (FileStream fos = new FileStream(DEST + RESULT_FILES[0], FileMode.Create)) { data = new byte[256]; while ((read = istream.Read(data, 0, data.Length)) != 0) { fos.Write(data, 0, read); } istream.Close(); } }
/// <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 string PdfSign(byte[] signature, string certPath, string password, string name, string reason, iTextSharp.text.Rectangle signatureRect, int signaturePage, string fieldName, double dsvScore) { FileStream ksfs = null; Pkcs12Store pk12 = null; try { ksfs = new FileStream(certPath, FileMode.Open); pk12 = new Pkcs12Store(ksfs, password.ToCharArray()); string alias = ""; foreach (string al in pk12.Aliases) { if (pk12.IsKeyEntry(al) && pk12.GetKey(al).Key.IsPrivate) { alias = al; break; } } Org.BouncyCastle.Pkcs.X509CertificateEntry[] ce = pk12.GetCertificateChain(alias); ICollection <X509Certificate> chain = new List <X509Certificate>(); foreach (X509CertificateEntry c in ce) { chain.Add(c.Certificate); } AsymmetricKeyEntry pk = pk12.GetKey(alias); RsaPrivateCrtKeyParameters parameters = pk.Key as RsaPrivateCrtKeyParameters; string tmpFile = System.IO.Path.GetTempFileName(); FileStream fs = new FileStream(tmpFile, FileMode.Create); PdfStamper stamper = PdfStamper.CreateSignature(reader, fs, '\0'); PdfContentByte cb = stamper.GetOverContent(signaturePage); Image integrityImage = Properties.Resources.integrity_red; if (dsvScore > Properties.Settings.Default.GreenThreshold) { integrityImage = Properties.Resources.integrity; } else if (dsvScore > Properties.Settings.Default.YellowThreshold) { integrityImage = Properties.Resources.integrity_yellow; } iTextSharp.text.Image imgIntegrity = iTextSharp.text.Image.GetInstance(integrityImage, ImageFormat.Png); imgIntegrity.SetAbsolutePosition(signatureRect.Left, signatureRect.Bottom - 20); imgIntegrity.ScalePercent(50.0f); cb.AddImage(imgIntegrity); iTextSharp.text.Image imgVerified = iTextSharp.text.Image.GetInstance(Properties.Resources.verified, ImageFormat.Png); imgVerified.SetAbsolutePosition(signatureRect.Left + 20, signatureRect.Bottom - 20); imgVerified.ScalePercent(50.0f); cb.AddImage(imgVerified); PdfSignatureAppearance appearance = stamper.SignatureAppearance; appearance.Reason = reason; //uncomment this portion only //appearance.SignatureGraphic = iTextSharp.text.Image.GetInstance(signature); //appearance.SignatureRenderingMode = PdfSignatureAppearance.RenderingMode.GRAPHIC_AND_DESCRIPTION; //appearance.SetVisibleSignature(new iTextSharp.text.Rectangle(40, 110, 240, 210), 1, "Signature"); appearance.SetVisibleSignature(signatureRect, signaturePage, fieldName); //appearance.Certificate = chain[0]; to remain commented out /* * PdfTemplate n2 = appearance.GetLayer(2); * ColumnText ct = new ColumnText(n2); * ct.SetSimpleColumn(n2.BoundingBox); * string backgroundText = "Digitally signed by " + Properties.Settings.Default.DefaultName + "\nOn: " + appearance.SignDate.ToString() + "\nReason: " + appearance.Reason; * iTextSharp.text.Paragraph paragraph = new iTextSharp.text.Paragraph(backgroundText); * ct.AddElement(paragraph); * ct.Go(); */ string backgroundText = "Digitally signed by " + name + "\nOn: " + appearance.SignDate.ToString() + "\nReason: " + appearance.Reason; appearance.Layer2Text = backgroundText; appearance.Image = iTextSharp.text.Image.GetInstance(signature); //appearance.ImageScale = 1; IExternalSignature pks = new PrivateKeySignature((ICipherParameters)parameters, DigestAlgorithms.SHA256); MakeSignature.SignDetached(appearance, pks, chain, null, null, null, 0, CryptoStandard.CADES); ksfs.Close(); //stamper.Close(); //fs.Close(); return(tmpFile); } catch (Exception ex) { MessageBox.Show(ex.Message); return(null); } }
/// <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(nameof(stream)); } if (password == null) { throw new ArgumentNullException(nameof(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++) { Import(chain[i].Certificate, true); } } else if (pkcs12.IsCertificateEntry(alias)) { var entry = pkcs12.GetCertificate(alias); Import(entry.Certificate, true); } } }
private static bool SignFile(ref string filename) { Signing s = new Signing(); if (!s.LoadFile(filename)) { Console.WriteLine("error loading xml file:" + filename); Environment.Exit(-1); return(false); } AsymmetricKeyEntry key = null; Org.BouncyCastle.X509.X509Certificate cert = null; try { string signercert = ConfigurationManager.AppSettings["signercert"].ToString(); string signerpwd = ConfigurationManager.AppSettings["signerpwd"].ToString(); FileStream fs = new FileStream(signercert, FileMode.Open, FileAccess.Read); Pkcs12Store store = new Pkcs12Store(fs, signerpwd.ToCharArray()); string pName = null; foreach (string n in store.Aliases) { if (store.IsKeyEntry(n)) { pName = n; break; } } key = store.GetKey(pName); cert = store.GetCertificate(pName).Certificate; } catch (Exception) { Console.WriteLine("error loading signer (config)"); Environment.Exit(-1); return(false); } if ((null == key) || (null == cert)) { Console.WriteLine("error loading signer (config) (2)"); Environment.Exit(-1); return(false); } string signedxml = ""; try { byte[] tobesigned = s.AddSignature(cert); // sha256WithRSAEncryption DerObjectIdentifier signingAlgo = new DerObjectIdentifier("1.2.840.113549.1.1.11"); ISigner signer = SignerUtilities.GetSigner(signingAlgo); signer.Init(true, key.Key); signer.BlockUpdate(tobesigned, 0, tobesigned.Length); byte[] signed = signer.GenerateSignature(); s.SetSignature(signed); signedxml = s.GetXml(); } catch (Exception) { Console.WriteLine("error signing xml"); Environment.Exit(-1); return(false); } filename += ".sig"; File.WriteAllText(filename, signedxml); return(true); }
private static void DoSignPdfFile(PdfStamper stamper, ConversionProfile profile, JobPasswords jobPasswords) { var signing = profile.PdfSettings.Signature; if (!signing.Enabled) //Leave without signing { return; } Logger.Debug("Start signing file."); signing.CertificateFile = Path.GetFullPath(signing.CertificateFile); if (string.IsNullOrEmpty(jobPasswords.PdfSignaturePassword)) { Logger.Error("Launched signing without certification password."); throw new ProcessingException("Launched signing without certification password.", 12204); } if (IsValidCertificatePassword(signing.CertificateFile, jobPasswords.PdfSignaturePassword) == false) { Logger.Error("Canceled signing. The password for certificate '" + signing.CertificateFile + "' is wrong."); throw new ProcessingException( "Canceled signing. The password for certificate '" + signing.CertificateFile + "' is wrong.", 12200); } if (CertificateHasPrivateKey(signing.CertificateFile, jobPasswords.PdfSignaturePassword) == false) { Logger.Error("Canceled signing. The certificate '" + signing.CertificateFile + "' has no private key."); throw new ProcessingException( "Canceled signing. The certificate '" + signing.CertificateFile + "' has no private key.", 12201); } var fsCert = new FileStream(signing.CertificateFile, FileMode.Open); var ks = new Pkcs12Store(fsCert, jobPasswords.PdfSignaturePassword.ToCharArray()); string alias = null; foreach (string al in ks.Aliases) { if (ks.IsKeyEntry(al) && ks.GetKey(al).Key.IsPrivate) { alias = al; break; } } fsCert.Close(); ICipherParameters pk = ks.GetKey(alias).Key; var x = ks.GetCertificateChain(alias); var chain = new X509Certificate[x.Length]; for (var k = 0; k < x.Length; ++k) { chain[k] = x[k].Certificate; } ITSAClient tsc = null; if (!string.IsNullOrEmpty(signing.TimeServerUrl.Trim())) { if (!signing.TimeServerIsSecured) { tsc = new TSAClientBouncyCastle(signing.TimeServerUrl); } else { tsc = new TSAClientBouncyCastle(signing.TimeServerUrl, signing.TimeServerLoginName, signing.TimeServerPassword); } } var psa = stamper.SignatureAppearance; if (tsc == null) { psa.SetCrypto(pk, chain, null, PdfSignatureAppearance.WINCER_SIGNED); } else { psa.SetCrypto(null, chain, null, PdfSignatureAppearance.SELF_SIGNED); } if (!profile.PdfSettings.Signature.AllowMultiSigning) { //Lock PDF, except for annotations and form filling (irrelevant for clawPDF) psa.CertificationLevel = PdfSignatureAppearance.CERTIFIED_FORM_FILLING_AND_ANNOTATIONS; } psa.Reason = signing.SignReason; psa.Contact = signing.SignContact; psa.Location = signing.SignLocation; if (signing.DisplaySignatureInDocument) { var signPage = SignPageNr(stamper, signing); psa.SetVisibleSignature(new Rectangle(signing.LeftX, signing.LeftY, signing.RightX, signing.RightY), signPage, null); } var dic = new PdfSignature(PdfName.ADOBE_PPKLITE, new PdfName("adbe.pkcs7.detached")); dic.Reason = psa.Reason; dic.Location = psa.Location; dic.Contact = psa.Contact; dic.Date = new PdfDate(psa.SignDate); psa.CryptoDictionary = dic; const int contentEstimated = 15000; // Preallocate excluded byte-range for the signature content (hex encoded) var exc = new Dictionary <PdfName, int>(); exc[PdfName.CONTENTS] = contentEstimated * 2 + 2; psa.PreClose(exc); const string hashAlgorithm = "SHA1"; //Always use HashAlgorithm "SHA1" var sgn = new PdfPKCS7(pk, chain, null, hashAlgorithm, false); var messageDigest = DigestUtilities.GetDigest(hashAlgorithm); var data = psa.GetRangeStream(); var buf = new byte[8192]; int n; while ((n = data.Read(buf, 0, buf.Length)) > 0) { messageDigest.BlockUpdate(buf, 0, n); } var hash = new byte[messageDigest.GetDigestSize()]; messageDigest.DoFinal(hash, 0); byte[] ocsp = null; if (chain.Length >= 2) { var url = PdfPKCS7.GetOCSPURL(chain[0]); if (!string.IsNullOrEmpty(url)) { ocsp = new OcspClientBouncyCastle().GetEncoded(chain[0], chain[1], url); } } var cal = psa.SignDate; var sh = sgn.GetAuthenticatedAttributeBytes(hash, cal, ocsp); sgn.Update(sh, 0, sh.Length); var paddedSig = new byte[contentEstimated]; if (tsc != null) { byte[] encodedSigTsa = null; try { encodedSigTsa = sgn.GetEncodedPKCS7(hash, cal, tsc, ocsp); Array.Copy(encodedSigTsa, 0, paddedSig, 0, encodedSigTsa.Length); } catch (Exception ex) { throw new ProcessingException( ex.GetType() + " while connecting to timeserver (can't connect to timeserver): " + ex.Message, 12205); } if (contentEstimated + 2 < encodedSigTsa.Length) { throw new ProcessingException( "Not enough space for signature", 12202); } } else { var encodedSig = sgn.GetEncodedPKCS7(hash, cal); Array.Copy(encodedSig, 0, paddedSig, 0, encodedSig.Length); if (contentEstimated + 2 < encodedSig.Length) { throw new ProcessingException("Not enough space for signature", 12203); } } var dic2 = new PdfDictionary(); dic2.Put(PdfName.CONTENTS, new PdfString(paddedSig).SetHexWriting(true)); psa.Close(dic2); }
private string signWithGraphic(byte[] signature) { OpenFileDialog ofd = new OpenFileDialog(); ofd.Filter = " PKCS#12 Files|*.pfx;*.p12"; DialogResult dResult = ofd.ShowDialog(); if (dResult != DialogResult.OK) { return(null); } string pfxFile = ofd.FileName; string password = InputBox.show("Enter Password", true, this); if (password == null) { return(null); } FileStream ksfs = new FileStream(pfxFile, FileMode.Open); Pkcs12Store pk12; try { pk12 = new Pkcs12Store(ksfs, password.ToCharArray()); } catch (Exception ex) { MessageBox.Show("Incorrect Passphrase - " + ex.Message); ksfs.Dispose(); return(null); } string alias = ""; foreach (string al in pk12.Aliases) { if (pk12.IsKeyEntry(al) && pk12.GetKey(al).Key.IsPrivate) { alias = al; break; } } Org.BouncyCastle.Pkcs.X509CertificateEntry[] ce = pk12.GetCertificateChain(alias); ICollection <X509Certificate> chain = new List <X509Certificate>(); foreach (X509CertificateEntry c in ce) { chain.Add(c.Certificate); } AsymmetricKeyEntry pk = pk12.GetKey(alias); RsaPrivateCrtKeyParameters parameters = pk.Key as RsaPrivateCrtKeyParameters; string tmpFile = System.IO.Path.GetTempFileName(); FileStream fs = new FileStream(tmpFile, FileMode.Create); PdfStamper stamper = PdfStamper.CreateSignature(reader, fs, '\0'); PdfSignatureAppearance appearance = stamper.SignatureAppearance; appearance.Reason = Properties.Settings.Default.DefaultReason; appearance.Location = Properties.Settings.Default.DefaultLocation; appearance.Contact = Properties.Settings.Default.DefaultContact; //uncomment this portion only //appearance.SignatureGraphic = iTextSharp.text.Image.GetInstance(signature); //appearance.SignatureRenderingMode = PdfSignatureAppearance.RenderingMode.GRAPHIC_AND_DESCRIPTION; appearance.SetVisibleSignature(new iTextSharp.text.Rectangle(40, 110, 240, 210), 1, "Signature"); //appearance.Certificate = chain[0]; to remain commented out /* * PdfTemplate n2 = appearance.GetLayer(2); * ColumnText ct = new ColumnText(n2); * ct.SetSimpleColumn(n2.BoundingBox); * string backgroundText = "Digitally signed by " + Properties.Settings.Default.DefaultName + "\nOn: " + appearance.SignDate.ToString() + "\nReason: " + appearance.Reason; * iTextSharp.text.Paragraph paragraph = new iTextSharp.text.Paragraph(backgroundText); * ct.AddElement(paragraph); * ct.Go(); */ string backgroundText = "Digitally signed by " + Properties.Settings.Default.DefaultName + "\nOn: " + appearance.SignDate.ToString() + "\nReason: " + appearance.Reason; appearance.Layer2Text = backgroundText; appearance.Image = iTextSharp.text.Image.GetInstance(signature); //appearance.ImageScale = 1; IExternalSignature pks = new PrivateKeySignature((ICipherParameters)parameters, DigestAlgorithms.SHA256); MakeSignature.SignDetached(appearance, pks, chain, null, null, null, 0, CryptoStandard.CADES); ksfs.Dispose(); //stamper.Close(); //fs.Close(); return(tmpFile); }
public static void Main(String[] args) { DirectoryInfo directory = new DirectoryInfo(DEST); directory.Create(); Properties properties = new Properties(); // Specify the correct path to the certificate properties.Load(new FileStream("c:/home/blowagie/key.properties", FileMode.Open, FileAccess.Read)); String path = properties.GetProperty("PRIVATE"); char[] pass = properties.GetProperty("PASSWORD").ToCharArray(); String tsaUrl = properties.GetProperty("TSAURL"); String tsaUser = properties.GetProperty("TSAUSERNAME"); String tsaPass = properties.GetProperty("TSAPASSWORD"); Pkcs12Store pk12 = new Pkcs12Store(new FileStream(path, FileMode.Open, FileAccess.Read), pass); string alias = null; foreach (var a in pk12.Aliases) { alias = ((string)a); if (pk12.IsKeyEntry(alias)) { break; } } ICipherParameters pk = pk12.GetKey(alias).Key; X509CertificateEntry[] ce = pk12.GetCertificateChain(alias); X509Certificate[] chain = new X509Certificate[ce.Length]; for (int k = 0; k < ce.Length; ++k) { chain[k] = ce[k].Certificate; } IOcspClient ocspClient = new OcspClientBouncyCastle(null); ITSAClient tsaClient = new TSAClientBouncyCastle(tsaUrl, tsaUser, tsaPass); C3_12_SignWithEstimatedSize app = new C3_12_SignWithEstimatedSize(); bool succeeded = false; int estimatedSize = 1000; while (!succeeded) { try { Console.WriteLine("Attempt: " + estimatedSize + " bytes"); app.Sign(SRC, DEST, chain, pk, DigestAlgorithms.SHA256, PdfSigner.CryptoStandard.CMS, "Test", "Ghent", null, ocspClient, tsaClient, estimatedSize); succeeded = true; Console.WriteLine("Succeeded!"); } catch (IOException ioe) { Console.WriteLine("Not succeeded: " + ioe.Message); estimatedSize += 50; } } }
/// <summary> /// Signs a PDF document using iTextSharp library /// </summary> /// <param name="sourceDocument">The path of the source pdf document which is to be signed</param> /// <param name="destinationDocument">The path at which the signed pdf document should be generated</param> /// <param name="privateKeyStream">A Stream containing the private/public key in .pfx format which would be used to sign the document</param> /// <param name="pfxKeyPass">The password for the private key</param> /// <param name="reasonForSigning">String describing the reason for signing, would be embedded as part of the signature</param> /// <param name="location">Location where the document was signed, would be embedded as part of the signature</param> public void SignPdfFile(string sourceDocument, string destinationDocument, PdfSignInfo info) { using (var cpfxFile = new FileStream(info.pfxFilePath, FileMode.Open, FileAccess.Read)) { Pkcs12Store pk12 = new Pkcs12Store(cpfxFile, info.pfxKeyPass.ToCharArray()); string alias = null; foreach (string tAlias in pk12.Aliases) { if (pk12.IsKeyEntry(tAlias)) { alias = tAlias; break; } } var pk = pk12.GetKey(alias).Key; using (var reader = new PdfReader(sourceDocument)) using (var fout = new FileStream(destinationDocument, FileMode.Create, FileAccess.ReadWrite)) using (var stamper = PdfStamper.CreateSignature(reader, fout, '\0')) { if (info.DocPass != null) { stamper.SetEncryption(info.DocPass, info.DocPass, PdfWriter.ALLOW_SCREENREADERS, PdfWriter.STRENGTH128BITS); } var img = new iTextSharp.text.Jpeg(new Uri(info.SignImagePath)); PdfSignatureAppearance appearance = stamper.SignatureAppearance; appearance.Image = img; appearance.Reason = info.ReasonForSigning; appearance.Location = info.Location; const float x = 20, y = 10; appearance.SetVisibleSignature(new iTextSharp.text.Rectangle(x, y, x + img.Width, y + img.Width), 1, "Icsi-Vendor"); IExternalSignature es = new PrivateKeySignature(pk, "SHA-256"); MakeSignature.SignDetached(appearance, es, new X509Certificate[] { pk12.GetCertificate(alias).Certificate }, null, null, null, 0, CryptoStandard.CMS); //http://www.phronesisweb.com/blog/filling-pdf-acrofields-in-c-using-itextsharp/ AcroFields form = stamper.AcroFields; form.GenerateAppearances = true; ////form.SetField("name", "John Doe"); ////form.SetField("address", "xxxxx, yyyy"); ////form.SetField("postal_code", "12345"); ////form.SetField("email", "*****@*****.**"); if (info.MetaData != null) { lock (info.MetaData) { foreach (Tuple <string, string> kv in info.MetaData) { form.SetField(kv.Item1, kv.Item2); //form.SetFieldProperty(kv.Item1.Compress(), "fflags", 0, null); } } } //http://forums.asp.net/t/1846462.aspx?PDF+form+contents+are+not+visible+iTextSharp //Dictionary<string, string> inf = reader.Info; ////inf.Add("Title", "Hello World stamped"); ////inf.Add("Subject", "Hello World with changed metadata"); ////inf.Add("Keywords", "iText in Action, PdfStamper"); ////inf.Add("Creator", "Silly standalone example"); ////inf.Add("Author", "Also Bruno Lowagie"); //if (info.MetaData != null) //{ // lock (info.MetaData) // foreach (Tuple<string, string> kv in info.MetaData) // inf.Add(kv.Item1, kv.Item2); // stamper.MoreInfo = inf; //} //stamper.SetFullCompression(); //stamper.Writer.SetFullCompression(); stamper.FormFlattening = true; stamper.Close(); } } }