我在 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 文件如下: