如何解决iText7 延迟签名的 pdf 文档显示“自应用签名以来文档已被更改或损坏” 你确定了错误字节的散列您处理哈希就像您的 CompanyA 只返回裸签名字节一样,但您嵌入了 CompanyA 返回的字节,就好像它们是完整的 CMS 签名容器
我在 Stackoverflow 上检查了其他类似问题,但它不适用于我的情况。
情况:我正在开发一个需要签署 pdf 文档的应用程序。签名密钥由另一家公司持有,假设它是 CompanyA。
我做了以下步骤:
- 准备好要签名的 pdf 文档。
- 创建了一个临时 pdf 文件,在原始 pdf 中添加了一个空签名。
- 阅读 Temp pdf 以获取消息摘要。 (将其编码为 base64)
- 将消息摘要(Base64 编码)发送给 CompanyA 以进行签名。
- 从 CompanyA 获取签名摘要(base64 编码)。
- 进行 base64 解码。并将结果嵌入到 Temp pdf 中以获得最终签名的 pdf。
一切顺利,我可以获得最终签名的 pdf。但是当我在 Adobe Reader 中打开它时,它说“自应用签名以来,文档已被更改或损坏”。
我使用这个 getHashBase64Str2Sign
来获取消息摘要(在 base64 中)。该方法调用emptySignature()
方法创建签名为空的Temp文件,然后调用getSignatureHash()
方法读取Temp文件获取消息摘要。
public static String getHashBase64Str2Sign() {
try {
// Add BC provider
BouncyCastleProvider providerBC = new BouncyCastleProvider();
Security.addProvider(providerBC);
// Create parent path of dest pdf file,if not exist
File file = new File(DEST).getParentFile();
if (!file.exists()) {
file.mkdirs();
}
CertificateFactory factory = CertificateFactory.getInstance("X.509");
Certificate[] chain = new Certificate[1];
try (InputStream certIs = new FileInputStream(CERT)) {
chain[0] = factory.generateCertificate(certIs);
}
// Get byte[] hash
DeferredSigning app = new DeferredSigning();
app.emptySignature(SRC,TEMP,"sig",chain);
byte[] sh = app.getSignatureHash(TEMP,"SHA256",chain);
// Encode byte[] hash to base64 String and return
return Base64.getEncoder().encodeToString(sh);
} catch (IOException | GeneralSecurityException e) {
e.printStackTrace();
return null;
}
}
private void emptySignature(String src,String dest,String fieldname,Certificate[] chain)
throws IOException,GeneralSecurityException {
PdfReader reader = new PdfReader(src);
PdfSigner signer = new PdfSigner(reader,new FileOutputStream(dest),new StampingProperties());
PdfSignatureAppearance appearance = signer.getSignatureAppearance();
appearance.setPageRect(new Rectangle(100,500,200,100));
appearance.setPageNumber(1);
appearance.setCertificate(chain[0]);
appearance.setReason("For test");
appearance.setLocation("HKSAR");
signer.setFieldName(fieldname);
/*
* ExternalBlankSignatureContainer constructor will create the PdfDictionary for
* the signature information and will insert the /Filter and /SubFilter values
* into this dictionary. It will leave just a blank placeholder for the
* signature that is to be inserted later.
*/
IExternalSignatureContainer external = new ExternalBlankSignatureContainer(PdfName.Adobe_PPKLite,PdfName.Adbe_pkcs7_detached);
// Sign the document using an external container.
// 8192 is the size of the empty signature placeholder.
signer.signExternalContainer(external,100000);
}
private byte[] getSignatureHash(String src,String hashAlgorithm,GeneralSecurityException {
InputStream is = new FileInputStream(src);
// Get the hash
BouncyCastleDigest digest = new BouncyCastleDigest();
PdfPKCS7 sgn = new PdfPKCS7(null,chain,hashAlgorithm,null,digest,false);
byte hash[] = DigestAlgorithms.digest(is,digest.getMessageDigest(sgn.getHashAlgorithm()));
return sgn.getAuthenticatedAttributeBytes(hash,PdfSigner.CryptoStandard.CMS,null);
}
private void createSignature(String src,String fieldName,byte[] sig)
throws IOException,GeneralSecurityException {
PdfReader reader = new PdfReader(src);
try (FileOutputStream os = new FileOutputStream(dest)) {
PdfSigner signer = new PdfSigner(reader,os,new StampingProperties());
IExternalSignatureContainer external = new MyExternalSignatureContainer(sig);
// Signs a PDF where space was already reserved. The field must cover the whole
// document.
PdfSigner.signDeferred(signer.getDocument(),fieldName,external);
}
}
然后,消息摘要被发送到 CompanyA 进行签名。从 CompanyA 获得签名摘要(base64 编码)后,我调用 embedSignedHashToPdf()
方法来获取签名的 pdf 文档。
public static void embedSignedHashToPdf(String signedHash) {
try {
byte[] sig = Base64.getDecoder().decode(signedHash);
// Get byte[] hash
DeferredSigning app = new DeferredSigning();
app.createSignature(TEMP,DEST,sig);
} catch (IOException | GeneralSecurityException e) {
e.printStackTrace();
}
}
class MyExternalSignatureContainer implements IExternalSignatureContainer {
protected byte[] sig;
public MyExternalSignatureContainer(byte[] sig) {
this.sig = sig;
}
@Override
public void modifySigningDictionary(PdfDictionary signDic) {
}
@Override
public byte[] sign(InputStream arg0) throws GeneralSecurityException {
return sig;
}
}
最后,我可以得到签名的pdf文档,但在Adobe Reader中显示错误,如下所示:
请检查原始 pdf、临时 pdf 和最终签名的 pdf 文件如下:
Temp pdf - helloworld_empty_signed.pdf
Final pdf - helloworld_signed_ok.pdf
解决方法
好的,我发现您的代码中有很多问题:
你确定了错误字节的散列
在 getSignatureHash
中,src
包含准备签署的中间 PDF 的路径
InputStream is = new FileInputStream(src);
...
byte hash[] = DigestAlgorithms.digest(is,...);
即您计算整个中间 PDF 的哈希值。
这是错误的!
必须为 PDF 计算散列,但签名容器的占位符除外,该占位符稍后将被嵌入:
散列该范围的最简单方法是已经在 emptySignature
中计算散列,然后使用散列计算 IExternalSignatureContainer
实现而不是愚蠢的 ExternalBlankSignatureContainer
从那里返回它。
例如使用这个实现:
public class PreSignatureContainer implements IExternalSignatureContainer {
private PdfDictionary sigDic;
private byte hash[];
public PreSignatureContainer(PdfName filter,PdfName subFilter) {
sigDic = new PdfDictionary();
sigDic.put(PdfName.Filter,filter);
sigDic.put(PdfName.SubFilter,subFilter);
}
@Override
public byte[] sign(InputStream data) throws GeneralSecurityException {
String hashAlgorithm = "SHA256";
BouncyCastleDigest digest = new BouncyCastleDigest();
try {
this.hash = DigestAlgorithms.digest(data,digest.getMessageDigest(hashAlgorithm));
} catch (IOException e) {
throw new GeneralSecurityException("PreSignatureContainer signing exception",e);
}
return new byte[0];
}
@Override
public void modifySigningDictionary(PdfDictionary signDic) {
signDic.putAll(sigDic);
}
public byte[] getHash() {
return hash;
}
}
像这样:
PreSignatureContainer external = new PreSignatureContainer(PdfName.Adobe_PPKLite,PdfName.Adbe_pkcs7_detached);
signer.signExternalContainer(external,16000);
byte[] documentHash = external.getHash();
您处理哈希就像您的 CompanyA 只返回裸签名字节一样,但您嵌入了 CompanyA 返回的字节,就好像它们是完整的 CMS 签名容器
在 getSignatureHash
中,您最终不会返回所谓的文档哈希,而是开始构建 CMS 签名容器并返回其签名属性:
PdfPKCS7 sgn = new PdfPKCS7(null,chain,hashAlgorithm,null,digest,false);
...
return sgn.getAuthenticatedAttributeBytes(hash,PdfSigner.CryptoStandard.CMS,null);
计算 PdfPKCS7.getAuthenticatedAttributeBytes(...)
仅在您检索这些属性字节的裸签名字节并使用相同的 PdfPKCS7
对象创建一个 CMS 签名容器时才有意义:
byte[] sh = sgn.getAuthenticatedAttributeBytes(hash,sigtype,ocspList,crlBytes);
byte[] extSignature = RETRIEVE_NAKED_SIGNATURE_BYTES_FOR(sh);
sgn.setExternalDigest(extSignature,ENCRYPTION_ALGORITHM_USED_FOR_SIGNING);
byte[] encodedSig = sgn.getEncodedPKCS7(hash,tsaClient,crlBytes);
特别是您计算签名属性然后忘记 PdfPKCS7
对象的方法根本没有任何意义。
但实际上看起来您的 CompanyA 可以返回完整的 CMS 签名容器,而不仅仅是裸签名字节,因为您立即将返回的字节嵌入 embedSignedHashToPdf
和 createSignature
中,并且您的示例 PDF 确实包含完整的 CMS签名容器。
在这种情况下,您根本不需要使用 PdfPKCS7
,而是直接将预先计算的文档摘要发送给 CompanyA 进行签名。
因此,您很可能根本不需要 PdfPKCS7
,而是将如上所述确定的文档哈希发送给 CompanyA 并嵌入他们返回的签名容器。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。