use of com.itextpdf.text.pdf.security.ExternalDigest in project commons by mosip.
the class PDFGeneratorImpl method signAndEncryptPDF.
@Override
public OutputStream signAndEncryptPDF(byte[] pdf, io.mosip.kernel.core.pdfgenerator.model.Rectangle rectangle, String reason, int pageNumber, Provider provider, CertificateEntry<X509Certificate, PrivateKey> certificateEntry, String password) throws IOException, GeneralSecurityException {
OutputStream outputStream = new ByteArrayOutputStream();
PdfReader pdfReader = null;
PdfStamper pdfStamper = null;
try {
pdfReader = new PdfReader(pdf);
pdfStamper = PdfStamper.createSignature(pdfReader, outputStream, '\0');
LOGGER.debug("certificate entry {}", certificateEntry);
LOGGER.info("provider {}", provider);
if (password != null && !password.trim().isEmpty()) {
pdfStamper.setEncryption(password.getBytes(), pdfOwnerPassword.getBytes(), com.itextpdf.text.pdf.PdfWriter.ALLOW_PRINTING, com.itextpdf.text.pdf.PdfWriter.ENCRYPTION_AES_256);
}
PdfSignatureAppearance signAppearance = pdfStamper.getSignatureAppearance();
signAppearance.setReason(reason);
// comment next line to have an invisible signature
signAppearance.setVisibleSignature(new Rectangle(rectangle.getLlx(), rectangle.getLly(), rectangle.getUrx(), rectangle.getUry()), pageNumber, null);
OcspClient ocspClient = new OcspClientBouncyCastle(null);
TSAClient tsaClient = null;
for (X509Certificate certificate : certificateEntry.getChain()) {
String tsaUrl = CertificateUtil.getTSAURL(certificate);
if (tsaUrl != null) {
tsaClient = new TSAClientBouncyCastle(tsaUrl);
break;
}
signAppearance.setCertificate(certificate);
}
List<CrlClient> crlList = new ArrayList<>();
crlList.add(new CrlClientOnline(certificateEntry.getChain()));
ExternalSignature pks = new PrivateKeySignature(certificateEntry.getPrivateKey(), SHA256, provider.getName());
ExternalDigest digest = new BouncyCastleDigest();
// Sign the document using the detached mode, CMS or CAdES equivalent.
MakeSignature.signDetached(signAppearance, digest, pks, certificateEntry.getChain(), crlList, ocspClient, tsaClient, 0, CryptoStandard.CMS);
} catch (DocumentException e) {
LOGGER.error("Document Exception occur {}", e.getCause());
throw new PDFGeneratorException(PDFGeneratorExceptionCodeConstant.PDF_EXCEPTION.getErrorCode(), e.getMessage(), e);
} finally {
outputStream.close();
if (pdfStamper != null) {
closeQuietly(pdfStamper);
}
if (pdfReader != null) {
pdfReader.close();
}
}
return outputStream;
}
Aggregations