【发布时间】:2020-11-03 10:33:32
【问题描述】:
我正在尝试对 pdf 文档进行数字签名,并且需要使用 MSSP(移动签名服务提供商)将签名附加到签名面板。我研究了一些stackoverflow问题,并做了以下事情。
首先我创建 pdf 的校验和。在生成校验和之前,将空签名添加到 pdf。在我生成校验和后,我将其作为数据发送到服务器以签署文档。服务器给了我base64签名,我从base64签名中找到了证书链。现在我需要在 pdf 上附加签名,显示到 Adobe 阅读器的“签名面板”部分。
我从 base64 签名中提取证书链,但我不知道如何将其附加到 pdf。
我的代码是:
此函数确实会为 pdf 创建空签名。
public static void emptySignature(String src, String dest, String fieldname) throws IOException, DocumentException, GeneralSecurityException {
PdfReader reader = new PdfReader(src);
FileOutputStream os = new FileOutputStream(dest);
PdfStamper stamper = PdfStamper.createSignature(reader, os, '\0');
PdfSignatureAppearance appearance = stamper.getSignatureAppearance();
appearance.setVisibleSignature(new Rectangle(36, 748, 144, 780), 1, fieldname);
ExternalSignatureContainer external = new ExternalBlankSignatureContainer(PdfName.ADOBE_PPKLITE, PdfName.ADBE_PKCS7_DETACHED);
MakeSignature.signExternalContainer(appearance, external, 8192);
}
这个函数确实得到了 pdf 的 SHA-256 哈希值。
public static String getHashValue(String filename) throws NoSuchAlgorithmException, IOException {
MessageDigest md = MessageDigest.getInstance("SHA-256");
String hex = checksum("output.pdf", md);
System.out.println("CHECKSUM: " + hex);
return hex;
}
private static String checksum(String filepath, MessageDigest md) throws IOException {
try (DigestInputStream dis = new DigestInputStream(new FileInputStream(filepath), md)) {
while (dis.read() != -1) ;
md = dis.getMessageDigest();
}
StringBuilder result = new StringBuilder();
for (byte b : md.digest()) {
result.append(String.format("%02x", b));
}
return result.toString();
}
然后我将 pdf 的哈希发送到服务器并获得 base 64 签名值: "MIAGCSqGSIb3DQEHAqCAMIACAQExDzANBglghkgBZQMEAgEFADCABgkqhkiG9w0BBwGggAQEVEVTVAAAAACggDCCBhwwggQEoAMCAQIC ... NKodC346j0GKueTJ595rhi2NbT679XZwMaMMqEyT41pimV76Nm85eW/2yYjHt08gCNVSJGP7laR8taVAAAAAAAAA="
我尝试了一些方法将签名附加到 pdf 的签名面板,但它需要私钥。所以请帮我提供一些建议,谢谢。
更新 1:
在我使用公共证书将签名附加到 pdf 后,我在 pdf 中收到消息“签名无效”
此代码是我附加签名的方式(我从链的第一个证书生成 pem 文件):
final String SRC = "test.pdf";
final String DEST = "signed.pdf";
final String CERT = "cert.pem";
File initialFile = new File(CERT);
InputStream is = new FileInputStream(initialFile);
// We get the self-signed certificate from the client
CertificateFactory factory = CertificateFactory.getInstance("X.509");
Certificate[] chain = new Certificate[1];
chain[0] = factory.generateCertificate(is);
System.out.println("chain[0]: -----> " + chain[0]);
// we create a reader and a stamper
PdfReader reader = new PdfReader(SRC);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
PdfStamper stamper = PdfStamper.createSignature(reader, baos, '\0');
// we create the signature appearance
PdfSignatureAppearance sap = stamper.getSignatureAppearance();
sap.setReason("test");
sap.setLocation("test");
sap.setVisibleSignature(new Rectangle(36, 748, 36, 748), 1, "signature"); //invisible
sap.setCertificate(chain[0]);
// we create the signature infrastructure
PdfSignature dic = new PdfSignature(PdfName.ADOBE_PPKLITE, PdfName.ADBE_PKCS7_DETACHED);
dic.setReason(sap.getReason());
dic.setLocation(sap.getLocation());
dic.setContact(sap.getContact());
dic.setDate(new PdfDate(sap.getSignDate()));
sap.setCryptoDictionary(dic);
HashMap<PdfName, Integer> exc = new HashMap<PdfName, Integer>();
exc.put(PdfName.CONTENTS, new Integer(8192 * 2 + 2));
sap.preClose(exc);
ExternalDigest externalDigest = new ExternalDigest() {
public MessageDigest getMessageDigest(String hashAlgorithm)
throws GeneralSecurityException {
return DigestAlgorithms.getMessageDigest(hashAlgorithm, null);
}
};
PdfPKCS7 sgn = new PdfPKCS7(null, chain, "SHA256", null, externalDigest, false);
InputStream data = sap.getRangeStream();
byte hash[] = DigestAlgorithms.digest(data, externalDigest.getMessageDigest("SHA256"));
// we get OCSP and CRL for the cert
OCSPVerifier ocspVerifier = new OCSPVerifier(null, null);
OcspClient ocspClient = new OcspClientBouncyCastle(ocspVerifier);
byte[] ocsp = null;
if (chain.length >= 2 && ocspClient != null) {
ocsp = ocspClient.getEncoded((X509Certificate) chain[0], (X509Certificate) chain[1], null);
}
byte[] sh = sgn.getAuthenticatedAttributeBytes(hash, ocsp, null, MakeSignature.CryptoStandard.CMS);
byte[] signedAttributesHash = DigestAlgorithms.digest(new ByteArrayInputStream(sh), externalDigest.getMessageDigest("SHA256"));
ByteArrayOutputStream os = baos;
byte[] signedHash = java.util.Base64.getDecoder().decode(base64Signature);
// we complete the PDF signing process
sgn.setExternalDigest(signedHash, null, "RSA");
Collection<byte[]> crlBytes = null;
TSAClientBouncyCastle tsaClient = null;
byte[] encodedSig = sgn.getEncodedPKCS7(hash, tsaClient, ocsp, crlBytes, MakeSignature.CryptoStandard.CMS);
byte[] paddedSig = new byte[8192];
System.arraycopy(encodedSig, 0, paddedSig, 0, encodedSig.length);
PdfDictionary dic2 = new PdfDictionary();
dic2.put(PdfName.CONTENTS, new PdfString(paddedSig).setHexWriting(true));
try {
sap.close(dic2);
} catch (DocumentException e) {
throw new IOException(e);
}
FileOutputStream fos = new FileOutputStream(new File(DEST));
os.writeTo(fos);
更新 2:
public byte[] sign(byte[] message) throws GeneralSecurityException {
MessageDigest messageDigest = MessageDigest.getInstance(getHashAlgorithm());
byte[] messageHash = messageDigest.digest(message);
StringBuilder sb = new StringBuilder();
for (int i = 0; i < messageHash.length; ++i) {
sb.append(Integer.toHexString((messageHash[i] & 0xFF) | 0x100).substring(1, 3));
}
byte[] signedByte = null;
String msisdn = "97688888888";
Client client = null;
try {
client = new Client( msisdn, sb.toString());
} catch (JSONException e) {
e.printStackTrace();
}
try {
String strResult = client.sendRequest();
JSONObject jsonResult = new JSONObject(strResult);
System.out.println("Response:" + jsonResult);
String base64Signature = jsonResult.getJSONObject("MSS_SignatureResp").getJSONObject("MSS_Signature").getString("Base64Signature");
System.out.println(base64Signature);
signedByte = Base64.getDecoder().decode(base64Signature);
} catch (IOException | JSONException e) {
e.printStackTrace();
}
return signedByte;
}
更新 3:
【问题讨论】:
-
你的方法有很多错误,特别是你计算了错误字节的散列(你不能散列整个准备好的文件,而只能散列准备好的文件,除了要被签名替换的占位符注入),然后您将签名注入另一个签名字段。在详细介绍之前,请澄清您的签名服务器返回什么样的签名?成熟的 CMS 签名容器?还是裸签名值?
-
@mkl 感谢您的回复,服务器返回 base 64 编码的长字符串(在本例中为 7216 个字符)。我使用 bouncycastle SignedData 从 b64 签名生成了 SignedData 对象。抱歉,我不太了解“成熟的 CMS 签名容器?还是裸签名值?”
-
我发现服务器返回给我的CMS
-
太棒了。这使得它更容易实现。我在办公室时会尝试写一些东西。
-
第一个问题:您真的需要将PDF准备和签名容器注入的过程严格分开吗?在我看来,只有在从您的服务器请求实际签名需要很长时间时才需要这样做;在这种情况下,不想长时间阻塞资源(特别是内存)。如果快速返回签名(最多几秒钟后),单步方法更合适。
标签: java pdf itext digital-signature