Этап 1:
- Создайте хэш документа.
- Зашифруйте хэш, используя закрытый ключ ESP.
- Создайте запрос на подпись, который перенаправляет на страницу аутентификации ESP (здесь происходит аутентификация на основе UIDAI).
Получить байты подписи от другой конечной точки, предоставленной ESP.
У меня есть следующие проблемы:
< h3>Поддержание активности объекта PdfSignatureAppearance
Поскольку подписание происходит в два этапа, мне нужно поддерживать активный объект PdfSignatureAppearance до завершения подписания.
Проблема с вставкой сертификата
При попытке вставить сертификат из ответа ESP подпись становится недействительной при проверке в Adobe
Код: Выделить всё
Invalid signature: Document is modified."
Код для генерации хеша:
Код: Выделить всё
public String pdfSigner(File file, HttpServletRequest request, HttpSession session) {
String hashDocument = null;
PdfReader reader;
try {
String sourcefile = file.getAbsolutePath();
System.out.println("Path--->" + sourcefile);
destFile = sourcefile.replace(file.getName(), "Signed_Pdf.pdf");
request.getSession().setAttribute("fileName", "Signed_Pdf.pdf");
reader = new PdfReader(sourcefile);
Rectangle cropBox = reader.getCropBox(1);
Rectangle rectangle = null;
String user = null;
rectangle = new Rectangle(cropBox.getLeft(), cropBox.getBottom(), cropBox.getLeft(100), cropBox.getBottom(90));
fout = new FileOutputStream(destFile);
PdfStamper stamper = PdfStamper.createSignature(reader, fout, '\0', null, true);
appearance = stamper.getSignatureAppearance();
appearance.setRenderingMode(PdfSignatureAppearance.RenderingMode.DESCRIPTION);
appearance.setAcro6Layers(false);
Font font = new Font();
font.setSize(6);
font.setFamily("Helvetica");
font.setStyle("italic");
appearance.setLayer2Font(font);
Calendar currentDat = Calendar.getInstance();
System.out.println("remove 5 min");
currentDat.add(currentDat.MINUTE, 5); //Adding Delta Time of 5 Minutes....
appearance.setSignDate(currentDat);
if (user == null || user == "null" || user.equals(null) || user.equals("null")) {
appearance.setLayer2Text("Signed");
} else {
appearance.setLayer2Text("Signed by " + user);
}
appearance.setCertificationLevel(PdfSignatureAppearance.NOT_CERTIFIED);
appearance.setImage(null);
// appearance.setSignDate(currentDat);
appearance.setVisibleSignature(rectangle,
reader.getNumberOfPages(), null);
int contentEstimated = 8192;
HashMap
exc = new HashMap();
exc.put(PdfName.CONTENTS, contentEstimated * 2 + 2);
PdfSignature dic = new PdfSignature(PdfName.ADOBE_PPKLITE,
PdfName.ADBE_PKCS7_DETACHED);
dic.setReason(appearance.getReason());
dic.setLocation(appearance.getLocation());
dic.setDate(new PdfDate(appearance.getSignDate()));
appearance.setCryptoDictionary(dic);
// request.getSession().setAttribute("pdfHash",appearance);
appearance.preClose(exc);
// fout.close();
request.getSession().setAttribute("appearance", appearance);
// System.gc();
// getting bytes of file
InputStream is = appearance.getRangeStream();
hashDocument = DigestUtils.sha256Hex(is);
//session=request.getSession();
//session.setAttribute("appearance1",appearance);
System.out.println("hex: " + is.toString());
} catch (Exception e) {
System.out.println("Error in signing doc.");
}
return hashDocument;
}
Код: Выделить всё
public String signPdfwithDS(String response, HttpServletRequest request, HttpSession session) {
int contentEstimated = 8192;
try {
String errorCode = response.substring(response.indexOf("errCode"), response.indexOf("errMsg"));
errorCode = errorCode.trim();
if (errorCode.contains("NA")) {
String pkcsResponse = xmlSigning.parseXml(response.trim());
byte[] sigbytes = Base64.decodeBase64(pkcsResponse);
byte[] paddedSig = new byte[contentEstimated];
System.arraycopy(sigbytes, 0, paddedSig, 0, sigbytes.length);
PdfDictionary dic2 = new PdfDictionary();
dic2.put(PdfName.CONTENTS,
new PdfString(paddedSig).setHexWriting(true));
//fout.close();
appearance.close(dic2);
} else {
destFile = "Error";
}
} catch (Exception e) {
e.printStackTrace();
}
System.out.println("Hash after signing :" + calculateSha256Hash(destFile));
return destFile;
}
Код: Выделить всё
String certString = response.substring(response.indexOf(User_X509_START_TAG), response.indexOf(User_X509_END_TAG))
.replaceAll(User_X509_START_TAG, "").replaceAll(User_X509_END_TAG, "");
byte[] certBytes = Base64.decodeBase64(certString);
ByteArrayInputStream stream = new ByteArrayInputStream(certBytes);
CertificateFactory factory = CertificateFactory.getInstance(X_509);
Certificate cert = factory.generateCertificate(stream);
List certificates = List.of(cert);
appearance.setCrypto(null, certificates.toArray(new Certificate[0]), null, null);
PDF, созданный с использованием сертификата, здесь я не создавал заполнитель в первой функции, создал его во второй функции при встраивании подписи.
Подробнее здесь: https://stackoverflow.com/questions/792 ... istributed
Мобильная версия