我正在开发一个Windows应用程序,我需要将数字签名签名为PDF文件,因为我使用了以下代码,这对于.pfx和.p12证书非常有用。
using Org.BouncyCastle.Pkcs;
using System.IO;
using iTextSharp.text.pdf;
using iTextSharp.text.pdf.security;
public class DigitalSignaturePDF
{
public void DigiSignPdf(string sourceDocument,
string destinationPath,
Stream privateKeyStream,
string keyPassword,
string reason,
string location,
bool isVisibleSignature)
{
Pkcs12Store pk12 = new Pkcs12Store(privateKeyStream, keyPassword.ToCharArray());
privateKeyStream.Dispose();
//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
PdfReader reader = new PdfReader(sourceDocument);
using (FileStream fout = new FileStream(destinationPath, FileMode.Append, FileAccess.Write))
{
using (PdfStamper stamper = PdfStamper.CreateSignature(reader, fout, '\0'))
{
// appearance
PdfSignatureAppearance appearance = stamper.SignatureAppearance;
//appearance.Image = new iTextSharp.text.pdf.PdfImage();
appearance.Reason = reason;
appearance.Location = location;
if (isVisibleSignature)
{
appearance.SetVisibleSignature(new iTextSharp.text.Rectangle(20, 10, 170, 60), reader.NumberOfPages, null);
}
// digital signature
IExternalSignature es = new PrivateKeySignature(pk, "SHA-256");
MakeSignature.SignDetached(appearance, es, new Org.BouncyCastle.X509.X509Certificate[] { pk12.GetCertificate(alias).Certificate }, null, null, null, 0, CryptoStandard.CMS);
stamper.Close();
}
}
reader.Close();
reader.Dispose();
}
}
现在我需要为.p7b(pkcs#7)文件准备相同的代码,任何人都可以使用pkcs#7证书签署pdf文件。