List of usage examples for com.itextpdf.text.pdf PdfSignatureAppearance setVisibleSignature
public void setVisibleSignature(Rectangle pageRect, int page, String fieldName)
From source file:SigningProcess.java
public static String sign(String base64, HashMap map) { String base64string = null;//from ww w . ja v a2 s . com try { System.out.println("map :" + map); // Getting a set of the entries Set set = map.entrySet(); System.out.println("set :" + set); // Get an iterator Iterator it = set.iterator(); // Display elements while (it.hasNext()) { Entry me = (Entry) it.next(); String key = (String) me.getKey(); if ("privateKey".equalsIgnoreCase(key)) { privateKey = (PrivateKey) me.getValue(); } if ("certificateChain".equalsIgnoreCase(key)) { certificateChain = (X509Certificate[]) me.getValue(); } } OcspClient ocspClient = new OcspClientBouncyCastle(); TSAClient tsaClient = null; for (int i = 0; i < certificateChain.length; i++) { X509Certificate cert = (X509Certificate) certificateChain[i]; String tsaUrl = CertificateUtil.getTSAURL(cert); if (tsaUrl != null) { tsaClient = new TSAClientBouncyCastle(tsaUrl); break; } } List<CrlClient> crlList = new ArrayList<CrlClient>(); crlList.add(new CrlClientOnline(certificateChain)); String property = System.getProperty("java.io.tmpdir"); BASE64Decoder decoder = new BASE64Decoder(); byte[] FileByte = decoder.decodeBuffer(base64); writeByteArraysToFile(property + "_unsigned.pdf", FileByte); // Creating the reader and the stamper PdfReader reader = new PdfReader(property + "_unsigned.pdf"); FileOutputStream os = new FileOutputStream(property + "_signed.pdf"); PdfStamper stamper = PdfStamper.createSignature(reader, os, '\0'); // Creating the appearance PdfSignatureAppearance appearance = stamper.getSignatureAppearance(); // appearance.setReason(reason); // appearance.setLocation(location); appearance.setAcro6Layers(false); appearance.setVisibleSignature(new Rectangle(36, 748, 144, 780), 1, "sig1"); // Creating the signature ExternalSignature pks = new PrivateKeySignature((PrivateKey) privateKey, DigestAlgorithms.SHA256, providerMSCAPI.getName()); ExternalDigest digest = new BouncyCastleDigest(); MakeSignature.signDetached(appearance, digest, pks, certificateChain, crlList, ocspClient, tsaClient, 0, MakeSignature.CryptoStandard.CMS); InputStream docStream = new FileInputStream(property + "_signed.pdf"); byte[] encodeBase64 = Base64.encodeBase64(IOUtils.toByteArray(docStream)); base64string = new String(encodeBase64); } catch (IOException ex) { System.out.println("Exception :" + ex.getLocalizedMessage()); } catch (DocumentException ex) { System.out.println("Exception :" + ex.getLocalizedMessage()); } catch (GeneralSecurityException ex) { System.out.println("Exception :" + ex.getLocalizedMessage()); } return base64string; }
From source file:com.bluexml.side.Framework.alfresco.signature.repo.action.executer.PDFSignatureActionExecuter.java
License:Open Source License
/** * /*from www .java 2 s. co m*/ * @param ruleAction * @param actionedUponNodeRef * @param actionedUponContentReader * @throws Exception */ protected void doSignature(Action ruleAction, NodeRef actionedUponNodeRef, ContentReader actionedUponContentReader) throws Exception { NodeRef privateKey = (NodeRef) ruleAction.getParameterValue(PARAM_PRIVATE_KEY); String location = (String) ruleAction.getParameterValue(PARAM_LOCATION); String reason = (String) ruleAction.getParameterValue(PARAM_REASON); String visibility = (String) ruleAction.getParameterValue(PARAM_VISIBILITY); String keyPassword = (String) ruleAction.getParameterValue(PARAM_KEY_PASSWORD); String keyType = (String) ruleAction.getParameterValue(PARAM_KEY_TYPE); String signedName = (String) ruleAction.getParameterValue(PARAM_SIGNED_NAME); int height = Integer.parseInt((String) ruleAction.getParameterValue(PARAM_HEIGHT)); int width = Integer.parseInt((String) ruleAction.getParameterValue(PARAM_WIDTH)); // New keystore parameters String alias = (String) ruleAction.getParameterValue(PARAM_ALIAS); String storePassword = (String) ruleAction.getParameterValue(PARAM_STORE_PASSWORD); // Ugly and verbose, but fault-tolerant String locationXStr = (String) ruleAction.getParameterValue(PARAM_LOCATION_X); String locationYStr = (String) ruleAction.getParameterValue(PARAM_LOCATION_Y); int locationX = 0; int locationY = 0; try { locationX = locationXStr != null ? Integer.parseInt(locationXStr) : 0; } catch (NumberFormatException e) { locationX = 0; } try { locationY = locationXStr != null ? Integer.parseInt(locationYStr) : 0; } catch (NumberFormatException e) { locationY = 0; } File tempDir = null; ContentWriter writer = null; KeyStore ks = null; try { // get a keystore instance by if (keyType == null || keyType.equalsIgnoreCase(KEY_TYPE_DEFAULT)) { ks = KeyStore.getInstance(KeyStore.getDefaultType()); } else if (keyType.equalsIgnoreCase(KEY_TYPE_PKCS12)) { ks = KeyStore.getInstance("pkcs12"); } else { throw new Exception("Unknown key type " + keyType + " specified"); } // open the reader to the key and load it ContentReader keyReader = serviceRegistry.getContentService().getReader(privateKey, ContentModel.PROP_CONTENT); ks.load(keyReader.getContentInputStream(), storePassword.toCharArray()); // set alias // String alias = (String) ks.aliases().nextElement(); PrivateKey key = (PrivateKey) ks.getKey(alias, keyPassword.toCharArray()); Certificate[] chain = ks.getCertificateChain(alias); //open original pdf ContentReader pdfReader = getReader(actionedUponNodeRef); PdfReader reader = new PdfReader(pdfReader.getContentInputStream()); // create temp dir to store file File alfTempDir = TempFileProvider.getTempDir(); tempDir = new File(alfTempDir.getPath() + File.separatorChar + actionedUponNodeRef.getId()); tempDir.mkdir(); File file = new File(tempDir, serviceRegistry.getFileFolderService().getFileInfo(actionedUponNodeRef).getName()); FileOutputStream fout = new FileOutputStream(file); PdfStamper stamp = PdfStamper.createSignature(reader, fout, '\0'); PdfSignatureAppearance sap = stamp.getSignatureAppearance(); sap.setCrypto(key, chain, null, PdfSignatureAppearance.WINCER_SIGNED); // set reason for signature and location of signer sap.setReason(reason); sap.setLocation(location); if (visibility.equalsIgnoreCase(PDFSignatureActionExecuter.VISIBILITY_VISIBLE)) { sap.setVisibleSignature(new Rectangle(locationX + width, locationY - height, locationX, locationY), 1, null); } stamp.close(); String[] splitedFilename = file.getName().split("\\."); String name = "-" + signedName + "." + splitedFilename[splitedFilename.length - 1]; for (int i = splitedFilename.length - 2; i >= 0; i--) { if (name.equals("-" + signedName + "." + splitedFilename[splitedFilename.length - 1])) { name = splitedFilename[i] + name; } else { name = splitedFilename[i] + "." + name; } } writer = getWriter(name, (NodeRef) ruleAction.getParameterValue(PARAM_DESTINATION_FOLDER)); writer.setEncoding(actionedUponContentReader.getEncoding()); writer.setMimetype(FILE_MIMETYPE); writer.putContent(file); file.delete(); } catch (Exception e) { throw e; } finally { if (tempDir != null) { try { tempDir.delete(); } catch (Exception ex) { } } } }
From source file:com.isa.firma.FirmaPDFController.java
public ByteArrayOutputStream firmar(PDFFirma infoFirma, InputStream pdfbase64) throws AppletException { try {/* w w w. j av a 2 s . c o m*/ System.out.println("Firma Controller::firmar"); PdfReader reader = new PdfReader(pdfbase64); ByteArrayOutputStream os = new ByteArrayOutputStream(); PdfStamper stamper = PdfStamper.createSignature(reader, os, '\0', null, true); PdfSignatureAppearance appearance = stamper.getSignatureAppearance(); System.out.println("Pre definir apariencia..."); if (infoFirma.isApariencia()) { System.out.println("Insertando apriencia en documento..."); appearance.setSignatureGraphic(Image.getInstance(new URL(infoFirma.getRutaImagen()))); appearance.setRenderingMode(Utiles.getModoApariencia()); int numeroPagFirma = infoFirma.getHoja() == -1 ? reader.getNumberOfPages() : infoFirma.getHoja(); int cantidadFirmaActuales = reader.getAcroFields().getSignatureNames().size(); int[] coords = infoFirma.calcularCorrdenadasFirma(cantidadFirmaActuales, infoFirma.getAncho(), infoFirma.getLargo()); //llx, lly, urx, ury String v = Utiles.encodingString(infoFirma.getFirmante()); System.out.println("Post encoding: " + v); appearance.setLayer2Text(v); //appearance.setLayer2Text( infoFirma.getFirmante() ); appearance.setVisibleSignature(new Rectangle(coords[0], coords[1], coords[2], coords[3]), numeroPagFirma, "Id: " + IdGenerator.generate()); } ExternalSignature es = new PrivateKeySignature(infoFirma.getPk(), "SHA-256", infoFirma.getProvidername()); ExternalDigest digest = new BouncyCastleDigest(); MakeSignature.signDetached(appearance, digest, es, infoFirma.getChainCert(), null, null, null, 0, CryptoStandard.CMS); System.out.println("PDF Firmado correctamente."); return os; } catch (IOException ex) { Logger.getLogger(FirmaPDFController.class.getName()).log(Level.SEVERE, null, ex); throw new AppletException(UtilesMsg.ERROR_FIRMANDO_DOCUMENTO, null, ex.getCause()); } catch (DocumentException ex) { Logger.getLogger(FirmaPDFController.class.getName()).log(Level.SEVERE, null, ex); throw new AppletException(UtilesMsg.ERROR_FIRMANDO_DOCUMENTO, null, ex.getCause()); } catch (KeyStoreException ex) { Logger.getLogger(FirmaPDFController.class.getName()).log(Level.SEVERE, null, ex); throw new AppletException(UtilesMsg.ERROR_FIRMANDO_DOCUMENTO, null, ex.getCause()); } catch (NoSuchAlgorithmException ex) { Logger.getLogger(FirmaPDFController.class.getName()).log(Level.SEVERE, null, ex); throw new AppletException(UtilesMsg.ERROR_FIRMANDO_DOCUMENTO, null, ex.getCause()); } catch (UnrecoverableKeyException ex) { Logger.getLogger(FirmaPDFController.class.getName()).log(Level.SEVERE, null, ex); throw new AppletException(UtilesMsg.ERROR_FIRMANDO_DOCUMENTO, null, ex.getCause()); } catch (GeneralSecurityException ex) { Logger.getLogger(FirmaPDFController.class.getName()).log(Level.SEVERE, null, ex); throw new AppletException(UtilesMsg.ERROR_FIRMANDO_DOCUMENTO, null, ex.getCause()); } }
From source file:com.isa.firma.pades.FirmaPDFController.java
public ByteArrayOutputStream firmar(PDFFirma infoFirma, InputStream pdfbase64) throws AppletException { try {//from w ww.j a va 2 s .c o m PdfReader reader = new PdfReader(pdfbase64); ByteArrayOutputStream os = new ByteArrayOutputStream(); PdfStamper stamper = PdfStamper.createSignature(reader, os, '\0', null, true); PdfSignatureAppearance appearance = stamper.getSignatureAppearance(); if (infoFirma.isApariencia()) { System.out.println("Definiendo apariencia..."); appearance.setRenderingMode(Utiles.getModoApariencia()); if (!Utiles.getModoApariencia().equals(PdfSignatureAppearance.RenderingMode.DESCRIPTION)) { appearance.setSignatureGraphic(Image.getInstance(new URL(infoFirma.getRutaImagen()))); } int numeroPagFirma = infoFirma.getHoja() == -1 ? reader.getNumberOfPages() : infoFirma.getHoja(); int cantidadFirmaActuales = reader.getAcroFields().getSignatureNames().size(); int[] coords = infoFirma.calcularCorrdenadasFirma(cantidadFirmaActuales, infoFirma.getAncho(), infoFirma.getLargo()); System.out.println("firmante: " + infoFirma.getFirmante()); System.out.println("serie: " + infoFirma.getNroSerie()); //llx, lly, urx, ury appearance.setLayer2Text(infoFirma.generarTextoEnFirma()); appearance.setVisibleSignature(new Rectangle(coords[0], coords[1], coords[2], coords[3]), numeroPagFirma, "Id: " + IdGenerator.generate()); } ExternalSignature es = new PrivateKeySignature(infoFirma.getPk(), "SHA-256", infoFirma.getProvidername()); ExternalDigest digest = new BouncyCastleDigest(); MakeSignature.signDetached(appearance, digest, es, infoFirma.getChainCert(), null, null, null, 0, CryptoStandard.CMS); System.out.println("PDF Firmado correctamente."); return os; } catch (IOException ex) { Logger.getLogger(FirmaPDFController.class.getName()).log(Level.SEVERE, null, ex); throw new AppletException(UtilesMsg.ERROR_FIRMANDO_DOCUMENTO, null, ex.getCause()); } catch (DocumentException ex) { Logger.getLogger(FirmaPDFController.class.getName()).log(Level.SEVERE, null, ex); throw new AppletException(UtilesMsg.ERROR_FIRMANDO_DOCUMENTO, null, ex.getCause()); } catch (KeyStoreException ex) { Logger.getLogger(FirmaPDFController.class.getName()).log(Level.SEVERE, null, ex); throw new AppletException(UtilesMsg.ERROR_FIRMANDO_DOCUMENTO, null, ex.getCause()); } catch (NoSuchAlgorithmException ex) { Logger.getLogger(FirmaPDFController.class.getName()).log(Level.SEVERE, null, ex); throw new AppletException(UtilesMsg.ERROR_FIRMANDO_DOCUMENTO, null, ex.getCause()); } catch (UnrecoverableKeyException ex) { Logger.getLogger(FirmaPDFController.class.getName()).log(Level.SEVERE, null, ex); throw new AppletException(UtilesMsg.ERROR_FIRMANDO_DOCUMENTO, null, ex.getCause()); } catch (GeneralSecurityException ex) { Logger.getLogger(FirmaPDFController.class.getName()).log(Level.SEVERE, null, ex); throw new AppletException(UtilesMsg.ERROR_FIRMANDO_DOCUMENTO, null, ex.getCause()); } }
From source file:com.vectorprint.report.itext.style.stylers.DocumentSettings.java
License:Open Source License
/** * adds a visible signature of 200 / 100 at top left of the first page of the pdf with "verify origin" as reason, the * localhost name as location. Uses MakeSignature.signDetached(psa, as, pks, certificateChain, null, null, null, 0, * MakeSignature.CryptoStandard.CMS)//from ww w . ja va 2s .c om * * @see #loadKeyStore(char[]) * @see #getKey(java.security.KeyStore, java.lang.String, char[]) } * @param psa * @throws KeyStoreException * @throws NoSuchAlgorithmException * @throws UnrecoverableKeyException * @throws VectorPrintException */ @Override public void configureVisualSignature(PdfSignatureAppearance psa) throws KeyStoreException, NoSuchAlgorithmException, UnrecoverableKeyException, VectorPrintException { psa.setReason("verify origin"); try { psa.setLocation(InetAddress.getLocalHost().getHostName()); } catch (UnknownHostException ex) { log.log(Level.WARNING, "unable to set location for pdf signature", ex); } char[] pw = getValue(KEYSTORE_PASSWORD, char[].class); char[] clone = pw.clone(); KeyStore ks = loadKeyStore(pw); PrivateKey key = getKey(ks, (String) ks.aliases().nextElement(), clone); Certificate[] certificateChain = ks.getCertificateChain((String) ks.aliases().nextElement()); PrivateKeySignature pks = new PrivateKeySignature(key, getValue(DIGESTPARAM, DIGESTALGORITHM.class).name(), "BC"); ExternalDigest as = new BouncyCastleDigest(); psa.setVisibleSignature(new Rectangle(0, getHeight() - 100, 200, getHeight()), 1, "signature"); try { MakeSignature.signDetached(psa, as, pks, certificateChain, null, null, null, 0, MakeSignature.CryptoStandard.CMS); } catch (IOException | DocumentException | GeneralSecurityException ex) { throw new VectorPrintException(ex); } }
From source file:controller.CCInstance.java
License:Open Source License
public final boolean signPdf(final String pdfPath, final String destination, final CCSignatureSettings settings, final SignatureListener sl) throws CertificateException, IOException, DocumentException, KeyStoreException, SignatureFailedException, FileNotFoundException, NoSuchAlgorithmException, InvalidAlgorithmParameterException { PrivateKey pk;/*from www . j av a 2 s . co m*/ final PdfReader reader = new PdfReader(pdfPath); pk = getPrivateKeyFromAlias(settings.getCcAlias().getAlias()); if (getCertificationLevel(pdfPath) == PdfSignatureAppearance.CERTIFIED_NO_CHANGES_ALLOWED) { String message = Bundle.getBundle().getString("fileDoesNotAllowChanges"); if (sl != null) { sl.onSignatureComplete(pdfPath, false, message); } throw new SignatureFailedException(message); } if (reader.getNumberOfPages() - 1 < settings.getPageNumber()) { settings.setPageNumber(reader.getNumberOfPages() - 1); } if (null == pk) { String message = Bundle.getBundle().getString("noSmartcardFound"); if (sl != null) { sl.onSignatureComplete(pdfPath, false, message); } throw new CertificateException(message); } if (null == pkcs11ks.getCertificateChain(settings.getCcAlias().getAlias())) { String message = Bundle.getBundle().getString("certificateNullChain"); if (sl != null) { sl.onSignatureComplete(pdfPath, false, message); } throw new CertificateException(message); } final ArrayList<Certificate> embeddedCertificateChain = settings.getCcAlias().getCertificateChain(); final Certificate owner = embeddedCertificateChain.get(0); final Certificate lastCert = embeddedCertificateChain.get(embeddedCertificateChain.size() - 1); if (null == owner) { String message = Bundle.getBundle().getString("certificateNameUnknown"); if (sl != null) { sl.onSignatureComplete(pdfPath, false, message); } throw new CertificateException(message); } final X509Certificate X509C = ((X509Certificate) lastCert); final Calendar now = Calendar.getInstance(); final Certificate[] filledMissingCertsFromChainInTrustedKeystore = getCompleteTrustedCertificateChain( X509C); final Certificate[] fullCertificateChain; if (filledMissingCertsFromChainInTrustedKeystore.length < 2) { fullCertificateChain = new Certificate[embeddedCertificateChain.size()]; for (int i = 0; i < embeddedCertificateChain.size(); i++) { fullCertificateChain[i] = embeddedCertificateChain.get(i); } } else { fullCertificateChain = new Certificate[embeddedCertificateChain.size() + filledMissingCertsFromChainInTrustedKeystore.length - 1]; int i = 0; for (i = 0; i < embeddedCertificateChain.size(); i++) { fullCertificateChain[i] = embeddedCertificateChain.get(i); } for (int f = 1; f < filledMissingCertsFromChainInTrustedKeystore.length; f++, i++) { fullCertificateChain[i] = filledMissingCertsFromChainInTrustedKeystore[f]; } } // Leitor e Stamper FileOutputStream os = null; try { os = new FileOutputStream(destination); } catch (FileNotFoundException e) { String message = Bundle.getBundle().getString("outputFileError"); if (sl != null) { sl.onSignatureComplete(pdfPath, false, message); } throw new IOException(message); } // Aparncia da Assinatura final char pdfVersion; switch (Settings.getSettings().getPdfVersion()) { case "/1.2": pdfVersion = PdfWriter.VERSION_1_2; break; case "/1.3": pdfVersion = PdfWriter.VERSION_1_3; break; case "/1.4": pdfVersion = PdfWriter.VERSION_1_4; break; case "/1.5": pdfVersion = PdfWriter.VERSION_1_5; break; case "/1.6": pdfVersion = PdfWriter.VERSION_1_6; break; case "/1.7": pdfVersion = PdfWriter.VERSION_1_7; break; default: pdfVersion = PdfWriter.VERSION_1_7; } final PdfStamper stamper = (getNumberOfSignatures(pdfPath) == 0 ? PdfStamper.createSignature(reader, os, pdfVersion) : PdfStamper.createSignature(reader, os, pdfVersion, null, true)); final PdfSignatureAppearance appearance = stamper.getSignatureAppearance(); appearance.setSignDate(now); appearance.setReason(settings.getReason()); appearance.setLocation(settings.getLocation()); appearance.setCertificationLevel(settings.getCertificationLevel()); appearance.setSignatureCreator(SIGNATURE_CREATOR); appearance.setCertificate(owner); final String fieldName = settings.getPrefix() + " " + (1 + getNumberOfSignatures(pdfPath)); if (settings.isVisibleSignature()) { appearance.setVisibleSignature(settings.getPositionOnDocument(), settings.getPageNumber() + 1, fieldName); appearance.setRenderingMode(PdfSignatureAppearance.RenderingMode.DESCRIPTION); if (null != settings.getAppearance().getImageLocation()) { appearance.setImage(Image.getInstance(settings.getAppearance().getImageLocation())); } com.itextpdf.text.Font font = new com.itextpdf.text.Font(FontFactory .getFont(settings.getAppearance().getFontLocation(), BaseFont.IDENTITY_H, BaseFont.EMBEDDED, 0) .getBaseFont()); font.setColor(new BaseColor(settings.getAppearance().getFontColor().getRGB())); if (settings.getAppearance().isBold() && settings.getAppearance().isItalic()) { font.setStyle(Font.BOLD + Font.ITALIC); } else if (settings.getAppearance().isBold()) { font.setStyle(Font.BOLD); } else if (settings.getAppearance().isItalic()) { font.setStyle(Font.ITALIC); } else { font.setStyle(Font.PLAIN); } appearance.setLayer2Font(font); String text = ""; if (settings.getAppearance().isShowName()) { if (!settings.getCcAlias().getName().isEmpty()) { text += settings.getCcAlias().getName() + "\n"; } } if (settings.getAppearance().isShowReason()) { if (!settings.getReason().isEmpty()) { text += settings.getReason() + "\n"; } } if (settings.getAppearance().isShowLocation()) { if (!settings.getLocation().isEmpty()) { text += settings.getLocation() + "\n"; } } if (settings.getAppearance().isShowDate()) { DateFormat df = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss"); SimpleDateFormat sdf = new SimpleDateFormat("Z"); text += df.format(now.getTime()) + " " + sdf.format(now.getTime()) + "\n"; } if (!settings.getText().isEmpty()) { text += settings.getText(); } PdfTemplate layer2 = appearance.getLayer(2); Rectangle rect = settings.getPositionOnDocument(); Rectangle sr = new Rectangle(rect.getWidth(), rect.getHeight()); float size = ColumnText.fitText(font, text, sr, 1024, PdfWriter.RUN_DIRECTION_DEFAULT); ColumnText ct = new ColumnText(layer2); ct.setRunDirection(PdfWriter.RUN_DIRECTION_DEFAULT); ct.setAlignment(Element.ALIGN_MIDDLE); int align; switch (settings.getAppearance().getAlign()) { case 0: align = Element.ALIGN_LEFT; break; case 1: align = Element.ALIGN_CENTER; break; case 2: align = Element.ALIGN_RIGHT; break; default: align = Element.ALIGN_LEFT; } ct.setSimpleColumn(new Phrase(text, font), sr.getLeft(), sr.getBottom(), sr.getRight(), sr.getTop(), size, align); ct.go(); } else { appearance.setVisibleSignature(new Rectangle(0, 0, 0, 0), 1, fieldName); } // CRL <- Pesado! final ArrayList<CrlClient> crlList = null; // OCSP OcspClient ocspClient = new OcspClientBouncyCastle(); // TimeStamp TSAClient tsaClient = null; if (settings.isTimestamp()) { tsaClient = new TSAClientBouncyCastle(settings.getTimestampServer(), null, null); } final String hashAlg = getHashAlgorithm(X509C.getSigAlgName()); final ExternalSignature es = new PrivateKeySignature(pk, hashAlg, pkcs11Provider.getName()); final ExternalDigest digest = new ProviderDigest(pkcs11Provider.getName()); try { MakeSignature.signDetached(appearance, digest, es, fullCertificateChain, crlList, ocspClient, tsaClient, 0, MakeSignature.CryptoStandard.CMS); if (sl != null) { sl.onSignatureComplete(pdfPath, true, ""); } return true; } catch (Exception e) { os.flush(); os.close(); new File(destination).delete(); if ("sun.security.pkcs11.wrapper.PKCS11Exception: CKR_FUNCTION_CANCELED".equals(e.getMessage())) { throw new SignatureFailedException(Bundle.getBundle().getString("userCanceled")); } else if ("sun.security.pkcs11.wrapper.PKCS11Exception: CKR_GENERAL_ERROR".equals(e.getMessage())) { throw new SignatureFailedException(Bundle.getBundle().getString("noPermissions")); } else if (e instanceof ExceptionConverter) { String message = Bundle.getBundle().getString("timestampFailed"); if (sl != null) { sl.onSignatureComplete(pdfPath, false, message); } throw new SignatureFailedException(message); } else { if (sl != null) { sl.onSignatureComplete(pdfPath, false, Bundle.getBundle().getString("unknownErrorLog")); } controller.Logger.getLogger().addEntry(e); } return false; } }
From source file:de.rub.dez6a3.jpdfsigner.control.ITextSigner.java
License:Open Source License
public ByteArrayOutputStream doSign(byte[] pdf, Rectangle stampPos, int pageNmbrForStamp) throws IOException, DocumentException, NoSuchAlgorithmException, InvalidKeyException, SignatureException { Certificate[] chain = signCert.toArray(new Certificate[0]); PdfReader reader = new PdfReader(pdf); ByteArrayOutputStream byteOS = new ByteArrayOutputStream(); PdfStamper stp = PdfStamper.createSignature(reader, byteOS, '\0', null, true); PdfSignatureAppearance sap = stp.getSignatureAppearance(); if (stampPos != null) { sap.setVisibleSignature( new com.itextpdf.text.Rectangle(stampPos.x, stampPos.y, stampPos.width, stampPos.height), pageNmbrForStamp, null); sap.setRenderingMode(PdfSignatureAppearance.RenderingMode.NAME_AND_DESCRIPTION); sap.setAcro6Layers(true);/*from www.j a v a 2 s . co m*/ } // Siganture Appearance PdfSignature dic = new PdfSignature(PdfName.ADOBE_PPKLITE, new PdfName("adbe.pkcs7.detached")); log.info("Creating signature with reason: " + ParamValidator.getInstance().getSignatureReason()); sap.setReason(ParamValidator.getInstance().getSignatureReason()); sap.setLocation("Ruhr-Universitt Bochum"); Image i = Image.getInstance(getClass().getResource("/de/rub/dez6a3/jpdfsigner/resources/images/sign.png")); sap.setImage(i); sap.setCrypto((PrivateKey) signPrivKey, chain, null, PdfSignatureAppearance.WINCER_SIGNED); dic.setReason(ParamValidator.getInstance().getSignatureReason()); dic.setLocation("Ruhr-Universitt Bochum"); sap.setCryptoDictionary(dic); // preserve some space for the contents int contentEstimated = 15000; HashMap<PdfName, Integer> exc = new HashMap<PdfName, Integer>(); exc.put(PdfName.CONTENTS, new Integer(contentEstimated * 2 + 2)); sap.preClose(exc); // make the digest InputStream data = sap.getRangeStream(); MessageDigest messageDigest = MessageDigest.getInstance("SHA1"); 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(); // If we add a time stamp: TSAClient tsc = new TSAClientBouncyCastle("http://zeitstempel.dfn.de/"); // Create the signature PdfPKCS7 sgn; try { sgn = new PdfPKCS7((PrivateKey) signPrivKey, chain, null, "SHA1", null, false); byte sh[] = sgn.getAuthenticatedAttributeBytes(hash, cal, null); sgn.update(sh, 0, sh.length); byte[] encodedSig = sgn.getEncodedPKCS7(hash, cal, tsc, null); if (contentEstimated + 2 < encodedSig.length) { throw new DocumentException("Not enough space"); } byte[] paddedSig = new byte[contentEstimated]; System.arraycopy(encodedSig, 0, paddedSig, 0, encodedSig.length); // Replace the contents PdfDictionary dic2 = new PdfDictionary(); dic2.put(PdfName.CONTENTS, new PdfString(paddedSig).setHexWriting(true)); sap.close(dic2); } catch (NoSuchProviderException ex) { ex.printStackTrace(); } return byteOS; }
From source file:de.sign.SignMain.java
License:Open Source License
public void sign() throws DocumentException, IOException, GeneralSecurityException { PdfReader reader = new PdfReader(this.orgFile); OutputStream os = new FileOutputStream(this.orgFile.replace(".pdf", "SIGN.pdf")); PdfStamper stamper = PdfStamper.createSignature(reader, os, '\0'); // Create appearance PdfSignatureAppearance appearance = stamper.getSignatureAppearance(); Rectangle cropBox = reader.getCropBox(1); float width = 50; float height = 50; Rectangle rectangle = new Rectangle(cropBox.getRight(width) - 20, cropBox.getTop(height) - 20, cropBox.getRight() - 20, cropBox.getTop() - 20); appearance.setVisibleSignature(rectangle, 1, "sig"); appearance.setLocation(getHostname()); appearance.setReason("Evidence of document integrity"); appearance.setCertificationLevel(1); // 1 = CERTIFIED_NO_CHANGES_ALLOWED appearance.setAcro6Layers(false);/* w w w. j a v a2 s . c o m*/ appearance.setLayer2Text(""); //Sign Security.addProvider(new BouncyCastleProvider()); TSAClient tsc = new TSAClientBouncyCastle(this.tsa_URL); ExternalDigest digest = new BouncyCastleDigest(); ExternalSignature signature = new PrivateKeySignature(getPrivateKey(), "SHA-1", "BC"); MakeSignature.signDetached(appearance, digest, signature, getCertificateChain(), null, null, tsc, 0, CryptoStandard.CMS); }
From source file:ec.rubrica.pdf.FirmadorPdf.java
License:Open Source License
public byte[] firmar(PrivateKey pk, X509Certificate certificado, String razon, String ubicacion) throws IOException { try {// w w w. jav a2 s . c o m // Creating the reader and the stamper PdfReader reader = new PdfReader(pdf); ByteArrayOutputStream signedPdf = new ByteArrayOutputStream(); PdfStamper stamper = PdfStamper.createSignature(reader, signedPdf, '\0'); // Creating the appearance PdfSignatureAppearance appearance = stamper.getSignatureAppearance(); appearance.setReason(razon); appearance.setLocation(ubicacion); Rectangle pageSize = reader.getPageSize(1); Rectangle position = new Rectangle(15, pageSize.getHeight() - 50, 250, pageSize.getHeight()); appearance.setVisibleSignature(position, 1, "sig"); // Creating the signature ExternalSignature pks = new PrivateKeySignature(pk, DigestAlgorithms.SHA1, null); Certificate[] chain = new Certificate[] { certificado }; MakeSignature.signDetached(appearance, pks, chain, null, null, tsaClient, BouncyCastleProvider.PROVIDER_NAME, 0, MakeSignature.CMS); return signedPdf.toByteArray(); } catch (DocumentException e) { throw new RuntimeException(e); } catch (GeneralSecurityException e) { throw new RuntimeException(e); } }
From source file:ec.rubrica.pdf.FirmaPDF.java
License:Open Source License
public static byte[] firmar(byte[] pdf, PrivateKey pk, Certificate[] chain, TSAClient tsaClient) throws IOException { try {//from w w w. j a v a 2 s.c o m // Creating the reader and the stamper PdfReader reader = new PdfReader(pdf); ByteArrayOutputStream signedPdf = new ByteArrayOutputStream(); PdfStamper stamper = PdfStamper.createSignature(reader, signedPdf, '\0'); // Creating the appearance PdfSignatureAppearance appearance = stamper.getSignatureAppearance(); appearance.setReason("Testing"); appearance.setLocation("Quito"); appearance.setVisibleSignature(new Rectangle(36, 748, 144, 780), 1, "sig"); // Creating the signature PrivateKeySignature pks = new PrivateKeySignature(pk, DigestAlgorithms.SHA1, null); OcspClient ocsp = new OcspClientBouncyCastle(); MakeSignature.signDetached(appearance, pks, chain, null, ocsp, tsaClient, BouncyCastleProvider.PROVIDER_NAME, 0, MakeSignature.CMS); return signedPdf.toByteArray(); } catch (DocumentException e) { throw new RuntimeException(e); } catch (GeneralSecurityException e) { throw new RuntimeException(e); } }