Я подписываю pdf с использованием itextsharp, но подписанный pdf показывает личность, неизвестную на чужом ПК / ноутбуке, поскольку некоторые сертификаты в иерархии отсутствуют в их предварительном просмотре Adobe. Я мой Adobe показывает все корни и все сертификаты действительны. Кто-то сказал мне, что для подписи используется только корневой сертификат, а не весь корневой. но я не мог понять, как подписать его из всей иерархии сертификатов. Я использовал ниже код для подписи. Код находится в C #. NET Framework.
public async Task<byte[]> GetDigitalSigneddDsData1()
{
X509Certificate2 cert = null;
X509Store x509Store = new X509Store(StoreName.My, StoreLocation.CurrentUser);
x509Store.Open(OpenFlags.ReadWrite);
//manually chose the certificate in the store
X509Certificate2Collection select = X509Certificate2UI.SelectFromCollection(x509Store.Certificates,
null, null, X509SelectionFlag.SingleSelection);
if (select.Count > 0) cert = select[0]; //This will get us the selected certificate in "cert" object
if (cert.HasPrivateKey)
{
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 X509Certificate2Signature(cert, "SHA-1");
var parser = new X509CertificateParser();
var bouncyCertificate = parser.ReadCertificate(cert.RawData);
var algorithm = DigestAlgorithms.GetDigest(bouncyCertificate.SigAlgOid);
bool IsSignBasedOnSearchText, IsDSCToDisplayAboveSearchText;
int MarginXForDSCToSearchText, MarginYForDSCToSearchText;
byte[] bytearrayofdocument = System.IO.File.ReadAllBytes("D:\\file.pdf");
var userId = Guid.NewGuid();
var pdfpassword = "IamPdfPassword";
var dscPassowrd = "IamDscPassowrd";
var latestSignData = SignPdfWithCert(cert, bytearrayofdocument, userId, pdfpassword, 100, 100, 25, 25, 1, dscPassowrd, chain, algorithm, "uniqueid", MarginXForDSCToSearchText = 0, MarginYForDSCToSearchText = 0);
return latestSignData;
}
return null;
}
private static byte[] SignPdfWithCert(X509Certificate2 cert, byte[] SourcePdfBytes, Guid userId, string password, int xPlace, int yPlace, int width, int height, int pageNo, string dscPin, Org.BouncyCastle.X509.X509Certificate[] chain, string algorithm, string itemId, int MarginXForDSCToSearchText = 5, int MarginYForDSCToSearchText = 5)
{
var signature = new X509Certificate2Signature(cert, algorithm);
PdfReader pdfReader;
PdfReader.unethicalreading = true;
if (!string.IsNullOrEmpty(password))
pdfReader = new PdfReader(SourcePdfBytes, Encoding.ASCII.GetBytes(password));
else
pdfReader = new PdfReader(SourcePdfBytes);
MemoryStream signedPdf = new MemoryStream();
PdfStamper pdfStamper;
pdfStamper = PdfStamper.CreateSignature(pdfReader, signedPdf, '\0', null, true); // Append new digital signature
//pdfStamper = PdfStamper.CreateSignature(pdfReader, signedPdf, '\0'); // first digital signature in document IF you don't want to add any additional signature in document.
if (string.IsNullOrEmpty(password) == false)
{
pdfStamper.SetEncryption(Encoding.ASCII.GetBytes(password), Encoding.ASCII.GetBytes(password), PdfWriter.AllowCopy, PdfWriter.ENCRYPTION_AES_256);
}
PdfSignatureAppearance signatureAppearance = pdfStamper.SignatureAppearance;
//PdfAnnotation pdfStamp = PdfAnnotation.CreateStamp(
// pdfStamper.Writer, new iTextSharp.text.Rectangle(xPlace, yPlace, xPlace + width, yPlace + height), null, Guid.NewGuid().ToString());
//pdfStamp.Flags = PdfAnnotation.FLAGS_PRINT;
//pdfStamper.AddAnnotation(pdfStamp, pageNo);
//here set signatureAppearance at your will by using properties of different properties of pdfsigntuareapprearance.
signatureAppearance.Location = cert.IssuerName.Name;
signatureAppearance.Acro6Layers = false;
signatureAppearance.Layer4Text = PdfSignatureAppearance.questionMark; //Property neeeds to be set for watermarking behind the signature which indicates signature status as per User's computer.
signatureAppearance.CertificationLevel = PdfSignatureAppearance.NOT_CERTIFIED;
signatureAppearance.SignatureRenderingMode = PdfSignatureAppearance.RenderingMode.DESCRIPTION;
signatureAppearance.SetVisibleSignature(new iTextSharp.text.Rectangle(xPlace, yPlace, xPlace + width, yPlace + height), pageNo, string.Concat(itemId, pageNo));
RSACryptoServiceProvider rsa = (RSACryptoServiceProvider)cert.PrivateKey;
CspParameters cspp = new CspParameters();
cspp.KeyContainerName = rsa.CspKeyContainerInfo.KeyContainerName;
cspp.ProviderName = rsa.CspKeyContainerInfo.ProviderName;
// cspp.ProviderName = "Microsoft Smart Card Key Storage Provider";
cspp.ProviderType = rsa.CspKeyContainerInfo.ProviderType;
SecureString pwd = GetSecurePin(dscPin);
cspp.KeyPassword = pwd;
cspp.Flags = CspProviderFlags.NoPrompt;
try
{
// cspp.CryptoKeySecurity.AddAccessRule(new CryptoKeyAccessRule(cert.SerialNumber, CryptoKeyRights.GenericRead, AccessControlType.Allow));
RSACryptoServiceProvider rsa2 = new RSACryptoServiceProvider(cspp);
}
catch
{
// ignored- It tries to sign with given dsc pin, if it fails then " MakeSignature.SignDetached" method will call windows security dialog to enter password.
}
rsa.PersistKeyInCsp = true;
MakeSignature.SignDetached(signatureAppearance, signature, chain, null, null, null, 0, CryptoStandard.CADES);
SourcePdfBytes = signedPdf.ToArray();
pdfStamper.Close();
return SourcePdfBytes;
}
private static SecureString GetSecurePin(string PinCode)
{
SecureString pwd = new SecureString();
if (!string.IsNullOrEmpty(PinCode))
{
foreach (var c in PinCode.ToCharArray()) pwd.AppendChar(c);
}
return pwd;
}
Подписанный PDF скачать по этой ссылке: https://gofile.io/?c=sRb06y
Буду признателен за любую помощь / руководство. Заранее спасибо.