我正在尝试在已经签名的PDF文档中启用LTV,而不使用LTV格式。我在所有情况下都发现了与链接How to enable LTV for a timestamp signature,iText LTV enabled - how to add more CRLs? 中所述相同的示例,该链接定义了获得预期结果的过程。碰巧我没有工作,它没有给我任何错误,但是我没有添加LTV。
为什么在执行以下代码时没有给我任何错误,但是我却没有添加LTV的一些想法。
这是我尝试添加LTV的方法:
public void addLtv(String src, String dest, OcspClient ocsp, CrlClient crl, TSAClient tsa)
throws IOException, DocumentException, GeneralSecurityException {
PdfReader r = new PdfReader(src);
FileOutputStream fos = new FileOutputStream(dest);
PdfStamper stp = PdfStamper.createSignature(r, fos, '\0', null, true);
LtvVerification v = stp.getLtvVerification();
AcroFields fields = stp.getAcroFields();
List<String> names = fields.getSignatureNames();
String sigName = names.get(names.size() - 1);
PdfPKCS7 pkcs7 = fields.verifySignature(sigName);
if (pkcs7.isTsp()) {
v.addVerification(sigName, ocsp, crl,
LtvVerification.CertificateOption.SIGNING_CERTIFICATE,
LtvVerification.Level.OCSP_CRL,
LtvVerification.CertificateInclusion.NO);
}
else {
for (String name : names) {
v.addVerification(name, ocsp, crl,
LtvVerification.CertificateOption.WHOLE_CHAIN,
LtvVerification.Level.OCSP_CRL,
LtvVerification.CertificateInclusion.NO);
}
}
PdfSignatureAppearance sap = stp.getSignatureAppearance();
LtvTimestamp.timestamp(sap, tsa, null);
}
我正在使用的版本:
答案 0 :(得分:1)
此评论的结果
我要启用Adobe LTV
该任务与PAdES的相关性较弱(即使使用了PAdES中引入的机制),但重点是Adobe专有签名配置文件,即“启用LTV”签名。
很遗憾,此专有签名配置文件未正确指定。 Adobe告诉我们的只是
启用LTV意味着包含验证文件所需的所有信息(减去根证书)。
(有关详细信息和背景,请阅读this answer)
因此,实现示例签名的 LTV enable 方法涉及一些试验和错误,并且我不能保证Adobe会在Adobe Acrobat版本中接受此代码的输出为“ LTV enabled”。
此外,当前的iText 5签名API不足以完成任务,因为(事实证明)Adobe需要某些其他可选结构,而iText代码不会创建这些结构。解决此问题的最简单方法是从两个方面更新iText类LtvVerification
,因此我将在此处进行描述。或者,可以使用Java反射或复制和调整很多代码;如果无法如下所示更新iText,则必须选择一种这样的替代方法。
此部分显示了代码的添加和更改,LTV可以使用这些添加和更改来启用文档,例如OP的示例PDF sign_without_LTV.pdf
。
LtvVerification
类的方法这是原始代码,利用了iText签名API中的LtvVerification
类。不幸的是,为此必须向该类添加功能。
LtvVerification
iText 5 LtvVerification
类仅提供addVerification
个接受签名字段名称的方法。我们还需要这些方法的功能来实现不绑定到表单字段的签名,例如OCSP响应签名。为此,我添加了该方法的以下重载:
public boolean addVerification(PdfName signatureHash, Collection<byte[]> ocsps, Collection<byte[]> crls, Collection<byte[]> certs) throws IOException, GeneralSecurityException {
if (used)
throw new IllegalStateException(MessageLocalization.getComposedMessage("verification.already.output"));
ValidationData vd = new ValidationData();
if (ocsps != null) {
for (byte[] ocsp : ocsps) {
vd.ocsps.add(buildOCSPResponse(ocsp));
}
}
if (crls != null) {
for (byte[] crl : crls) {
vd.crls.add(crl);
}
}
if (certs != null) {
for (byte[] cert : certs) {
vd.certs.add(cert);
}
}
validated.put(signatureHash, vd);
return true;
}
此外,在最终VRI词典中需要(根据规范可选)输入时间。因此,我在outputDss
方法中添加了一行,如下所示:
...
if (ocsp.size() > 0)
vri.put(PdfName.OCSP, writer.addToBody(ocsp, false).getIndirectReference());
if (crl.size() > 0)
vri.put(PdfName.CRL, writer.addToBody(crl, false).getIndirectReference());
if (cert.size() > 0)
vri.put(PdfName.CERT, writer.addToBody(cert, false).getIndirectReference());
// v--- added line
vri.put(PdfName.TU, new PdfDate());
// ^--- added line
vrim.put(vkey, writer.addToBody(vri, false).getIndirectReference());
...
需要一些对安全性原语进行操作的辅助方法。这些方法大部分是从现有的iText类中收集的(由于它们是私有的,因此无法原样使用)或从那里的代码派生而来:
static X509Certificate getOcspSignerCertificate(byte[] basicResponseBytes) throws CertificateException, OCSPException, OperatorCreationException {
JcaX509CertificateConverter converter = new JcaX509CertificateConverter().setProvider(BouncyCastleProvider.PROVIDER_NAME);
BasicOCSPResponse borRaw = BasicOCSPResponse.getInstance(basicResponseBytes);
BasicOCSPResp bor = new BasicOCSPResp(borRaw);
for (final X509CertificateHolder x509CertificateHolder : bor.getCerts()) {
X509Certificate x509Certificate = converter.getCertificate(x509CertificateHolder);
JcaContentVerifierProviderBuilder jcaContentVerifierProviderBuilder = new JcaContentVerifierProviderBuilder();
jcaContentVerifierProviderBuilder.setProvider(BouncyCastleProvider.PROVIDER_NAME);
final PublicKey publicKey = x509Certificate.getPublicKey();
ContentVerifierProvider contentVerifierProvider = jcaContentVerifierProviderBuilder.build(publicKey);
if (bor.isSignatureValid(contentVerifierProvider))
return x509Certificate;
}
return null;
}
static PdfName getOcspSignatureKey(byte[] basicResponseBytes) throws NoSuchAlgorithmException, IOException {
BasicOCSPResponse basicResponse = BasicOCSPResponse.getInstance(basicResponseBytes);
byte[] signatureBytes = basicResponse.getSignature().getBytes();
DEROctetString octetString = new DEROctetString(signatureBytes);
byte[] octetBytes = octetString.getEncoded();
byte[] octetHash = hashBytesSha1(octetBytes);
PdfName octetName = new PdfName(Utilities.convertToHex(octetHash));
return octetName;
}
static PdfName getCrlSignatureKey(byte[] crlBytes) throws NoSuchAlgorithmException, IOException, CRLException, CertificateException {
CertificateFactory cf = CertificateFactory.getInstance("X.509");
X509CRL crl = (X509CRL)cf.generateCRL(new ByteArrayInputStream(crlBytes));
byte[] signatureBytes = crl.getSignature();
DEROctetString octetString = new DEROctetString(signatureBytes);
byte[] octetBytes = octetString.getEncoded();
byte[] octetHash = hashBytesSha1(octetBytes);
PdfName octetName = new PdfName(Utilities.convertToHex(octetHash));
return octetName;
}
static X509Certificate getIssuerCertificate(X509Certificate certificate) throws IOException, StreamParsingException {
String url = getCACURL(certificate);
if (url != null && url.length() > 0) {
HttpURLConnection con = (HttpURLConnection)new URL(url).openConnection();
if (con.getResponseCode() / 100 != 2) {
throw new IOException(MessageLocalization.getComposedMessage("invalid.http.response.1", con.getResponseCode()));
}
InputStream inp = (InputStream) con.getContent();
byte[] buf = new byte[1024];
ByteArrayOutputStream bout = new ByteArrayOutputStream();
while (true) {
int n = inp.read(buf, 0, buf.length);
if (n <= 0)
break;
bout.write(buf, 0, n);
}
inp.close();
X509CertParser parser = new X509CertParser();
parser.engineInit(new ByteArrayInputStream(bout.toByteArray()));
return (X509Certificate) parser.engineRead();
}
return null;
}
static String getCACURL(X509Certificate certificate) {
ASN1Primitive obj;
try {
obj = getExtensionValue(certificate, Extension.authorityInfoAccess.getId());
if (obj == null) {
return null;
}
ASN1Sequence AccessDescriptions = (ASN1Sequence) obj;
for (int i = 0; i < AccessDescriptions.size(); i++) {
ASN1Sequence AccessDescription = (ASN1Sequence) AccessDescriptions.getObjectAt(i);
if ( AccessDescription.size() != 2 ) {
continue;
}
else if (AccessDescription.getObjectAt(0) instanceof ASN1ObjectIdentifier) {
ASN1ObjectIdentifier id = (ASN1ObjectIdentifier)AccessDescription.getObjectAt(0);
if ("1.3.6.1.5.5.7.48.2".equals(id.getId())) {
ASN1Primitive description = (ASN1Primitive)AccessDescription.getObjectAt(1);
String AccessLocation = getStringFromGeneralName(description);
if (AccessLocation == null) {
return "" ;
}
else {
return AccessLocation ;
}
}
}
}
} catch (IOException e) {
return null;
}
return null;
}
static ASN1Primitive getExtensionValue(X509Certificate certificate, String oid) throws IOException {
byte[] bytes = certificate.getExtensionValue(oid);
if (bytes == null) {
return null;
}
ASN1InputStream aIn = new ASN1InputStream(new ByteArrayInputStream(bytes));
ASN1OctetString octs = (ASN1OctetString) aIn.readObject();
aIn = new ASN1InputStream(new ByteArrayInputStream(octs.getOctets()));
return aIn.readObject();
}
static String getStringFromGeneralName(ASN1Primitive names) throws IOException {
ASN1TaggedObject taggedObject = (ASN1TaggedObject) names ;
return new String(ASN1OctetString.getInstance(taggedObject, false).getOctets(), "ISO-8859-1");
}
static byte[] hashBytesSha1(byte[] b) throws NoSuchAlgorithmException {
MessageDigest sh = MessageDigest.getInstance("SHA1");
return sh.digest(b);
}
尚未对其进行优化,可以使它们性能更高,更优雅。
基于这些添加和帮助者,可以使用此方法makeLtvEnabled
添加启用LTV的签名所需的LTV信息:
public void makeLtvEnabled(PdfStamper stp, OcspClient ocspClient, CrlClient crlClient) throws IOException, GeneralSecurityException, StreamParsingException, OperatorCreationException, OCSPException {
stp.getWriter().addDeveloperExtension(new PdfDeveloperExtension(PdfName.ADBE, new PdfName("1.7"), 8));
LtvVerification v = stp.getLtvVerification();
AcroFields fields = stp.getAcroFields();
Map<PdfName, X509Certificate> moreToCheck = new HashMap<>();
ArrayList<String> names = fields.getSignatureNames();
for (String name : names)
{
PdfPKCS7 pdfPKCS7 = fields.verifySignature(name);
List<X509Certificate> certificatesToCheck = new ArrayList<>();
certificatesToCheck.add(pdfPKCS7.getSigningCertificate());
while (!certificatesToCheck.isEmpty()) {
X509Certificate certificate = certificatesToCheck.remove(0);
addLtvForChain(certificate, ocspClient, crlClient,
(ocsps, crls, certs) -> {
try {
v.addVerification(name, ocsps, crls, certs);
} catch (IOException | GeneralSecurityException e) {
e.printStackTrace();
}
},
moreToCheck::put
);
}
}
while (!moreToCheck.isEmpty()) {
PdfName key = moreToCheck.keySet().iterator().next();
X509Certificate certificate = moreToCheck.remove(key);
addLtvForChain(certificate, ocspClient, crlClient,
(ocsps, crls, certs) -> {
try {
v.addVerification(key, ocsps, crls, certs);
} catch (IOException | GeneralSecurityException e) {
e.printStackTrace();
}
},
moreToCheck::put
);
}
}
void addLtvForChain(X509Certificate certificate, OcspClient ocspClient, CrlClient crlClient, VriAdder vriAdder,
BiConsumer<PdfName, X509Certificate> moreSignersAndCertificates) throws GeneralSecurityException, IOException, StreamParsingException, OperatorCreationException, OCSPException {
List<byte[]> ocspResponses = new ArrayList<>();
List<byte[]> crls = new ArrayList<>();
List<byte[]> certs = new ArrayList<>();
while (certificate != null) {
System.out.println(certificate.getSubjectX500Principal().getName());
X509Certificate issuer = getIssuerCertificate(certificate);
certs.add(certificate.getEncoded());
byte[] ocspResponse = ocspClient.getEncoded(certificate, issuer, null);
if (ocspResponse != null) {
System.out.println(" with OCSP response");
ocspResponses.add(ocspResponse);
X509Certificate ocspSigner = getOcspSignerCertificate(ocspResponse);
if (ocspSigner != null) {
System.out.printf(" signed by %s\n", ocspSigner.getSubjectX500Principal().getName());
}
moreSignersAndCertificates.accept(getOcspSignatureKey(ocspResponse), ocspSigner);
} else {
Collection<byte[]> crl = crlClient.getEncoded(certificate, null);
if (crl != null && !crl.isEmpty()) {
System.out.printf(" with %s CRLs\n", crl.size());
crls.addAll(crl);
for (byte[] crlBytes : crl) {
moreSignersAndCertificates.accept(getCrlSignatureKey(crlBytes), null);
}
}
}
certificate = issuer;
}
vriAdder.accept(ocspResponses, crls, certs);
}
interface VriAdder {
void accept(Collection<byte[]> ocsps, Collection<byte[]> crls, Collection<byte[]> certs);
}
({MakeLtvEnabled as makeLtvEnabledV2
)
对于INPUT_PDF
处的签名PDF和结果输出流RESULT_STREAM
,可以使用上述方法:
PdfReader pdfReader = new PdfReader(INPUT_PDF);
PdfStamper pdfStamper = new PdfStamper(pdfReader, RESULT_STREAM, (char)0, true);
OcspClient ocsp = new OcspClientBouncyCastle();
CrlClient crl = new CrlClientOnline();
makeLtvEnabledV2(pdfStamper, ocsp, crl);
pdfStamper.close();
(MakeLtvEnabled测试方法testV2
)
以上方法仅在某些简化限制下有效,尤其是:
如果您不能接受这些限制,则可以相应地改进代码。
为避免打补丁iText类,此方法从上面的方法中获取所需的代码,并从iText的签名API中获取LtvVerification
类,并将所有内容合并为一个新的实用程序类。此类可以LTV启用文档,而无需打补丁的iText版本。
AdobeLtvEnabling
类此类将上面的代码和一些LtvVerification
代码组合到一个用于LTV启用文档的实用程序类中。
不幸的是,将其复制到此处会使消息大小超出堆栈溢出的30000个字符限制。不过,您可以从github检索代码:
对于INPUT_PDF
处的签名PDF和结果输出流RESULT_STREAM
,您可以使用上面的类,如下所示:
PdfReader pdfReader = new PdfReader(INPUT_PDF);
PdfStamper pdfStamper = new PdfStamper(pdfReader, RESULT_STREAM, (char)0, true);
AdobeLtvEnabling adobeLtvEnabling = new AdobeLtvEnabling(pdfStamper);
OcspClient ocsp = new OcspClientBouncyCastle();
CrlClient crl = new CrlClientOnline();
adobeLtvEnabling.enable(ocsp, crl);
pdfStamper.close();
(MakeLtvEnabled测试方法testV3
)
由于该实用工具类仅将第一种方法中的代码重新打包,因此存在相同的限制。
如开头所述,所有Adobe都告诉我们有关“启用LTV” 签名配置文件是
启用LTV意味着验证文件所需的所有信息(减去根证书)都包含在其中
但是他们没有告诉我们他们期望信息被嵌入文件中的精确程度如何。
起初,我只是收集了所有这些信息,并确保将其添加到PDF的适用的“文档安全性商店”字典中(证书, OCSP 和 CRL )。
但是,即使验证文件所需的所有信息(减去根证书)都包含在其中,但Adobe Acrobat并未将文件视为“启用LTV”。
然后我LTV使用Adobe Acrobat启用了文档并分析了差异。事实证明,还需要以下额外数据:
对于每个OCSP响应的签名,Adobe Acrobat要求存在相应的 VRI 词典。在OP的示例PDF中,此VRI词典根本不需要包含任何证书,CRL或OCSP响应,但是 VRI 词典需要存在。
相比之下,对于CRL签名而言,不是。这看起来有些武断。
根据ISO 32000-2和ETSI EN 319 142-1的规范,这些 VRI 词典的使用完全是可选的。对于PAdES BASELINE签名,甚至还有使用 VRI 字典的反对建议!
Adobe Acrobat希望 VRI 词典每个都包含一个 TU 条目,记录相应的 VRI 词典的创建时间。 (也许 TS 也可以,但我没有测试过。)
根据ISO 32000-2和ETSI EN 319 142-1规范,这些 TU 条目的使用纯粹是可选。对于PAdES签名,甚至还建议使用 TU 或 TS 条目 !
因此,由应用程序根据PDF规范默认添加的LTV信息不会导致Adobe Acrobat报告的“启用LTV”签名也就不足为奇了。
很明显,我不得不添加对Adobe Acrobat中某些证书的信任,以使它完全考虑到OP文档“已启用LTV”的上述代码的结果。我选择了根证书“ CA RAIZ NACIONAL-COSTA RICA v2”。