iTextSharp – Frequently asked questions – Part 2

In previous part C#,iTextSharp – PDF file – Insert/extract image,text,font, text highlighting and auto fillin, I listed some code listings for typical features of iTextSharp in editing PDF files. That post just gets growing up and too long, therefore I would like to continue the work in this second one.

1. Sign PDF

1.1 Certificate

To sign a PDF file we need a certifcate in .cer and .pfx format. For code demo, I’ll use OpenSSL for generating certificate files with following commands.

openssl req -new -newkey rsa:1024 -days 365 -extensions v3_ca -subj "/C=VN/ST=SG/L=SaiGon/O=SuperVerisign/OU=RootCA/CN=SuperVerisignRootCA/" -nodes -x509 -sha256 -set_serial 0 -keyout RootCA.key -out RootCA.cert
openssl req -newkey rsa:1024 -subj "/C=DE/ST=BY/L=Munich/O=HintDesk/OU=Blog/CN=HintDeskBlog/" -nodes -sha256 -keyout HintDesk.key -out HintDesk.csr
openssl x509 -req -sha256 -CAcreateserial -in HintDesk.csr -days 365 -CA RootCA.cert -CAkey RootCA.key -out HintDesk.cert
openssl pkcs12 -export -in HintDesk.cert -inkey HintDesk.key -CSP "Microsoft Enhanced RSA and AES Cryptographic Provider" -out HintDesk.pfx

1.2 Sign PDF file

private static void SignPdfFile(string sourcePath, string destPath, string certificatePath,
	string keyPassword, string reason, string location)
{
	if (File.Exists(destPath))
		File.Delete(destPath);

	var pk12 = new Pkcs12Store(new System.IO.FileStream(certificatePath, System.IO.FileMode.Open, System.IO.FileAccess.Read), keyPassword.ToCharArray());

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

	// reader and stamper
	var reader = new PdfReader(sourcePath);
	using (var fout = new FileStream(destPath, FileMode.Create, FileAccess.ReadWrite))
	{
		using (var stamper = PdfStamper.CreateSignature(reader, fout, '\0'))
		{
			// appearance
			var appearance = stamper.SignatureAppearance;
			//appearance.Image = new iTextSharp.text.pdf.PdfImage();
			appearance.Reason = reason;
			appearance.Location = location;
			appearance.SetVisibleSignature(new Rectangle(20, 10, 170, 60), 1, "HintDesk");
			// digital signature
			IExternalSignature es = new PrivateKeySignature(pk, "SHA-256");
			MakeSignature.SignDetached(appearance, es, new[] { pk12.GetCertificate(alias).Certificate }, null,
				null, null, 0, CryptoStandard.CMS);

			stamper.Close();
		}
	}
}

2. Source code

Source code: https://bitbucket.org/hintdesk/dotnet-itextsharp-pdf-file-insertextract-imagetext-and-auto

Leave a Reply

Your email address will not be published. Required fields are marked *