List of usage examples for com.lowagie.text.pdf PdfSignatureAppearance WINCER_SIGNED
PdfName WINCER_SIGNED
To view the source code for com.lowagie.text.pdf PdfSignatureAppearance WINCER_SIGNED.
Click Source Link
From source file:androidGLUESigner.pdf.PDFSignerEngine.java
License:Open Source License
/** * Prepare the signing of the pdf (siganture appearance, placeholders, sigimage, ..) * @param inputStream the stream to the input pdf file * @param outputStream the stream to the output pdf file * @return hash value with ocsp included * @throws IOException// w w w. j a v a2s. c o m * @throws DocumentException * @throws GeneralSecurityException */ public byte[] prepareSign(InputStream inputStream, OutputStream outputStream) throws IOException, DocumentException, GeneralSecurityException { PdfReader reader = new PdfReader(inputStream); PdfStamper stp = PdfStamper.createSignature(reader, outputStream, '\0', null, true); PdfSignatureAppearance sap = stp.getSignatureAppearance(); sap.setCrypto(null, getCertificateChain(), null, PdfSignatureAppearance.WINCER_SIGNED); PdfSignature dic = new PdfSignature(PdfName.ADOBE_PPKLITE, PdfName.ADBE_PKCS7_DETACHED); dic.setReason(siginfo.getSignatureReason()); dic.setLocation(siginfo.getSignatureLocation()); dic.setName(siginfo.getSignatureName()); dic.setDate(new PdfDate(sap.getSignDate())); sap.setCryptoDictionary(dic); // get the selected rectangle and pagenumber for visible signature Rectangle signatureRect = new Rectangle(siginfo.getSignatureRect().left, siginfo.getSignatureRect().bottom, siginfo.getSignatureRect().right, siginfo.getSignatureRect().top); int pageNumber = siginfo.getPageNumber(); sap.setVisibleSignature(signatureRect, pageNumber, null); // set signature picture, if there is one if (siginfo.getSignatureType() == SignatureType.PICTURE) { Image obj_pic = Image.getInstance(siginfo.getImagePath()); sap.setImage(obj_pic); } // preserve some space for the contents HashMap<PdfName, Integer> exc = new HashMap<PdfName, Integer>(); exc.put(PdfName.CONTENTS, new Integer(SIGNATURE_MAX_SIZE * 2 + 2)); sap.preClose(exc); // Save placeholder which will be replaced with actual signature later byte[] placeHolder = getPlaceHolderArr(SIGNATURE_MAX_SIZE * 2); // Replace the contents PdfDictionary dic2 = new PdfDictionary(); dic2.put(PdfName.CONTENTS, new PdfString(placeHolder).setHexWriting(true)); sap.close(dic2); // Calculate the digest InputStream data = sap.getRangeStream(); MessageDigest messageDigest = MessageDigest.getInstance("SHA-256"); byte buf[] = new byte[8192]; int n; while ((n = data.read(buf)) > 0) { messageDigest.update(buf, 0, n); } hash = messageDigest.digest(); calendar = Calendar.getInstance(); ocsp = ocspRequest(cert, issuerCert); System.out.println("Got OCSP response, length = " + ocsp.length); // Calculate another digest over authenticatedAttributes PdfPKCS7 sgn = new PdfPKCS7(null, getCertificateChain(), null, hashAlgo, null, true); byte[] sh = sgn.getAuthenticatedAttributeBytes(hash, calendar, ocsp); return sh; }
From source file:com.orange.atk.atkUI.corecli.utils.PdfUtilities.java
License:Apache License
private void signDocument(String pdfFileName) { try {/*from ww w .j a va2s . c o m*/ // 1. copy File tmpPDFFile = new File(tmpDir, "tmp2PDF.pdf"); copyFile(new File(pdfFileName), tmpPDFFile); // 2. sign KeyStore ks = KeyStore.getInstance(typeKeystore); FileInputStream fis = new FileInputStream(keystore); ks.load(fis, passwordKeystore.toCharArray()); PrivateKey key = (PrivateKey) ks.getKey(aliasCertificate, passwordKeystore.toCharArray()); Certificate[] chain = ks.getCertificateChain(aliasCertificate); PdfReader reader = new PdfReader(tmpPDFFile.getAbsolutePath()); FileOutputStream fout = new FileOutputStream(pdfFileName); PdfStamper stp = PdfStamper.createSignature(reader, fout, '\0'); PdfSignatureAppearance sap = stp.getSignatureAppearance(); sap.setCrypto(key, chain, null, PdfSignatureAppearance.WINCER_SIGNED); sap.setVisibleSignature(new Rectangle(450, 730, 550, 780), 1, null); stp.close(); fis.close(); } catch (Exception e) { e.printStackTrace(Out.log); } }
From source file:ec.gov.informatica.firmadigital.FirmaDigital.java
License:Open Source License
/** * Firma un archivo./*from w w w . j av a 2 s. com*/ * * @param data * @return */ // public void firmar(String claveToken, // String tipoCertificado, String urlCertificado, String path) { public void firmar(String claveToken, String tipoCertificado, String path) { try { KeyStore keyStore = null; Enumeration<String> enumeration = null; String alias = null; PrivateKey privateKey = null; Certificate[] certs = null; CMSSignatureProcessor cms = null; KeyStoreProvider keyStoreProvider = null; try { if (tipoCertificado.equals("1") || tipoCertificado.equals("2") || tipoCertificado.equals("3")) { System.out.println("- Firmando con certificado token." + tipoCertificado); keyStoreProvider = this.getKeyStoreProvider(tipoCertificado); System.out.println(claveToken.toCharArray()); keyStore = keyStoreProvider.getKeystore(claveToken.toCharArray()); enumeration = keyStore.aliases(); alias = enumeration.nextElement(); privateKey = (PrivateKey) keyStore.getKey(alias, null); cms = new BouncyCastleSignatureProcessor(keyStore); } // if (tipoCertificado.equals("4")) { // System.out.println("- Firmando con certificado en archivo."); // keyStore = java.security.KeyStore.getInstance("PKCS12"); // // instancia el ks // keyStore.load(new java.io.FileInputStream(urlCertificado), // claveToken.toCharArray()); // Enumeration en = keyStore.aliases(); // alias = ""; // Vector vectaliases = new Vector(); // while (en.hasMoreElements()) { // vectaliases.add(en.nextElement()); // } // String[] aliases = (String[]) (vectaliases.toArray(new // String[0])); // for (int i = 0; i < aliases.length; i++) { // if (keyStore.isKeyEntry(aliases[i])) { // alias = aliases[i]; // break; // } // } // privateKey = (PrivateKey) keyStore.getKey(alias, // claveToken.toCharArray()); // cms = new BouncyCastleSignatureProcessor(keyStore); // } } catch (Exception e) { System.out.println(" \n Fallo trayendo keystore " + e.getMessage()); } certs = keyStore.getCertificateChain(alias); Certificate[] chain = keyStore.getCertificateChain(alias); PrivateKey key = (PrivateKey) keyStore.getKey(alias, claveToken.toCharArray()); String revocados = ""; // para verificar revocados revocados = verificaRevocados(((X509Certificate) certs[0]).getSerialNumber().toString(), tipoCertificado); if (!revocados.isEmpty()) { System.out.println(" CERTIFICADO REVOCADO " + revocados); return; } System.out.println("- Certificado valido "); PdfReader reader = new PdfReader(path); FileOutputStream fout = new FileOutputStream(path + ".Firmado.pdf"); PdfStamper stp = PdfStamper.createSignature(reader, fout, '?'); PdfSignatureAppearance sap = stp.getSignatureAppearance(); sap.setCrypto(key, chain, null, PdfSignatureAppearance.WINCER_SIGNED); sap.setReason("Firma Procesos Legales"); sap.setLocation("RedTools"); // Aade la firma visible. Podemos comentarla para que no sea // visible. sap.setVisibleSignature(new Rectangle(100, 100, 200, 200), 1, null); stp.close(); // byte[] datosFirmados = cms.sign(data, privateKey, certs); System.out.println("Firmado Correctamente..!"); // this.datosUsuarioActual = this // .crearDatosUsuario((X509Certificate) certs[0]); // llena la // clase de // tipo // datosUsuario // con el // certificado // actual // return datosFirmados; } catch (GeneralSecurityException e) { throw new RuntimeException(e); // FIXME } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); throw new RuntimeException(e); } catch (DocumentException e) { // TODO Auto-generated catch block e.printStackTrace(); throw new RuntimeException(e); } }
From source file:net.sf.jsignpdf.SignerLogic.java
License:Mozilla Public License
/** * Signs a single file.//from w w w . ja v a 2 s.co m * * @return true when signing is finished succesfully, false otherwise */ public boolean signFile() { final String outFile = options.getOutFileX(); if (!validateInOutFiles(options.getInFile(), outFile)) { LOGGER.info(RES.get("console.skippingSigning")); return false; } boolean finished = false; Throwable tmpException = null; FileOutputStream fout = null; try { SSLInitializer.init(options); final PrivateKeyInfo pkInfo = KeyStoreUtils.getPkInfo(options); final PrivateKey key = pkInfo.getKey(); final Certificate[] chain = pkInfo.getChain(); if (ArrayUtils.isEmpty(chain)) { // the certificate was not found LOGGER.info(RES.get("console.certificateChainEmpty")); return false; } LOGGER.info(RES.get("console.createPdfReader", options.getInFile())); PdfReader reader; try { reader = new PdfReader(options.getInFile(), options.getPdfOwnerPwdStrX().getBytes()); } catch (Exception e) { try { reader = new PdfReader(options.getInFile(), new byte[0]); } catch (Exception e2) { // try to read without password reader = new PdfReader(options.getInFile()); } } LOGGER.info(RES.get("console.createOutPdf", outFile)); fout = new FileOutputStream(outFile); final HashAlgorithm hashAlgorithm = options.getHashAlgorithmX(); LOGGER.info(RES.get("console.createSignature")); char tmpPdfVersion = '\0'; // default version - the same as input if (reader.getPdfVersion() < hashAlgorithm.getPdfVersion()) { // this covers also problems with visible signatures (embedded // fonts) in PDF 1.2, because the minimal version // for hash algorithms is 1.3 (for SHA1) if (options.isAppendX()) { // if we are in append mode and version should be updated // then return false (not possible) LOGGER.info(RES.get("console.updateVersionNotPossibleInAppendMode")); return false; } tmpPdfVersion = hashAlgorithm.getPdfVersion(); LOGGER.info(RES.get("console.updateVersion", new String[] { String.valueOf(reader.getPdfVersion()), String.valueOf(tmpPdfVersion) })); } final PdfStamper stp = PdfStamper.createSignature(reader, fout, tmpPdfVersion, null, options.isAppendX()); if (!options.isAppendX()) { // we are not in append mode, let's remove existing signatures // (otherwise we're getting to troubles) final AcroFields acroFields = stp.getAcroFields(); @SuppressWarnings("unchecked") final List<String> sigNames = acroFields.getSignatureNames(); for (String sigName : sigNames) { acroFields.removeField(sigName); } } if (options.isAdvanced() && options.getPdfEncryption() != PDFEncryption.NONE) { LOGGER.info(RES.get("console.setEncryption")); final int tmpRight = options.getRightPrinting().getRight() | (options.isRightCopy() ? PdfWriter.ALLOW_COPY : 0) | (options.isRightAssembly() ? PdfWriter.ALLOW_ASSEMBLY : 0) | (options.isRightFillIn() ? PdfWriter.ALLOW_FILL_IN : 0) | (options.isRightScreanReaders() ? PdfWriter.ALLOW_SCREENREADERS : 0) | (options.isRightModifyAnnotations() ? PdfWriter.ALLOW_MODIFY_ANNOTATIONS : 0) | (options.isRightModifyContents() ? PdfWriter.ALLOW_MODIFY_CONTENTS : 0); switch (options.getPdfEncryption()) { case PASSWORD: stp.setEncryption(true, options.getPdfUserPwdStr(), options.getPdfOwnerPwdStrX(), tmpRight); break; case CERTIFICATE: final X509Certificate encCert = KeyStoreUtils .loadCertificate(options.getPdfEncryptionCertFile()); if (encCert == null) { LOGGER.error(RES.get("console.pdfEncError.wrongCertificateFile", StringUtils.defaultString(options.getPdfEncryptionCertFile()))); return false; } if (!KeyStoreUtils.isEncryptionSupported(encCert)) { LOGGER.error(RES.get("console.pdfEncError.cantUseCertificate", encCert.getSubjectDN().getName())); return false; } stp.setEncryption(new Certificate[] { encCert }, new int[] { tmpRight }, PdfWriter.ENCRYPTION_AES_128); break; default: LOGGER.error(RES.get("console.unsupportedEncryptionType")); return false; } } final PdfSignatureAppearance sap = stp.getSignatureAppearance(); sap.setCrypto(key, chain, null, PdfSignatureAppearance.WINCER_SIGNED); final String reason = options.getReason(); if (StringUtils.isNotEmpty(reason)) { LOGGER.info(RES.get("console.setReason", reason)); sap.setReason(reason); } final String location = options.getLocation(); if (StringUtils.isNotEmpty(location)) { LOGGER.info(RES.get("console.setLocation", location)); sap.setLocation(location); } final String contact = options.getContact(); if (StringUtils.isNotEmpty(contact)) { LOGGER.info(RES.get("console.setContact", contact)); sap.setContact(contact); } LOGGER.info(RES.get("console.setCertificationLevel")); sap.setCertificationLevel(options.getCertLevelX().getLevel()); if (options.isVisible()) { // visible signature is enabled LOGGER.info(RES.get("console.configureVisible")); LOGGER.info(RES.get("console.setAcro6Layers", Boolean.toString(options.isAcro6Layers()))); sap.setAcro6Layers(options.isAcro6Layers()); final String tmpImgPath = options.getImgPath(); if (tmpImgPath != null) { LOGGER.info(RES.get("console.createImage", tmpImgPath)); final Image img = Image.getInstance(tmpImgPath); LOGGER.info(RES.get("console.setSignatureGraphic")); sap.setSignatureGraphic(img); } final String tmpBgImgPath = options.getBgImgPath(); if (tmpBgImgPath != null) { LOGGER.info(RES.get("console.createImage", tmpBgImgPath)); final Image img = Image.getInstance(tmpBgImgPath); LOGGER.info(RES.get("console.setImage")); sap.setImage(img); } LOGGER.info(RES.get("console.setImageScale")); sap.setImageScale(options.getBgImgScale()); LOGGER.info(RES.get("console.setL2Text")); final String signer = PdfPKCS7.getSubjectFields((X509Certificate) chain[0]).getField("CN"); final String timestamp = new SimpleDateFormat("yyyy.MM.dd HH:mm:ss z") .format(sap.getSignDate().getTime()); if (options.getL2Text() != null) { final Map<String, String> replacements = new HashMap<String, String>(); replacements.put(L2TEXT_PLACEHOLDER_SIGNER, StringUtils.defaultString(signer)); replacements.put(L2TEXT_PLACEHOLDER_TIMESTAMP, timestamp); replacements.put(L2TEXT_PLACEHOLDER_LOCATION, StringUtils.defaultString(location)); replacements.put(L2TEXT_PLACEHOLDER_REASON, StringUtils.defaultString(reason)); replacements.put(L2TEXT_PLACEHOLDER_CONTACT, StringUtils.defaultString(contact)); final String l2text = StrSubstitutor.replace(options.getL2Text(), replacements); sap.setLayer2Text(l2text); } else { final StringBuilder buf = new StringBuilder(); buf.append(RES.get("default.l2text.signedBy")).append(" ").append(signer).append('\n'); buf.append(RES.get("default.l2text.date")).append(" ").append(timestamp); if (StringUtils.isNotEmpty(reason)) buf.append('\n').append(RES.get("default.l2text.reason")).append(" ").append(reason); if (StringUtils.isNotEmpty(location)) buf.append('\n').append(RES.get("default.l2text.location")).append(" ").append(location); sap.setLayer2Text(buf.toString()); } if (FontUtils.getL2BaseFont() != null) { sap.setLayer2Font(new Font(FontUtils.getL2BaseFont(), options.getL2TextFontSize())); } LOGGER.info(RES.get("console.setL4Text")); sap.setLayer4Text(options.getL4Text()); LOGGER.info(RES.get("console.setRender")); RenderMode renderMode = options.getRenderMode(); if (renderMode == RenderMode.GRAPHIC_AND_DESCRIPTION && sap.getSignatureGraphic() == null) { LOGGER.warn( "Render mode of visible signature is set to GRAPHIC_AND_DESCRIPTION, but no image is loaded. Fallback to DESCRIPTION_ONLY."); LOGGER.info(RES.get("console.renderModeFallback")); renderMode = RenderMode.DESCRIPTION_ONLY; } sap.setRender(renderMode.getRender()); LOGGER.info(RES.get("console.setVisibleSignature")); int page = options.getPage(); if (page < 1 || page > reader.getNumberOfPages()) { page = reader.getNumberOfPages(); } sap.setVisibleSignature(new Rectangle(options.getPositionLLX(), options.getPositionLLY(), options.getPositionURX(), options.getPositionURY()), page, null); } LOGGER.info(RES.get("console.processing")); final PdfSignature dic = new PdfSignature(PdfName.ADOBE_PPKLITE, new PdfName("adbe.pkcs7.detached")); if (!StringUtils.isEmpty(reason)) { dic.setReason(sap.getReason()); } if (!StringUtils.isEmpty(location)) { dic.setLocation(sap.getLocation()); } if (!StringUtils.isEmpty(contact)) { dic.setContact(sap.getContact()); } dic.setDate(new PdfDate(sap.getSignDate())); sap.setCryptoDictionary(dic); final Proxy tmpProxy = options.createProxy(); final CRLInfo crlInfo = new CRLInfo(options, chain); // CRLs are stored twice in PDF c.f. // PdfPKCS7.getAuthenticatedAttributeBytes final int contentEstimated = (int) (Constants.DEFVAL_SIG_SIZE + 2L * crlInfo.getByteCount()); final Map<PdfName, Integer> exc = new HashMap<PdfName, Integer>(); exc.put(PdfName.CONTENTS, new Integer(contentEstimated * 2 + 2)); sap.preClose(exc); PdfPKCS7 sgn = new PdfPKCS7(key, chain, crlInfo.getCrls(), hashAlgorithm.getAlgorithmName(), null, false); InputStream data = sap.getRangeStream(); final MessageDigest messageDigest = MessageDigest.getInstance(hashAlgorithm.getAlgorithmName()); byte buf[] = new byte[8192]; int n; while ((n = data.read(buf)) > 0) { messageDigest.update(buf, 0, n); } byte hash[] = messageDigest.digest(); Calendar cal = Calendar.getInstance(); byte[] ocsp = null; if (options.isOcspEnabledX() && chain.length >= 2) { LOGGER.info(RES.get("console.getOCSPURL")); String url = PdfPKCS7.getOCSPURL((X509Certificate) chain[0]); if (StringUtils.isEmpty(url)) { // get from options LOGGER.info(RES.get("console.noOCSPURL")); url = options.getOcspServerUrl(); } if (!StringUtils.isEmpty(url)) { LOGGER.info(RES.get("console.readingOCSP", url)); final OcspClientBouncyCastle ocspClient = new OcspClientBouncyCastle((X509Certificate) chain[0], (X509Certificate) chain[1], url); ocspClient.setProxy(tmpProxy); ocsp = ocspClient.getEncoded(); } } byte sh[] = sgn.getAuthenticatedAttributeBytes(hash, cal, ocsp); sgn.update(sh, 0, sh.length); TSAClientBouncyCastle tsc = null; if (options.isTimestampX() && !StringUtils.isEmpty(options.getTsaUrl())) { LOGGER.info(RES.get("console.creatingTsaClient")); if (options.getTsaServerAuthn() == ServerAuthentication.PASSWORD) { tsc = new TSAClientBouncyCastle(options.getTsaUrl(), StringUtils.defaultString(options.getTsaUser()), StringUtils.defaultString(options.getTsaPasswd())); } else { tsc = new TSAClientBouncyCastle(options.getTsaUrl()); } final String tsaHashAlg = options.getTsaHashAlgWithFallback(); LOGGER.info(RES.get("console.settingTsaHashAlg", tsaHashAlg)); tsc.setHashAlgorithm(tsaHashAlg); tsc.setProxy(tmpProxy); final String policyOid = options.getTsaPolicy(); if (StringUtils.isNotEmpty(policyOid)) { LOGGER.info(RES.get("console.settingTsaPolicy", policyOid)); tsc.setPolicy(policyOid); } } byte[] encodedSig = sgn.getEncodedPKCS7(hash, cal, tsc, ocsp); if (contentEstimated + 2 < encodedSig.length) { System.err.println( "SigSize - contentEstimated=" + contentEstimated + ", sigLen=" + encodedSig.length); throw new Exception("Not enough space"); } byte[] paddedSig = new byte[contentEstimated]; System.arraycopy(encodedSig, 0, paddedSig, 0, encodedSig.length); PdfDictionary dic2 = new PdfDictionary(); dic2.put(PdfName.CONTENTS, new PdfString(paddedSig).setHexWriting(true)); LOGGER.info(RES.get("console.closeStream")); sap.close(dic2); fout.close(); fout = null; finished = true; } catch (Exception e) { LOGGER.error(RES.get("console.exception"), e); } catch (OutOfMemoryError e) { LOGGER.fatal(RES.get("console.memoryError"), e); } finally { if (fout != null) { try { fout.close(); } catch (Exception e) { e.printStackTrace(); } } LOGGER.info(RES.get("console.finished." + (finished ? "ok" : "error"))); options.fireSignerFinishedEvent(tmpException); } return finished; }
From source file:org.allcolor.yahp.cl.converter.CDocumentReconstructor.java
License:Open Source License
/** * construct a pdf document from pdf parts. * //w ww.j a v a 2 s. c o m * @param files * list containing the pdf to assemble * @param properties * converter properties * @param fout * outputstream to write the new pdf * @param base_url * base url of the document * @param producer * producer of the pdf * * @throws CConvertException * if an error occured while reconstruct. */ public static void reconstruct(final List files, final Map properties, final OutputStream fout, final String base_url, final String producer, final PageSize[] size, final List hf) throws CConvertException { OutputStream out = fout; OutputStream out2 = fout; boolean signed = false; OutputStream oldOut = null; File tmp = null; File tmp2 = null; try { tmp = File.createTempFile("yahp", "pdf"); tmp2 = File.createTempFile("yahp", "pdf"); oldOut = out; if ("true".equals(properties.get(IHtmlToPdfTransformer.USE_PDF_SIGNING))) { signed = true; out2 = new FileOutputStream(tmp2); } // end if else { out2 = oldOut; } out = new FileOutputStream(tmp); com.lowagie.text.Document document = null; PdfCopy writer = null; boolean first = true; Map mapSizeDoc = new HashMap(); int totalPage = 0; for (int i = 0; i < files.size(); i++) { final File fPDF = (File) files.get(i); final PdfReader reader = new PdfReader(fPDF.getAbsolutePath()); reader.consolidateNamedDestinations(); final int n = reader.getNumberOfPages(); if (first) { first = false; // step 1: creation of a document-object // set title/creator/author document = new com.lowagie.text.Document(reader.getPageSizeWithRotation(1)); // step 2: we create a writer that listens to the document writer = new PdfCopy(document, out); // use pdf version 1.5 writer.setPdfVersion(PdfWriter.VERSION_1_3); // compress the pdf writer.setFullCompression(); // check if encryption is needed if ("true".equals(properties.get(IHtmlToPdfTransformer.USE_PDF_ENCRYPTION))) { final String password = (String) properties .get(IHtmlToPdfTransformer.PDF_ENCRYPTION_PASSWORD); final int securityType = CDocumentReconstructor.getSecurityFlags(properties); writer.setEncryption(PdfWriter.STANDARD_ENCRYPTION_128, password, null, securityType); } // end if final String title = (String) properties.get(IHtmlToPdfTransformer.PDF_TITLE); if (title != null) { document.addTitle(title); } // end if else if (base_url != null) { document.addTitle(base_url); } // end else if final String creator = (String) properties.get(IHtmlToPdfTransformer.PDF_CREATOR); if (creator != null) { document.addCreator(creator); } // end if else { document.addCreator(IHtmlToPdfTransformer.VERSION); } // end else final String author = (String) properties.get(IHtmlToPdfTransformer.PDF_AUTHOR); if (author != null) { document.addAuthor(author); } // end if final String sproducer = (String) properties.get(IHtmlToPdfTransformer.PDF_PRODUCER); if (sproducer != null) { document.add(new Meta("Producer", sproducer)); } // end if else { document.add(new Meta("Producer", (IHtmlToPdfTransformer.VERSION + " - http://www.allcolor.org/YaHPConverter/ - " + producer))); } // end else // step 3: we open the document document.open(); } // end if PdfImportedPage page; for (int j = 0; j < n;) { ++j; totalPage++; mapSizeDoc.put("" + totalPage, "" + i); page = writer.getImportedPage(reader, j); writer.addPage(page); } // end for } // end for document.close(); out.flush(); out.close(); { final PdfReader reader = new PdfReader(tmp.getAbsolutePath()); ; final int n = reader.getNumberOfPages(); final PdfStamper stp = new PdfStamper(reader, out2); int i = 0; BaseFont.createFont(BaseFont.HELVETICA, BaseFont.WINANSI, BaseFont.EMBEDDED); final CHtmlToPdfFlyingSaucerTransformer trans = new CHtmlToPdfFlyingSaucerTransformer(); while (i < n) { i++; int indexSize = Integer.parseInt((String) mapSizeDoc.get("" + i)); final int[] dsize = size[indexSize].getSize(); final int[] dmargin = size[indexSize].getMargin(); for (final Iterator it = hf.iterator(); it.hasNext();) { final CHeaderFooter chf = (CHeaderFooter) it.next(); if (chf.getSfor().equals(CHeaderFooter.ODD_PAGES) && (i % 2 == 0)) { continue; } else if (chf.getSfor().equals(CHeaderFooter.EVEN_PAGES) && (i % 2 != 0)) { continue; } final String text = chf.getContent().replaceAll("<pagenumber>", "" + i) .replaceAll("<pagecount>", "" + n); // text over the existing page final PdfContentByte over = stp.getOverContent(i); final ByteArrayOutputStream bbout = new ByteArrayOutputStream(); if (chf.getType().equals(CHeaderFooter.HEADER)) { trans.transform(new ByteArrayInputStream(text.getBytes("utf-8")), base_url, new PageSize(dsize[0] - (dmargin[0] + dmargin[1]), dmargin[3]), new ArrayList(), properties, bbout); } else if (chf.getType().equals(CHeaderFooter.FOOTER)) { trans.transform(new ByteArrayInputStream(text.getBytes("utf-8")), base_url, new PageSize(dsize[0] - (dmargin[0] + dmargin[1]), dmargin[2]), new ArrayList(), properties, bbout); } final PdfReader readerHF = new PdfReader(bbout.toByteArray()); if (chf.getType().equals(CHeaderFooter.HEADER)) { over.addTemplate(stp.getImportedPage(readerHF, 1), dmargin[0], dsize[1] - dmargin[3]); } else if (chf.getType().equals(CHeaderFooter.FOOTER)) { over.addTemplate(stp.getImportedPage(readerHF, 1), dmargin[0], 0); } readerHF.close(); } } stp.close(); } try { out2.flush(); } catch (Exception ignore) { } finally { try { out2.close(); } catch (Exception ignore) { } } if (signed) { final String keypassword = (String) properties .get(IHtmlToPdfTransformer.PDF_SIGNING_PRIVATE_KEY_PASSWORD); final String password = (String) properties.get(IHtmlToPdfTransformer.PDF_ENCRYPTION_PASSWORD); final String keyStorepassword = (String) properties .get(IHtmlToPdfTransformer.PDF_SIGNING_KEYSTORE_PASSWORD); final String privateKeyFile = (String) properties .get(IHtmlToPdfTransformer.PDF_SIGNING_PRIVATE_KEY_FILE); final String reason = (String) properties.get(IHtmlToPdfTransformer.PDF_SIGNING_REASON); final String location = (String) properties.get(IHtmlToPdfTransformer.PDF_SIGNING_LOCATION); final boolean selfSigned = !"false" .equals(properties.get(IHtmlToPdfTransformer.USE_PDF_SELF_SIGNING)); PdfReader reader = null; if (password != null) { reader = new PdfReader(tmp2.getAbsolutePath(), password.getBytes()); } // end if else { reader = new PdfReader(tmp2.getAbsolutePath()); } // end else final KeyStore ks = selfSigned ? KeyStore.getInstance(KeyStore.getDefaultType()) : KeyStore.getInstance("pkcs12"); ks.load(new FileInputStream(privateKeyFile), keyStorepassword.toCharArray()); final String alias = (String) ks.aliases().nextElement(); final PrivateKey key = (PrivateKey) ks.getKey(alias, keypassword.toCharArray()); final Certificate chain[] = ks.getCertificateChain(alias); final PdfStamper stp = PdfStamper.createSignature(reader, oldOut, '\0'); if ("true".equals(properties.get(IHtmlToPdfTransformer.USE_PDF_ENCRYPTION))) { stp.setEncryption(PdfWriter.STANDARD_ENCRYPTION_128, password, null, CDocumentReconstructor.getSecurityFlags(properties)); } // end if final PdfSignatureAppearance sap = stp.getSignatureAppearance(); if (selfSigned) { sap.setCrypto(key, chain, null, PdfSignatureAppearance.SELF_SIGNED); } // end if else { sap.setCrypto(key, chain, null, PdfSignatureAppearance.WINCER_SIGNED); } // end else if (reason != null) { sap.setReason(reason); } // end if if (location != null) { sap.setLocation(location); } // end if stp.close(); oldOut.flush(); } // end if } // end try catch (final Exception e) { throw new CConvertException( "ERROR: An Exception occured while reconstructing the pdf document: " + e.getMessage(), e); } // end catch finally { try { tmp.delete(); } // end try catch (final Exception ignore) { } try { tmp2.delete(); } // end try catch (final Exception ignore) { } } // end finally }
From source file:org.opensignature.opensignpdf.PDFSigner.java
License:Open Source License
/** * Allow you to sign a PDF File with a PKCS11 session opened. * //from w w w . ja v a 2 s .co m * @param mySign * @param session * @param pdfFiles * @param suffix * @param reason * @param signatureVisibility * @param cal * @throws OpenSignatureException * @throws TokenException * @throws IOException * @throws CertificateException * @throws OpenSignatureException * @throws KeyStoreException * @throws UnrecoverableKeyException * @throws NoSuchAlgorithmException * @throws FileNotFoundException * @throws DocumentException * @throws NoSuchAlgorithmException * @throws ExceptionConverter */ public void signPDFwithKS(KeyStore ks, String alias, String pwd, File[] pdfFiles, String suffix, String reason, boolean signatureVisibility, Calendar cal) throws OpenSignatureException, KeyStoreException, NoSuchAlgorithmException, UnrecoverableKeyException { if (pdfFiles == null || ks == null) { throw new OpenSignatureException("Invalid parameters."); } // -- System's date by default if (cal == null) { cal = Calendar.getInstance(); } logger.info("[signPDFwithKS.in]:: " + Arrays.asList(new Object[] { "<ks>", alias, Arrays.asList(pdfFiles), suffix, reason, Boolean.valueOf(signatureVisibility) })); if (alias == null) { Enumeration aliases = ks.aliases(); while (aliases.hasMoreElements()) { String alTmp = (String) aliases.nextElement(); logger.debug("[signPDFwithKS]:: alTmp: " + alTmp); X509Certificate x509certificate = (X509Certificate) ks.getCertificate(alTmp); boolean[] keyUsage = x509certificate.getKeyUsage(); if (keyUsage != null && (keyUsage[1] || keyUsage[0])) { alias = alTmp; break; } } } logger.debug("\n\n[signPDFwithKS]:: alias: " + alias + "\n\n"); PrivateKey key = (PrivateKey) ks.getKey(alias, pwd.toCharArray()); Certificate[] certs = ks.getCertificateChain(alias); for (int i = 0; i < pdfFiles.length; i++) { logger.info("[signPDFwithKS]:: Signing the file: " + pdfFiles[i].getAbsolutePath()); try { // -- Check the access to the PDF if (!pdfFiles[i].exists() || !pdfFiles[i].canRead()) { throw new FileNotFoundException( "The file '" + pdfFiles[i].getAbsolutePath() + "' doesn't exist."); } byte signatureBytes[] = new byte[128]; // -- Creating the OutputStream overwritting the file if it exists // previously File fOut = FileUtils.addSuffix(pdfFiles[i], suffix, true); FileOutputStream fos = new FileOutputStream(fOut); BufferedOutputStream bos = new BufferedOutputStream(fos); // -- Creating the reader PdfReader reader = createPDFReader(pdfFiles[i]); PdfStamperOSP stamper; if ("countersigner".equals(typeSignatureSelected)) { stamper = PdfStamperOSP.createSignature(reader, bos, '\0', null, true); } else { stamper = PdfStamperOSP.createSignature(reader, bos, '\0'); } PdfSignatureAppearanceOSP sap = stamper.getSignatureAppearance(); sap.setCrypto(null, certs, null, PdfSignatureAppearance.WINCER_SIGNED); sap.setReason(reason); if (signatureVisibility) { if ("countersigner".equals(typeSignatureSelected)) { sap.setCertified(0); sap.setVisibleSignature(fieldName); } else { sap.setCertified(2); if (!"".equals(fieldName)) { sap.setVisibleSignature(fieldName); } else { sap.setVisibleSignature(new com.lowagie.text.Rectangle(llx, lly, urx, ury), 1, null); } } } sap.setExternalDigest(new byte[128], new byte[20], "RSA"); PdfDictionary dic = new PdfDictionary(); dic.put(PdfName.FT, PdfName.SIG); dic.put(PdfName.FILTER, new PdfName("Adobe.PPKLite")); dic.put(PdfName.SUBFILTER, new PdfName("adbe.pkcs7.detached")); if (cal != null) { dic.put(PdfName.M, new PdfDate(cal)); } else { dic.put(PdfName.M, new PdfNull()); } dic.put(PdfName.NAME, new PdfString(PdfPKCS7.getSubjectFields((X509Certificate) certs[0]).getField("CN"))); dic.put(PdfName.REASON, new PdfString(reason)); sap.setCryptoDictionary(dic); HashMap exc = new HashMap(); exc.put(PdfName.CONTENTS, new Integer(0x5002)); sap.preClose(exc); byte[] content = IOUtils.streamToByteArray(sap.getRangeStream()); //SHA256, alias CMSSignedDataGenerator.DIGEST_SHA256, // alias NISTObjectIdentifiers.id_sha256.getId(), // alias "2.16.840.1.101.3.4.2.1" byte[] hash = MessageDigest.getInstance("2.16.840.1.101.3.4.2.1", "BC").digest(content); // costruzione degli authenticated attributes ASN1EncodableVector signedAttributes = buildSignedAttributes(hash, cal); byte[] bytesForSecondHash = IOUtils.toByteArray(new DERSet(signedAttributes)); // -- Signature generated with the private key of the KS Signature signature = Signature.getInstance("SHA256withRSA"); signature.initSign(key); signature.update(bytesForSecondHash); signatureBytes = signature.sign(); byte[] encodedPkcs7 = null; try { // Create the set of Hash algorithms DERConstructedSet digestAlgorithms = new DERConstructedSet(); // Creo manualmente la sequenza di digest algos ASN1EncodableVector algos = new ASN1EncodableVector(); //algos.add(new DERObjectIdentifier("1.3.14.3.2.26")); // SHA1 //SHA-256 algos.add(new DERObjectIdentifier("2.16.840.1.101.3.4.2.1")); algos.add(new DERNull()); digestAlgorithms.addObject(new DERSequence(algos)); // Create the contentInfo. ASN1EncodableVector ev = new ASN1EncodableVector(); ev.add(new DERObjectIdentifier("1.2.840.113549.1.7.1")); // PKCS7SignedData DERSequence contentinfo = new DERSequence(ev); // Get all the certificates // ASN1EncodableVector v = new ASN1EncodableVector(); for (int c = 0; c < certs.length; c++) { ASN1InputStream tempstream = new ASN1InputStream( new ByteArrayInputStream(certs[c].getEncoded())); v.add(tempstream.readObject()); } DERSet dercertificates = new DERSet(v); // Create signerinfo structure. // ASN1EncodableVector signerinfo = new ASN1EncodableVector(); // Add the signerInfo version // signerinfo.add(new DERInteger(1)); v = new ASN1EncodableVector(); v.add(CertUtil.getIssuer((X509Certificate) certs[0])); v.add(new DERInteger(((X509Certificate) certs[0]).getSerialNumber())); signerinfo.add(new DERSequence(v)); // Add the digestAlgorithm v = new ASN1EncodableVector(); //v.add(new DERObjectIdentifier("1.3.14.3.2.26")); // SHA1 //SHA-256 v.add(new DERObjectIdentifier("1.2.840.113549.1.7.1")); v.add(new DERNull()); signerinfo.add(new DERSequence(v)); // add the authenticated attribute if present signerinfo.add(new DERTaggedObject(false, 0, new DERSet(signedAttributes))); // Add the digestEncryptionAlgorithm v = new ASN1EncodableVector(); v.add(new DERObjectIdentifier("1.2.840.113549.1.1.1"));// RSA v.add(new DERNull()); signerinfo.add(new DERSequence(v)); // Add the encrypted digest signerinfo.add(new DEROctetString(signatureBytes)); // Add unsigned attributes (timestamp) if (serverTimestamp != null && !"".equals(serverTimestamp.toString())) { byte[] timestampHash = MessageDigest.getInstance("SHA-256").digest(signatureBytes); ASN1EncodableVector unsignedAttributes = buildUnsignedAttributes(timestampHash, serverTimestamp, usernameTimestamp, passwordTimestamp); if (unsignedAttributes != null) { signerinfo.add(new DERTaggedObject(false, 1, new DERSet(unsignedAttributes))); } } // Finally build the body out of all the components above ASN1EncodableVector body = new ASN1EncodableVector(); body.add(new DERInteger(1)); // pkcs7 version, always 1 body.add(digestAlgorithms); body.add(contentinfo); body.add(new DERTaggedObject(false, 0, dercertificates)); // Only allow one signerInfo body.add(new DERSet(new DERSequence(signerinfo))); // Now we have the body, wrap it in it's PKCS7Signed shell // and return it // ASN1EncodableVector whole = new ASN1EncodableVector(); whole.add(new DERObjectIdentifier("1.2.840.113549.1.7.2"));// PKCS7_SIGNED_DATA whole.add(new DERTaggedObject(0, new DERSequence(body))); encodedPkcs7 = IOUtils.toByteArray(new DERSequence(whole)); } catch (Exception e) { throw new ExceptionConverter(e); } PdfDictionary dic2 = new PdfDictionary(); byte out[] = new byte[0x5000 / 2]; System.arraycopy(encodedPkcs7, 0, out, 0, encodedPkcs7.length); dic2.put(PdfName.CONTENTS, new PdfString(out).setHexWriting(true)); sap.close(dic2); bos.close(); fos.close(); } catch (Exception e) { logger.warn("[signPDFwithKS]:: ", e); } } logger.info("[signPDFwithKS.out]:: "); }
From source file:org.opensignature.opensignpdf.PDFSigner.java
License:Open Source License
/** * @param mySign//www . j a v a2 s. c o m * @param session * @param reason * @param signCertKeyObject * @param certs * @param stamper * @throws IOException * @throws DocumentException * @throws NoSuchAlgorithmException * @throws TokenException * @throws ExceptionConverter * @throws NoSuchProviderException */ private void createSignatureAppearance(MyPkcs11 mySign, Session session, String reason, Key signCertKeyObject, X509Certificate[] certs, PdfStamperOSP stamper, boolean signatureVisible, Calendar cal) throws IOException, DocumentException, NoSuchAlgorithmException, TokenException, ExceptionConverter, NoSuchProviderException { logger.info("[createSignatureAppearance.in]:: "); byte[] signatureBytes = new byte[128]; PdfSignatureAppearanceOSP sap = stamper.getSignatureAppearance(); sap.setCrypto(null, certs, null, PdfSignatureAppearance.WINCER_SIGNED); sap.setReason(reason); if (signatureVisible) { if ("countersigner".equals(typeSignatureSelected)) { sap.setCertified(0); sap.setVisibleSignature(fieldName); } else { sap.setCertified(0); if ((fieldName != null) && (!"".equals(fieldName))) { sap.setVisibleSignature(fieldName); } else { sap.setVisibleSignature(new com.lowagie.text.Rectangle(llx, lly, urx, ury), 1, null); } } } //aggiunta di grafico per la firma if ("true".equals(graphicSignSelected)) { sap.setSignatureGraphic(Image.getInstance(fileImgfirma)); sap.setRender(2); } else { sap.setRender(0); } sap.setExternalDigest(new byte[128], new byte[20], "RSA"); PdfDictionary dic = new PdfDictionary(); dic.put(PdfName.FT, PdfName.SIG); dic.put(PdfName.FILTER, new PdfName("Adobe.PPKLite")); dic.put(PdfName.SUBFILTER, new PdfName("adbe.pkcs7.detached")); if (cal != null) { dic.put(PdfName.M, new PdfDate(cal)); } else { dic.put(PdfName.M, new PdfNull()); } dic.put(PdfName.NAME, new PdfString(PdfPKCS7.getSubjectFields((X509Certificate) certs[0]).getField("CN"))); dic.put(PdfName.REASON, new PdfString(reason)); sap.setCryptoDictionary(dic); HashMap exc = new HashMap(); exc.put(PdfName.CONTENTS, new Integer(0x5002)); sap.preClose(exc); byte[] content = IOUtils.streamToByteArray(sap.getRangeStream()); byte[] hash = MessageDigest.getInstance("2.16.840.1.101.3.4.2.1", "BC").digest(content); // costruzione degli authenticated attributes ASN1EncodableVector signedAttributes = buildSignedAttributes(hash, cal); byte[] bytesForSecondHash = IOUtils.toByteArray(new DERSet(signedAttributes)); byte[] secondHash = MessageDigest.getInstance("2.16.840.1.101.3.4.2.1").digest(bytesForSecondHash); // -- Generatting the signature signatureBytes = mySign.sign(session, secondHash, signCertKeyObject); byte[] encodedPkcs7 = null; try { // Create the set of Hash algorithms DERConstructedSet digestAlgorithms = new DERConstructedSet(); // Creo manualmente la sequenza di digest algos ASN1EncodableVector algos = new ASN1EncodableVector(); //algos.add(new DERObjectIdentifier("1.3.14.3.2.26")); // SHA1 //SHA256 algos.add(new DERObjectIdentifier("2.16.840.1.101.3.4.2.1")); algos.add(new DERNull()); digestAlgorithms.addObject(new DERSequence(algos)); // Create the contentInfo. ASN1EncodableVector ev = new ASN1EncodableVector(); ev.add(new DERObjectIdentifier("1.2.840.113549.1.7.1")); // PKCS7SignedData DERSequence contentinfo = new DERSequence(ev); // Get all the certificates // ASN1EncodableVector v = new ASN1EncodableVector(); for (int c = 0; c < certs.length; c++) { ASN1InputStream tempstream = new ASN1InputStream(new ByteArrayInputStream(certs[c].getEncoded())); v.add(tempstream.readObject()); } DERSet dercertificates = new DERSet(v); // Create signerinfo structure. // ASN1EncodableVector signerinfo = new ASN1EncodableVector(); // Add the signerInfo version // signerinfo.add(new DERInteger(1)); v = new ASN1EncodableVector(); v.add(CertUtil.getIssuer(certs[0])); v.add(new DERInteger(certs[0].getSerialNumber())); signerinfo.add(new DERSequence(v)); // Add the digestAlgorithm v = new ASN1EncodableVector(); //v.add(new DERObjectIdentifier("1.3.14.3.2.26")); // SHA1 //SHA-256 v.add(new DERObjectIdentifier("2.16.840.1.101.3.4.2.1")); v.add(new DERNull()); signerinfo.add(new DERSequence(v)); // add the authenticated attribute if present signerinfo.add(new DERTaggedObject(false, 0, new DERSet(signedAttributes))); // Add the digestEncryptionAlgorithm v = new ASN1EncodableVector(); v.add(new DERObjectIdentifier("1.2.840.113549.1.1.1"));// RSA v.add(new DERNull()); signerinfo.add(new DERSequence(v)); // Add the encrypted digest signerinfo.add(new DEROctetString(signatureBytes)); // Add unsigned attributes (timestamp) if (serverTimestamp != null && !"".equals(serverTimestamp.toString())) { byte[] timestampHash = MessageDigest.getInstance("2.16.840.1.101.3.4.2.1", "BC") .digest(signatureBytes); ASN1EncodableVector unsignedAttributes = buildUnsignedAttributes(timestampHash, serverTimestamp, usernameTimestamp, passwordTimestamp); if (unsignedAttributes != null) { signerinfo.add(new DERTaggedObject(false, 1, new DERSet(unsignedAttributes))); } } // Finally build the body out of all the components above ASN1EncodableVector body = new ASN1EncodableVector(); body.add(new DERInteger(1)); // pkcs7 version, always 1 body.add(digestAlgorithms); body.add(contentinfo); body.add(new DERTaggedObject(false, 0, dercertificates)); // Only allow one signerInfo body.add(new DERSet(new DERSequence(signerinfo))); // Now we have the body, wrap it in it's PKCS7Signed shell // and return it // ASN1EncodableVector whole = new ASN1EncodableVector(); whole.add(new DERObjectIdentifier("1.2.840.113549.1.7.2"));// PKCS7_SIGNED_DATA whole.add(new DERTaggedObject(0, new DERSequence(body))); encodedPkcs7 = IOUtils.toByteArray(new DERSequence(whole)); } catch (Exception e) { throw new ExceptionConverter(e); } PdfDictionary dic2 = new PdfDictionary(); byte out[] = new byte[0x5000 / 2]; System.arraycopy(encodedPkcs7, 0, out, 0, encodedPkcs7.length); dic2.put(PdfName.CONTENTS, new PdfString(out).setHexWriting(true)); sap.close(dic2); logger.info("[createSignatureAppearance.retorna]:: "); }
From source file:org.webpki.pdf.PDFSigner.java
License:Apache License
public byte[] addDocumentSignature(byte[] indoc, boolean certified) throws IOException { try {/*w ww . j a v a 2s.c o m*/ PdfReader reader = new PdfReader(indoc); ByteArrayOutputStream bout = new ByteArrayOutputStream(8192); PdfStamper stp = PdfStamper.createSignature(reader, bout, '\0', null, true); for (Attachment file : attachments) { stp.addFileAttachment(file.description, file.data, "dummy", file.filename); } PdfSignatureAppearance sap = stp.getSignatureAppearance(); sap.setCrypto(null, signer.getCertificatePath(), null, PdfSignatureAppearance.WINCER_SIGNED); if (reason != null) { sap.setReason(reason); } if (location != null) { sap.setLocation(location); } if (enable_signature_graphics) { sap.setVisibleSignature(new Rectangle(100, 100, 400, 130), reader.getNumberOfPages(), null); } sap.setCertified(certified); // sap.setExternalDigest (new byte[128], new byte[20], "RSA"); sap.setExternalDigest(new byte[512], new byte[20], "RSA"); sap.preClose(); MessageDigest messageDigest = MessageDigest.getInstance("SHA1"); byte buf[] = new byte[8192]; int n; InputStream inp = sap.getRangeStream(); while ((n = inp.read(buf)) > 0) { messageDigest.update(buf, 0, n); } byte hash[] = messageDigest.digest(); PdfSigGenericPKCS sg = sap.getSigStandard(); PdfLiteral slit = (PdfLiteral) sg.get(PdfName.CONTENTS); byte[] outc = new byte[(slit.getPosLength() - 2) / 2]; PdfPKCS7 sig = sg.getSigner(); sig.setExternalDigest(signer.signData(hash, AsymSignatureAlgorithms.RSA_SHA1), hash, "RSA"); PdfDictionary dic = new PdfDictionary(); byte[] ssig = sig.getEncodedPKCS7(); System.arraycopy(ssig, 0, outc, 0, ssig.length); dic.put(PdfName.CONTENTS, new PdfString(outc).setHexWriting(true)); sap.close(dic); return bout.toByteArray(); } catch (NoSuchAlgorithmException nsae) { throw new IOException(nsae.getMessage()); } catch (DocumentException de) { throw new IOException(de.getMessage()); } }
From source file:si.vsrs.cif.svev.example.utils.PDFSignature.java
License:EUPL
public File signPDF(File document, InputStream keystore, String password, String keyPassord, String keystoreType, String alias, boolean bshowVisualization) { if (document == null || !document.exists()) { throw new RuntimeException("Error reading pdf"); }/*from w w w . j a va2 s. c o m*/ String name = document.getName(); String substring = name.substring(0, name.lastIndexOf(".")); File outputDocument = new File(document.getParent(), substring + "_signed.pdf"); try (FileInputStream fis = new FileInputStream(document); FileOutputStream fout = new FileOutputStream(outputDocument)) { KeyStore ks = KeyStore.getInstance(keystoreType); ks.load(keystore, password.toCharArray()); PrivateKey key = (PrivateKey) ks.getKey(alias, keyPassord.toCharArray()); Certificate[] chain = ks.getCertificateChain(alias); X509Certificate xcert = (X509Certificate) chain[0]; PdfReader reader = new PdfReader(fis); char tmpPdfVersion = '\0'; // default version - the same as input final PdfStamper stp = PdfStamper.createSignature(reader, fout, tmpPdfVersion, null, true); final PdfSignatureAppearance sap = stp.getSignatureAppearance(); sap.setCrypto(key, chain, null, PdfSignatureAppearance.WINCER_SIGNED); sap.setReason("Testni podpis"); sap.setLocation("Maribor"); sap.setContact(xcert.getSubjectDN().getName()); // sap.setLayer2Text(""); // sap.setLayer4Text(""); sap.setAcro6Layers(true); // --:> Rectangle rc = reader.getPageSize(1); if (bshowVisualization) { sap.setVisibleSignature(new Rectangle(5, rc.getHeight() - 40, 240, rc.getHeight() - 5), 1, null); } final PdfSignature dic = new PdfSignature(PdfName.ADOBE_PPKLITE, new 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); final int contentEstimated = 15000; final HashMap<PdfName, Integer> exc = new HashMap<>(); exc.put(PdfName.CONTENTS, contentEstimated * 2 + 2); sap.preClose(exc); PdfPKCS7 sgn = new PdfPKCS7(key, chain, null, "SHA-256", null, false); InputStream data = sap.getRangeStream(); final MessageDigest messageDigest = MessageDigest.getInstance("SHA-256"); byte buf[] = new byte[8192]; int n; while ((n = data.read(buf)) > 0) { messageDigest.update(buf, 0, n); } byte hash[] = messageDigest.digest(); Calendar cal = Calendar.getInstance(); byte sh[] = sgn.getAuthenticatedAttributeBytes(hash, cal, null); sgn.update(sh, 0, sh.length); byte[] encodedSig = sgn.getEncodedPKCS7(hash, cal, null, null); byte[] paddedSig = new byte[contentEstimated]; System.arraycopy(encodedSig, 0, paddedSig, 0, encodedSig.length); PdfDictionary dic2 = new PdfDictionary(); dic2.put(PdfName.CONTENTS, new PdfString(paddedSig).setHexWriting(true)); sap.close(dic2); } catch (IOException | KeyStoreException | NoSuchAlgorithmException | CertificateException | UnrecoverableKeyException | DocumentException | InvalidKeyException | NoSuchProviderException | SignatureException ex) { throw new RuntimeException(ex.getMessage(), ex); } return outputDocument; }
From source file:vn.vfossa.signature.PdfContent.java
License:Open Source License
@Override public void addSignature(X509Certificate certificate, PrivateKey key) throws Exception { // TODO Auto-generated method stub Certificate cer[] = { certificate }; for (int index = path.length() - 1; index >= 0; index--) if (path.charAt(index) == '.') { signedPath = path.substring(0, index) + "_signed" + path.substring(index); break; }//from w w w . ja v a2s . c o m File file = new File(signedPath); FileOutputStream out = new FileOutputStream(file); int numOfPages = content.getNumberOfPages(); int numOfSignatures = content.getAcroFields().getSignatureNames().size() + 1; PdfStamper stp = PdfStamper.createSignature(content, out, '\0', null, true); PdfSignatureAppearance sap = stp.getSignatureAppearance(); int m = (numOfPages - 1) * 5 + (numOfSignatures - 1) * 200; try { Calendar ca = Calendar.getInstance(); ca.setTime(new Date()); sap.setSignDate(ca); } catch (Exception ex) { ex.printStackTrace(); } sap.setCrypto(key, cer, null, PdfSignatureAppearance.WINCER_SIGNED); sap.setVisibleSignature(new com.lowagie.text.Rectangle(m, 0, m + 200, 30), 1, null); stp.close(); //Files.delete(Paths.get(path)); content = new PdfReader(signedPath); }