public static void SignDetached(PdfSignatureAppearance sap, IExternalSignature externalSignature, ICollection<X509Certificate> chain, ICollection<ICrlClient> crlList, IOcspClient ocspClient,
ITSAClient tsaClient, int estimatedSize, CryptoStandard sigtype)
{
List<X509Certificate> certa = new List<X509Certificate>(chain);
ICollection<byte[]> crlBytes = null;
int i = 0;
while (crlBytes == null && i < certa.Count)
crlBytes = ProcessCrl(certa[i++], crlList);
if (estimatedSize == 0) {
estimatedSize = 8192;
if (crlBytes != null) {
foreach (byte[] element in crlBytes) {
estimatedSize += element.Length + 10;
}
}
if (ocspClient != null)
estimatedSize += 4192;
if (tsaClient != null)
estimatedSize += 4192;
}
sap.Certificate = certa[0];
PdfSignature dic = new PdfSignature(PdfName.ADOBE_PPKLITE, sigtype == CryptoStandard.CADES ? PdfName.ETSI_CADES_DETACHED : PdfName.ADBE_PKCS7_DETACHED);
dic.Reason = sap.Reason;
dic.Location = sap.Location;
dic.Contact = sap.Contact;
dic.Date = new PdfDate(sap.SignDate); // time-stamp will over-rule this
sap.CryptoDictionary = dic;
Dictionary<PdfName, int> exc = new Dictionary<PdfName, int>();
exc[PdfName.CONTENTS] = estimatedSize * 2 + 2;
sap.PreClose(exc);
String hashAlgorithm = externalSignature.GetHashAlgorithm();
PdfPKCS7 sgn = new PdfPKCS7(null, chain, hashAlgorithm, false);
IDigest messageDigest = DigestUtilities.GetDigest(hashAlgorithm);
Stream data = sap.GetRangeStream();
byte[] hash = DigestAlgorithms.Digest(data, hashAlgorithm);
DateTime cal = DateTime.Now;
byte[] ocsp = null;
if (chain.Count >= 2 && ocspClient != null) {
ocsp = ocspClient.GetEncoded(certa[0], certa[1], null);
}
byte[] sh = sgn.getAuthenticatedAttributeBytes(hash, cal, ocsp, crlBytes, sigtype);
byte[] extSignature = externalSignature.Sign(sh);
sgn.SetExternalDigest(extSignature, null, externalSignature.GetEncryptionAlgorithm());
byte[] encodedSig = sgn.GetEncodedPKCS7(hash, cal, tsaClient, ocsp, crlBytes, sigtype);
if (estimatedSize + 2 < encodedSig.Length)
throw new IOException("Not enough space");
byte[] paddedSig = new byte[estimatedSize];
System.Array.Copy(encodedSig, 0, paddedSig, 0, encodedSig.Length);
PdfDictionary dic2 = new PdfDictionary();
dic2.Put(PdfName.CONTENTS, new PdfString(paddedSig).SetHexWriting(true));
sap.Close(dic2);
}