List of usage examples for com.itextpdf.text.pdf PdfSignatureAppearance setLocation
public void setLocation(String location)
From source file:org.alfresco.extension.countersign.action.executer.PDFSignatureProviderActionExecuter.java
License:Open Source License
/** * @see org.alfresco.repo.action.executer.ActionExecuterAbstractBase#executeImpl(org.alfresco.service.cmr.repository.NodeRef, * org.alfresco.service.cmr.repository.NodeRef) *//* www . ja va 2 s .com*/ protected void executeImpl(Action ruleAction, NodeRef actionedUponNodeRef) { if (serviceRegistry.getNodeService().exists(actionedUponNodeRef) == false) { // node doesn't exist - can't do anything return; } String location = (String) ruleAction.getParameterValue(PARAM_LOCATION); String geolocation = (String) ruleAction.getParameterValue(PARAM_GEOLOCATION); String reason = (String) ruleAction.getParameterValue(PARAM_REASON); String position = (String) ruleAction.getParameterValue(PARAM_POSITION); String keyPassword = (String) ruleAction.getParameterValue(PARAM_KEY_PASSWORD); String signatureJson = (String) ruleAction.getParameterValue(PARAM_SIGNATURE_JSON); Boolean visible = (Boolean) ruleAction.getParameterValue(PARAM_VISIBLE); Boolean graphic = (Boolean) ruleAction.getParameterValue(PARAM_GRAPHIC); boolean useSignatureField = false; String user = AuthenticationUtil.getRunAsUser(); String positionType = "predefined"; String positionLoc = "center"; JSONObject box; int page = -1; // parse out the position JSON JSONObject positionObj = null; try { positionObj = (JSONObject) parser.parse(position); } catch (ParseException e) { logger.error("Could not parse position JSON from Share"); throw new AlfrescoRuntimeException("Could not parse position JSON from Share"); } // get the page page = Integer.parseInt(String.valueOf(positionObj.get("page"))); // get the positioning type positionType = String.valueOf(positionObj.get("type")); // get the position (field or predefined) positionLoc = String.valueOf(positionObj.get("position")); // get the box (if required) box = (JSONObject) positionObj.get("box"); int width = 350; int height = 75; File tempDir = null; // current date, used for both signing the PDF and creating the // associated signature object Calendar now = Calendar.getInstance(); try { // get the keystore, pk and cert chain SignatureProvider signatureProvider = signatureProviderFactory.getSignatureProvider(user); KeyStore keystore = signatureProvider.getUserKeyStore(keyPassword); PrivateKey key = (PrivateKey) keystore.getKey(alias, keyPassword.toCharArray()); Certificate[] chain = keystore.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()); OutputStream cos = serviceRegistry.getContentService() .getWriter(actionedUponNodeRef, ContentModel.PROP_CONTENT, true).getContentOutputStream(); PdfStamper stamp = PdfStamper.createSignature(reader, cos, '\0', file, true); PdfSignatureAppearance sap = stamp.getSignatureAppearance(); sap.setCrypto(key, chain, null, PdfSignatureAppearance.SELF_SIGNED); // set reason for signature, location of signer, and date sap.setReason(reason); sap.setLocation(location); sap.setSignDate(now); // get the image for the signature BufferedImage sigImage = SignatureToImage.convertJsonToImage(signatureJson, width, height); // save the signature image back to the signatureProvider signatureProvider.saveSignatureImage(sigImage, signatureJson); if (visible) { //if this is a graphic sig, set the graphic here if (graphic) { sap.setRenderingMode(PdfSignatureAppearance.RenderingMode.GRAPHIC); sap.setSignatureGraphic(Image.getInstance(sigImage, Color.WHITE)); } else { sap.setRenderingMode(PdfSignatureAppearance.RenderingMode.NAME_AND_DESCRIPTION); } // either insert the sig at a defined field or at a defined position / drawn loc if (positionType.equalsIgnoreCase(POSITION_TYPE_PREDEFINED)) { Rectangle pageRect = reader.getPageSizeWithRotation(page); sap.setVisibleSignature(positionBlock(positionLoc, pageRect, width, height), page, null); } else if (positionType.equalsIgnoreCase(POSITION_TYPE_DRAWN)) { Rectangle pageRect = reader.getPageSizeWithRotation(page); sap.setVisibleSignature(positionBlock(pageRect, box), page, null); } else { sap.setVisibleSignature(positionLoc); useSignatureField = true; } } // close the stamp, applying the changes to the PDF stamp.close(); reader.close(); cos.close(); //delete the temp file file.delete(); // apply the "signed" aspect serviceRegistry.getNodeService().addAspect(actionedUponNodeRef, CounterSignSignatureModel.ASPECT_SIGNED, new HashMap<QName, Serializable>()); // create a "signature" node and associate it with the signed doc addSignatureNodeAssociation(actionedUponNodeRef, location, reason, useSignatureField ? positionLoc : "none", now.getTime(), geolocation, page, positionLoc); } catch (IOException e) { throw new AlfrescoRuntimeException(e.getMessage(), e); } catch (ContentIOException e) { throw new AlfrescoRuntimeException(e.getMessage(), e); } catch (DocumentException e) { throw new AlfrescoRuntimeException(e.getMessage(), e); } catch (KeyStoreException e) { throw new AlfrescoRuntimeException(e.getMessage(), e); } catch (UnrecoverableKeyException e) { throw new AlfrescoRuntimeException(e.getMessage(), e); } catch (NoSuchAlgorithmException e) { throw new AlfrescoRuntimeException(e.getMessage(), e); } finally { if (tempDir != null) { try { tempDir.delete(); } catch (Exception ex) { throw new AlfrescoRuntimeException(ex.getMessage(), ex); } } } }
From source file:org.alfresco.extension.pdftoolkit.repo.action.executer.PDFSignatureActionExecuter.java
License:Apache License
/** * /* w w w .ja v a 2 s. c o m*/ * @param ruleAction * @param actionedUponNodeRef * @param actionedUponContentReader */ protected void doSignature(Action ruleAction, NodeRef actionedUponNodeRef, ContentReader actionedUponContentReader) { NodeRef privateKey = (NodeRef) ruleAction.getParameterValue(PARAM_PRIVATE_KEY); String location = (String) ruleAction.getParameterValue(PARAM_LOCATION); String position = (String) ruleAction.getParameterValue(PARAM_POSITION); 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); int height = getInteger(ruleAction.getParameterValue(PARAM_HEIGHT)); int width = getInteger(ruleAction.getParameterValue(PARAM_WIDTH)); int pageNumber = getInteger(ruleAction.getParameterValue(PARAM_PAGE)); // New keystore parameters String alias = (String) ruleAction.getParameterValue(PARAM_ALIAS); String storePassword = (String) ruleAction.getParameterValue(PARAM_STORE_PASSWORD); int locationX = getInteger(ruleAction.getParameterValue(PARAM_LOCATION_X)); int locationY = getInteger(ruleAction.getParameterValue(PARAM_LOCATION_Y)); 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 AlfrescoRuntimeException("Unknown key type " + keyType + " specified"); } // open the reader to the key and load it ContentReader keyReader = getReader(privateKey); 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)) { //create the signature rectangle using either the provided position or //the exact coordinates, if provided if (position != null && !position.trim().equalsIgnoreCase("")) { Rectangle pageRect = reader.getPageSizeWithRotation(pageNumber); sap.setVisibleSignature(positionSignature(position, pageRect, width, height), pageNumber, null); } else { sap.setVisibleSignature( new Rectangle(locationX, locationY, locationX + width, locationY - height), pageNumber, null); } } stamp.close(); //can't use BasePDFActionExecuter.getWriter here need the nodeRef of the destination NodeRef destinationNode = createDestinationNode(file.getName(), (NodeRef) ruleAction.getParameterValue(PARAM_DESTINATION_FOLDER), actionedUponNodeRef); writer = serviceRegistry.getContentService().getWriter(destinationNode, ContentModel.PROP_CONTENT, true); writer.setEncoding(actionedUponContentReader.getEncoding()); writer.setMimetype(FILE_MIMETYPE); writer.putContent(file); file.delete(); //if useAspect is true, store some additional info about the signature in the props if (useAspect) { serviceRegistry.getNodeService().addAspect(destinationNode, PDFToolkitModel.ASPECT_SIGNED, new HashMap<QName, Serializable>()); serviceRegistry.getNodeService().setProperty(destinationNode, PDFToolkitModel.PROP_REASON, reason); serviceRegistry.getNodeService().setProperty(destinationNode, PDFToolkitModel.PROP_LOCATION, location); serviceRegistry.getNodeService().setProperty(destinationNode, PDFToolkitModel.PROP_SIGNATUREDATE, new java.util.Date()); serviceRegistry.getNodeService().setProperty(destinationNode, PDFToolkitModel.PROP_SIGNEDBY, AuthenticationUtil.getRunAsUser()); } } catch (IOException e) { throw new AlfrescoRuntimeException(e.getMessage(), e); } catch (KeyStoreException e) { throw new AlfrescoRuntimeException(e.getMessage(), e); } catch (ContentIOException e) { throw new AlfrescoRuntimeException(e.getMessage(), e); } catch (NoSuchAlgorithmException e) { throw new AlfrescoRuntimeException(e.getMessage(), e); } catch (CertificateException e) { throw new AlfrescoRuntimeException(e.getMessage(), e); } catch (UnrecoverableKeyException e) { throw new AlfrescoRuntimeException(e.getMessage(), e); } catch (DocumentException e) { throw new AlfrescoRuntimeException(e.getMessage(), e); } finally { if (tempDir != null) { try { tempDir.delete(); } catch (Exception ex) { throw new AlfrescoRuntimeException(ex.getMessage(), ex); } } } }
From source file:org.dihedron.crypto.operations.sign.pdf.PDFSigner.java
License:Open Source License
@Override public void sign(InputStream input, OutputStream output) throws CryptoException { try {/*w w w .j a va 2 s. c om*/ PdfReader reader = new PdfReader(input); PdfStamper stamper = PdfStamper.createSignature(reader, output, '\0'); PdfSignatureAppearance appearance = stamper.getSignatureAppearance(); //appearance.setVisibleSignature("mySig"); appearance.setReason("Signed with Dihedron WebSign - Digital Signature for the Web ver. " + Crypto.valueOf(Traits.VERSION)); appearance.setLocation("Hidden Signature"); appearance.setCrypto((PrivateKey) key, chain, null, PdfSignatureAppearance.WINCER_SIGNED); if (mode == Mode.EXCLUSIVE) { appearance.setCertificationLevel(PdfSignatureAppearance.CERTIFIED_NO_CHANGES_ALLOWED); } // TODO: no graphic signature mode enabled yet // if (graphic) { // appearance.setAcro6Layers(true); // appearance.setSignatureGraphic(Image.getInstance(RESOURCE)); // appearance.setRenderingMode( // PdfSignatureAppearance.RenderingMode.GRAPHIC); // } stamper.close(); } catch (IOException e) { logger.error("I/O exception writing the PDF", e); throw new CryptoException("I/O exception writing the PDF", e); } catch (DocumentException e) { logger.error("invalid document: exception writing the PDF", e); throw new CryptoException("document exception writing the PDF", e); } }
From source file:org.opencps.pki.PdfSigner.java
License:Open Source License
/** * Compute digest hash//from w ww. j av a 2 s . c o m */ protected byte[] computeDigest(float llx, float lly, float urx, float ury) throws SignatureException { byte digestHash[] = null; int contentEstimated = 8192; try { PdfReader reader = new PdfReader(getOriginFilePath()); FileOutputStream os = new FileOutputStream(getTempFilePath()); PdfStamper stamper = PdfStamper.createSignature(reader, os, '\0'); PdfSignatureAppearance appearance = stamper.getSignatureAppearance(); signatureFieldName = appearance.getNewSigName(); TSAClient tsaClient = null; appearance.setCertificate(getCertificate()); String tsaUrl = CertificateUtil.getTSAURL(getCertificate()); if (tsaUrl != null) { tsaClient = new TSAClientBouncyCastle(tsaUrl); } if (tsaClient != null) { LtvTimestamp.timestamp(appearance, tsaClient, signatureFieldName); contentEstimated += 4096; } appearance.setSignDate(signDate); CertificateInfo certInfo = new CertificateInfo(getCertificate()); appearance.setLocation(certInfo.getOrganizationUnit()); appearance.setReason("Document is signed by " + certInfo.getCommonName()); appearance.setContact(certInfo.getCommonName()); if (!isVisible) { appearance.setVisibleSignature(new Rectangle(0, 0, 0, 0), 1, signatureFieldName); } else { if (signatureImage != null) { appearance.setSignatureGraphic(signatureImage.getImage()); appearance.setRenderingMode(PdfSignatureAppearance.RenderingMode.GRAPHIC); } else { appearance.setLayer2Text(certInfo.getCommonName()); } appearance.setVisibleSignature(new Rectangle(llx, lly, urx, ury), 1, signatureFieldName); } ExternalSignatureContainer external = new ExternalBlankSignatureContainer(PdfName.ADOBE_PPKLITE, PdfName.ADBE_PKCS7_DETACHED); MakeSignature.signExternalContainer(appearance, external, contentEstimated); digestHash = DigestAlgorithms.digest(appearance.getRangeStream(), digest.getMessageDigest(getHashAlgorithm().toString())); reader.close(); os.close(); } catch (Exception e) { throw new SignatureException(e.getMessage(), e); } return digestHash; }
From source file:org.roda.common.certification.PDFSignatureUtils.java
public static Path runDigitalSignatureSign(Path input, String keystore, String alias, String password, String reason, String location, String contact) throws IOException, GeneralSecurityException, DocumentException { Security.addProvider(new BouncyCastleProvider()); Path signedPDF = Files.createTempFile("signed", ".pdf"); KeyStore ks = KeyStore.getInstance(KeyStore.getDefaultType()); InputStream is = new FileInputStream(keystore); ks.load(is, password.toCharArray()); PrivateKey pk = (PrivateKey) ks.getKey(alias, password.toCharArray()); Certificate[] chain = ks.getCertificateChain(alias); IOUtils.closeQuietly(is);/*from w w w . ja va2 s .c o m*/ PdfReader reader = new PdfReader(input.toString()); FileOutputStream os = new FileOutputStream(signedPDF.toFile()); PdfStamper stamper = PdfStamper.createSignature(reader, os, '\0'); PdfSignatureAppearance appearance = stamper.getSignatureAppearance(); appearance.setReason(reason); appearance.setLocation(location); appearance.setContact(contact); appearance.setVisibleSignature(new Rectangle(36, 748, 144, 780), 1, "RODASignature"); ExternalDigest digest = new BouncyCastleDigest(); ExternalSignature signature = new PrivateKeySignature(pk, DigestAlgorithms.SHA256, "BC"); MakeSignature.signDetached(appearance, digest, signature, chain, null, null, null, 0, null); IOUtils.closeQuietly(os); reader.close(); return signedPDF; }
From source file:org.roda.core.plugins.plugins.characterization.PDFSignatureUtils.java
public static Path runDigitalSignatureSign(Path input, String keystore, String alias, String password, String reason, String location, String contact) throws IOException, GeneralSecurityException, DocumentException { Security.addProvider(new BouncyCastleProvider()); Path signedPDF = Files.createTempFile("signed", ".pdf"); KeyStore ks = KeyStore.getInstance(KeyStore.getDefaultType()); try (InputStream is = new FileInputStream(keystore)) { ks.load(is, password.toCharArray()); PrivateKey pk = (PrivateKey) ks.getKey(alias, password.toCharArray()); Certificate[] chain = ks.getCertificateChain(alias); try (FileOutputStream os = new FileOutputStream(signedPDF.toFile())) { PdfReader reader = new PdfReader(input.toString()); PdfStamper stamper = PdfStamper.createSignature(reader, os, '\0'); PdfSignatureAppearance appearance = stamper.getSignatureAppearance(); appearance.setReason(reason); appearance.setLocation(location); appearance.setContact(contact); appearance.setVisibleSignature(new Rectangle(36, 748, 144, 780), 1, "RODASignature"); ExternalDigest digest = new BouncyCastleDigest(); ExternalSignature signature = new PrivateKeySignature(pk, DigestAlgorithms.SHA256, "BC"); MakeSignature.signDetached(appearance, digest, signature, chain, null, null, null, 0, null); reader.close();//from www . j a va2 s. co m } } return signedPDF; }
From source file:org.sinekartads.core.pdf.PDFTools.java
License:Open Source License
public static FinalizedSignature<SignatureType.SignCategory, SignDisposition.PDF, SecurityLevel.VerifyResult, PDFSignatureInfo> sign( SignedSignature<SignatureType.SignCategory, SignDisposition.PDF, SecurityLevel.VerifyResult, PDFSignatureInfo> signedSignature, // X509Certificate certificate, InputStream is, OutputStream os) throws SignatureException { //// signAndMark(doc, certificate, is, os, null, null, null, null, null); // signAndMark(signatureInfo, certificate, is, os, null, null, null); // }// w w w . j a va 2 s .c o m // // public static void signAndMark(PDFSignatureInfo doc, // X509Certificate certificate, InputStream is, OutputStream os, // String tsaUrl, String tsaUser, String tsaPassword) { //// signAndMark(doc, certificate, is, os, tsaUrl, tsaUser, tsaPassword, null, null); //// } //// //// public static void signAndMark(DigitalSignatureDocument doc, //// X509Certificate certificate, InputStream is, OutputStream os, //// String tsaUrl, String tsaUser, String tsaPassword, Collection<CrlClient> crlList, OcspClient ocspClient) { try { PDFSignatureInfo signature = (PDFSignatureInfo) signedSignature; TSAClient tsaClient = null; TsRequestInfo tsRequest = signature.getTsRequest(); if (tsRequest != null && StringUtils.isNotBlank(tsRequest.getTsUrl())) { tsaClient = new TSAClientBouncyCastle(tsRequest.getTsUrl(), tsRequest.getTsUsername(), tsRequest.getTsPassword()); } // if (tsaUrl!=null) { // tsaClient = new TSAClientBouncyCastle(tsaUrl, tsaUser, tsaPassword); // } int estimatedSize = 0; CryptoStandard sigtype = CryptoStandard.CMS; // creo il reader del pdf PdfReader reader = new PdfReader(is); // creo lo stamper (se il pdf e' gia' firmato, controfirma, // altrimenti firma PdfStamper stamper = null; if (isPdfSigned(reader)) { if (tracer.isDebugEnabled()) tracer.debug("document already signed, i will apply another sign"); stamper = PdfStamper.createSignature(reader, os, '\0', null, true); } else { if (tracer.isDebugEnabled()) tracer.debug("document never signed before, this is first"); stamper = PdfStamper.createSignature(reader, os, '\0'); } // questo e' il certificato su cui lavorare Certificate[] chain = signature.getRawX509Certificates(); // Certificate[] chain = new Certificate[1]; // chain[0] = certificate; // creo la signature apparence PdfSignatureAppearance sap = stamper.getSignatureAppearance(); ExternalDigest externalDigest = new BouncyCastleDigest(); // inizio codice copiato da MakeSignature // Collection<byte[]> crlBytes = null; // int i = 0; // while (crlBytes == null && i < chain.length) // crlBytes = MakeSignature.processCrl(chain[i++], crlList); if (estimatedSize == 0) { estimatedSize = 8192; // if (crlBytes != null) { // for (byte[] element : crlBytes) { // estimatedSize += element.length + 10; // } // } // if (ocspClient != null) estimatedSize += 4192; // if (tsaClient != null) estimatedSize += 4192; } sap.setCertificate(chain[0]); sap.setReason(signature.getReason()); sap.setLocation(signature.getLocation()); Calendar cal = Calendar.getInstance(); cal.setTime(signature.getSigningTime()); sap.setSignDate(cal); sap.getStamper().setUnicodeModDate(signature.getUnicodeModDate()); sap.getStamper().setFileId(signature.getFileId()); PdfSignature dic = new PdfSignature(PdfName.ADOBE_PPKLITE, PdfName.ADBE_PKCS7_DETACHED); dic.setReason(sap.getReason()); dic.setLocation(sap.getLocation()); dic.setContact(sap.getContact()); dic.setDate(new PdfDate(sap.getSignDate())); // time-stamp will over-rule this sap.setCryptoDictionary(dic); HashMap<PdfName, Integer> exc = new HashMap<PdfName, Integer>(); exc.put(PdfName.CONTENTS, new Integer(estimatedSize * 2 + 2)); sap.preClose(exc); String hashAlgorithm = signature.getDigestAlgorithm().getName(); PdfPKCS7 sgn = new PdfPKCS7(null, chain, hashAlgorithm, BouncyCastleProvider.PROVIDER_NAME, externalDigest, false); InputStream data = sap.getRangeStream(); byte hash[] = DigestAlgorithms.digest(data, externalDigest.getMessageDigest(hashAlgorithm)); // byte[] ocsp = null; // if (chain.length >= 2 && ocspClient != null) { // ocsp = ocspClient.getEncoded((X509Certificate) chain[0], (X509Certificate) chain[1], null); // } sgn.setExternalDigest(signature.getDigitalSignature(), null, "RSA"); // byte[] encodedSig = sgn.getEncodedPKCS7(hash, _getSignDate(doc.getSignDate()), tsaClient, ocsp, crlBytes, sigtype); byte[] encodedSig = sgn.getEncodedPKCS7(hash, cal, tsaClient, null, null, sigtype); if (estimatedSize + 2 < encodedSig.length) throw new IOException("Not enough space"); ASN1EncodableVector extraDataVectorEncoding = new ASN1EncodableVector(); // extraDataVectorEncoding.add(new DERObjectIdentifier("1.2.840.114283")); // encoding attribute extraDataVectorEncoding.add(new DERGeneralString("115.105.110.101.107.97.114.116.97")); // applico la firma al PDF byte[] extraDataVectorEncodingBytes = new DERSequence(new DERSequence(extraDataVectorEncoding)) .getEncoded(); byte[] paddedSig = new byte[estimatedSize]; System.arraycopy(encodedSig, 0, paddedSig, 0, encodedSig.length); System.arraycopy(extraDataVectorEncodingBytes, 0, paddedSig, encodedSig.length, extraDataVectorEncodingBytes.length); // encoding attribute PdfDictionary dic2 = new PdfDictionary(); dic2.put(PdfName.CONTENTS, new PdfString(paddedSig).setHexWriting(true)); sap.close(dic2); // this should be already done, but ... // closing streams try { is.close(); } catch (IOException e) { tracer.error("error on input stream", e); } try { os.flush(); } catch (IOException e) { tracer.error("error on output stream", e); } try { os.close(); } catch (IOException e) { tracer.error("error on output stream", e); } return signature.finalizeSignature(); // } catch (MarkFailedException e) { // throw e; } catch (Exception e) { tracer.error("Unable to sign PDF.", e); throw new SignatureException("Unable to sign PDF.", e); } }
From source file:org.sinekartads.core.pdf.PDFTools.java
License:Open Source License
public static DigestSignature<SignatureType.SignCategory, SignDisposition.PDF, SecurityLevel.VerifyResult, PDFSignatureInfo> calculateFingerPrint( ChainSignature<SignatureType.SignCategory, SignDisposition.PDF, SecurityLevel.VerifyResult, PDFSignatureInfo> chainSignature, // X509Certificate certificate, InputStream is) throws SignatureException { // calculateFingerPrint(doc, certificate, is, null, null, null, null, null); // }// ww w. ja va 2 s . co m // // public static void calculateFingerPrint(DigitalSignatureDocument doc, // X509Certificate certificate, InputStream is, Collection<CrlClient> crlList, OcspClient ocspClient, String tsaUrl, String tsaUser, String tsaPassword) { try { // TSAClient tsaClient=null; // // if (tsaUrl!=null) { // tsaClient = new SinekartaTSAClient(tsaUrl, tsaUser, tsaPassword); // } // int estimatedSize = 0; CryptoStandard sigtype = CryptoStandard.CMS; // FIXME qui c'era CMS PDFSignatureInfo signature = (PDFSignatureInfo) chainSignature; // creo il reader del pdf PdfReader reader = new PdfReader(is); // creo lo stamper (se il pdf e' gia' firmato, controfirma, // altrimenti firma PdfStamper stamper = null; if (isPdfSigned(reader)) { if (tracer.isDebugEnabled()) tracer.debug("calculating finger print for document already signed"); stamper = PdfStamper.createSignature(reader, null, '\0', null, true); } else { if (tracer.isDebugEnabled()) tracer.debug("calculating finger print for document never signed before"); stamper = PdfStamper.createSignature(reader, null, '\0'); } // questo e' il certificato su cui lavorare Certificate[] chain = signature.getRawX509Certificates(); // Certificate[] chain = new Certificate[1]; // chain[0] = certificate; // creo la signature apparence PdfSignatureAppearance sap = stamper.getSignatureAppearance(); ExternalDigest externalDigest = new BouncyCastleDigest(); // inizio codice copiato da MakeSignature // Collection<byte[]> crlBytes = null; // int i = 0; // while (crlBytes == null && i < chain.length) // crlBytes = MakeSignature.processCrl(chain[i++], crlList); if (estimatedSize == 0) { estimatedSize = 8192; // if (crlBytes != null) { // for (byte[] element : crlBytes) { // estimatedSize += element.length + 10; // } // } // if (ocspClient != null) estimatedSize += 4192; // if (tsaClient != null) estimatedSize += 4192; } Calendar now = Calendar.getInstance(); PdfDate date = new PdfDate(now); sap.setSignDate(now); signature.setSigningTime(now.getTime()); signature.setUnicodeModDate(date.toUnicodeString()); sap.setCertificate(chain[0]); sap.setReason(signature.getReason()); sap.setLocation(signature.getLocation()); PdfSignature dic = new PdfSignature(PdfName.ADOBE_PPKLITE, PdfName.ADBE_PKCS7_DETACHED); dic.setReason(sap.getReason()); dic.setLocation(sap.getLocation()); dic.setContact(sap.getContact()); dic.setDate(date); // time-stamp will over-rule this sap.setCryptoDictionary(dic); HashMap<PdfName, Integer> exc = new HashMap<PdfName, Integer>(); exc.put(PdfName.CONTENTS, new Integer(estimatedSize * 2 + 2)); sap.preClose(exc); String hashAlgorithm = signature.getDigestAlgorithm().getName(); PdfPKCS7 sgn = new PdfPKCS7(null, chain, hashAlgorithm, BouncyCastleProvider.PROVIDER_NAME, externalDigest, false); // String hashAlgorithm = Constants.SHA256; // PdfPKCS7 sgn = new PdfPKCS7(null, chain, hashAlgorithm, Constants.BC, externalDigest, false); InputStream data = sap.getRangeStream(); byte hash[] = DigestAlgorithms.digest(data, externalDigest.getMessageDigest(hashAlgorithm)); // byte[] ocsp = null; // if (chain.length >= 2 && ocspClient != null) { // ocsp = ocspClient.getEncoded((X509Certificate) chain[0], (X509Certificate) chain[1], null); // } // byte[] authenticatedAttributeBytes = sgn.getAuthenticatedAttributeBytes(hash, now, ocsp, crlBytes, sigtype); byte[] authenticatedAttributeBytes = sgn.getAuthenticatedAttributeBytes(hash, now, null, null, sigtype); // calcolo dell'impronta MessageDigest digester = MessageDigest.getInstance(signature.getDigestAlgorithm().getName()); byte[] fingerPrint = digester.digest(authenticatedAttributeBytes); // byte[] fingerPrint = Util.digest256(authenticatedAttributeBytes); signature.setAuthenticatedAttributeBytes(authenticatedAttributeBytes); signature.setFileId(sap.getStamper().getFileId()); // signature.setFileIDByteContent(TextUtil.byteToHex(sap.getStamper().getFileID().getBytes())); signature.setUnicodeModDate(sap.getStamper().getUnicodeModDate()); // signature.setModDateUnicodeString(sap.getStamper().getModDate().toUnicodeString()); signature.setSigningTime(now.getTime()); // SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmssSSSZ"); // signature.setSignDate(sdf.format(now.getTime())); // this should be already done, but ... // closing streams try { is.close(); } catch (IOException e) { tracer.error("error on input stream", e); } return signature.toDigestSignature(DigestInfo.getInstance(signature.getDigestAlgorithm(), fingerPrint)); } catch (Exception e) { tracer.error("Unable to calculate finger print of PDF.", e); // throw new PDFException("Unable calculate finger print of PDF.", e); throw new SignatureException("Unable calculate finger print of PDF.", e); } }
From source file:signpdfitext5.SignPdfItext5.java
public static void signPdf() throws IOException, DocumentException, KeyStoreException, NoSuchAlgorithmException, CertificateException, UnrecoverableKeyException, GeneralSecurityException { //Se agrega bouncyCastle al provider de java, si no se realiza, arroja un error Provider p = new BouncyCastleProvider(); Security.addProvider(p);//from w ww . java 2 s . c o m //Se instancia un keystore de tipo pkcs12 para leer el contenedor p12 o pfx KeyStore ks = KeyStore.getInstance("pkcs12"); //Se entrega la ruta y la clave del p12 o pfx ks.load(new FileInputStream(fContenedorp12.getAbsolutePath()), Contenedorp12clave.toCharArray()); //Se obtiene el nombre del certificado String alias = (String) ks.aliases().nextElement(); //Se obtiene la llave privada PrivateKey pk = (PrivateKey) ks.getKey(alias, Contenedorp12clave.toCharArray()); //Se obtiene la cadena de certificados en base al nombre del certificado Certificate[] chain = ks.getCertificateChain(alias); //Se indica el origen del pdf a firmar PdfReader reader = new PdfReader(fpdfOrigen.getAbsolutePath()); //Se indica el destino del pdf firmado PdfStamper stamper = PdfStamper.createSignature(reader, new FileOutputStream(fpdfDestino.getAbsolutePath()), '\0'); //Se indican alguno detalles de la forma en que se firmara PdfSignatureAppearance appearance = stamper.getSignatureAppearance(); appearance.setReason("It's personal."); appearance.setLocation("Foobar"); // Se entrega la llave privada del certificado, el algoritmo de firma y el provider usado (bouncycastle) ExternalSignature es = new PrivateKeySignature(pk, "SHA-256", "BC"); ExternalDigest digest = new BouncyCastleDigest(); //Se genera la firma y se almacena el pdf como se indico en las lineas anteriores MakeSignature.signDetached(appearance, digest, es, chain, null, null, null, 0, CryptoStandard.CMS); //Se cierran las instancias para liberar espacio stamper.close(); reader.close(); }