List of usage examples for com.itextpdf.text.pdf.security MakeSignature signDetached
public static void signDetached(PdfSignatureAppearance sap, ExternalDigest externalDigest, ExternalSignature externalSignature, Certificate[] chain, Collection<CrlClient> crlList, OcspClient ocspClient, TSAClient tsaClient, int estimatedSize, CryptoStandard sigtype) throws IOException, DocumentException, GeneralSecurityException
From source file:SigningProcess.java
public static String sign(String base64, HashMap map) { String base64string = null;/*from ww w. j a va2s . c o m*/ 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.isa.firma.FirmaPDFController.java
public ByteArrayOutputStream firmar(PDFFirma infoFirma, InputStream pdfbase64) throws AppletException { try {/*from w ww . ja va2s .co 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 {/* www . j ava 2s . 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 w ww . j ava 2 s.c o m*/ * * @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 w w w . j a va 2s.c om 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:cz.hobrasoft.pdfmu.operation.signature.OperationSignatureAdd.java
License:Open Source License
private static void sign(PdfSignatureAppearance sap, ExternalDigest externalDigest, ExternalSignature externalSignature, Certificate[] chain, TSAClient tsaClient, MakeSignature.CryptoStandard sigtype) throws OperationException { // TODO?: Set some of the following parameters more sensibly // Certificate Revocation List // digitalsignatures20130304.pdf : Section 3.2 Collection<CrlClient> crlList = null; // Online Certificate Status Protocol // digitalsignatures20130304.pdf : Section 3.2.4 OcspClient ocspClient = null;/*from w w w .j a v a 2 s .com*/ // digitalsignatures20130304.pdf : Section 3.5 // The value of 0 means "try a generous educated guess". // We need not change this unless we want to optimize the resulting PDF document size. int estimatedSize = 0; logger.info(String.format("Cryptographic standard (signature format): %s", sigtype)); try { MakeSignature.signDetached(sap, externalDigest, externalSignature, chain, crlList, ocspClient, tsaClient, estimatedSize, sigtype); } catch (ExceptionConverter ex) { Exception exInner = ex.getException(); if (exInner instanceof IOException) { if (exInner instanceof SSLHandshakeException) { Set<ExceptionMessagePattern> patterns = new HashSet<>(); // Untrusted patterns.add(new ExceptionMessagePattern(SIGNATURE_ADD_TSA_UNTRUSTED, "sun\\.security\\.validator\\.ValidatorException: PKIX path building failed: sun\\.security\\.provider\\.certpath\\.SunCertPathBuilderException: unable to find valid certification path to requested target", new ArrayList<String>())); // Bad certificate patterns.add(new ExceptionMessagePattern(SIGNATURE_ADD_TSA_BAD_CERTIFICATE, "Received fatal alert: bad_certificate", new ArrayList<String>())); // Handshake failure patterns.add(new ExceptionMessagePattern(SIGNATURE_ADD_TSA_HANDSHAKE_FAILURE, "Received fatal alert: handshake_failure", new ArrayList<String>())); OperationException oe = null; for (ExceptionMessagePattern p : patterns) { oe = p.getOperationException(exInner); if (oe != null) { break; } } if (oe == null) { ExceptionMessagePattern emp = new ExceptionMessagePattern(SIGNATURE_ADD_TSA_SSL_FATAL_ALERT, "Received fatal alert: (?<alert>.*)", Arrays.asList(new String[] { "alert" })); oe = emp.getOperationException(exInner); if (oe == null) { // Unknown exception oe = new OperationException(SIGNATURE_ADD_TSA_SSL_HANDSHAKE_EXCEPTION, exInner); } } assert oe != null; throw oe; } if (exInner instanceof SSLException) { ExceptionMessagePattern emp = new ExceptionMessagePattern(SSL_TRUSTSTORE_EMPTY, "java\\.lang\\.RuntimeException: Unexpected error: java\\.security\\.InvalidAlgorithmParameterException: the trustAnchors parameter must be non-empty", new ArrayList<String>()); OperationException oe = emp.getOperationException(exInner); if (oe != null) { throw oe; } throw new OperationException(SIGNATURE_ADD_FAIL, exInner); } if (exInner instanceof UnknownHostException || exInner instanceof FileNotFoundException) { String host = exInner.getMessage(); throw new OperationException(SIGNATURE_ADD_TSA_UNREACHABLE, exInner, new SimpleEntry<String, Object>("host", host)); } if (exInner instanceof SocketException) { ExceptionMessagePattern emp = new ExceptionMessagePattern(SSL_TRUSTSTORE_INCORRECT_TYPE, "java\\.security\\.NoSuchAlgorithmException: Error constructing implementation \\(algorithm: (?<algorithm>.*), provider: (?<provider>.*), class: (?<class>.*)\\)", Arrays.asList(new String[] { "algorithm", "provider", "class" })); OperationException oe = emp.getOperationException(exInner); if (oe != null) { throw oe; } throw new OperationException(SIGNATURE_ADD_FAIL, exInner); } Set<ExceptionMessagePattern> patterns = new HashSet<>(); // No username // May also be returned if the username and password are incorrect. patterns.add(new ExceptionMessagePattern(SIGNATURE_ADD_TSA_UNAUTHORIZED, "Server returned HTTP response code: 401 for URL: (?<url>.*)", Arrays.asList(new String[] { "url" }))); // Incorrect username or incorrect password patterns.add(new ExceptionMessagePattern(SIGNATURE_ADD_TSA_LOGIN_FAIL, "Invalid TSA '(?<url>.*)' response, code (?<code>\\d+)", Arrays.asList(new String[] { "url", "code" }))); patterns.add(new ExceptionMessagePattern(SIGNATURE_ADD_FAIL, "unknown tag (?<tag>\\d+) encountered", Arrays.asList(new String[] { "tag" }))); OperationException oe = null; for (ExceptionMessagePattern p : patterns) { oe = p.getOperationException(exInner); if (oe != null) { break; } } if (oe == null) { // Unknown exception oe = new OperationException(SIGNATURE_ADD_FAIL, exInner); } assert oe != null; throw oe; } throw new OperationException(SIGNATURE_ADD_FAIL, exInner); } catch (SignatureException ex) { throw new OperationException(SIGNATURE_ADD_SIGNATURE_EXCEPTION, ex); } catch (IOException | DocumentException | GeneralSecurityException ex) { throw new OperationException(SIGNATURE_ADD_FAIL, ex); } catch (NullPointerException ex) { // Invalid digest algorithm? throw new OperationException(SIGNATURE_ADD_FAIL, ex); } logger.info("Document successfully signed."); }
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 a 2 s . com*/ 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 {/*from w ww . 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 ww . j av a 2s . com*/ // 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); } }
From source file:EplanPrinter.PDFPrint.java
License:Open Source License
public String insertSignature(String src, String dest, String Keystore, String name, String password, int masterHeight, int masterWidth, int pageNum) throws GeneralSecurityException, IOException, DocumentException { float[] scalar = scale(1, 1, 120, 32, masterHeight, masterWidth, pageNum); float[] trans = translate(1, 1, r[pageNum - 1].getHeight(), r[pageNum - 1].getWidth(), masterHeight, masterWidth, pageNum);//from w w w. ja v a 2 s. c o m float[] f = commentTrans(1, 1, masterHeight, masterWidth, pageNum); float shift = 0; float pageChunk = r[pageNum - 1].getHeight() / 10; shift = r[pageNum - 1].getHeight() / 100; scalar[1] = (int) (pageChunk); scalar[0] = (int) (120 * pageChunk) / 32; trans[0] = (int) (0 + (pageChunk * widthScalar)); trans[1] = (int) (r[pageNum - 1].getHeight() - (pageChunk * heightScalar) - (shift * (heightScalar + 2))); heightScalar = heightScalar + 1; if (heightScalar == 8) { heightScalar = 0; widthScalar = widthScalar + 2; } /* Addition. ftorres - 7/22/2015 - Added to account for rotated pages * with the origin (0,0) not set to the bottom-left of the page. [1400] */ trans = translateRotation(trans[0], trans[1], pageNum); Rectangle cropBox = pds.getReader().getCropBox(1); Rectangle rectangle = new Rectangle(trans[0] + shift, trans[1] - scalar[1], trans[0] + shift + 120, trans[1] - scalar[1] + 32); BouncyCastleProvider provider = new BouncyCastleProvider(); Security.addProvider(provider); KeyStore ks = KeyStore.getInstance(KeyStore.getDefaultType()); ks.load(new FileInputStream(Keystore), password.toCharArray()); String alias = (String) ks.aliases().nextElement(); PrivateKey pk = (PrivateKey) ks.getKey(alias, password.toCharArray()); Certificate[] chain = ks.getCertificateChain(alias); // Creating the reader and the stamper PdfReader reader = new PdfReader(src); FileOutputStream os = new FileOutputStream(dest); PdfStamper stamper = PdfStamper.createSignature(reader, os, '\0'); // Creating the appearance PdfSignatureAppearance appearance = stamper.getSignatureAppearance(); appearance.setVisibleSignature(rectangle, 1, name); // Creating the signature ExternalSignature pks = new PrivateKeySignature(pk, "SHA-256", "BC"); ExternalDigest digest = new BouncyCastleDigest(); MakeSignature.signDetached(appearance, digest, pks, chain, null, null, null, 0, CryptoStandard.CMS); return ""; }