List of usage examples for com.itextpdf.text.pdf PdfSignatureAppearance getSignDate
public java.util.Calendar getSignDate()
From source file:SignPDF.java
License:Open Source License
public static void main(String args[]) { try {/* ww w .j a va2 s .c om*/ if (args.length != 1) { System.err.println("usage: $0 <pdf-file>"); System.exit(1); } src = args[0]; dest = src + ".temp"; rcname = System.getenv("SIGNPDFRC"); if (rcname == null || rcname.length() == 0) rcname = System.getenv("HOME") + "/.signpdf"; else System.out.println("using SIGNPDFRC=" + rcname); if (!getProperties()) createDefaultProperties(); KeyStore ks = KeyStore.getInstance(KeyStore.getDefaultType()); ks.load(new FileInputStream(path), keystore_password.toCharArray()); if (alias == null || alias.length() == 0) alias = (String) ks.aliases().nextElement(); Certificate[] chain = ks.getCertificateChain(alias); PrivateKey key = (PrivateKey) ks.getKey(alias, key_password.toCharArray()); X509Certificate cert = (X509Certificate) ks.getCertificate(alias); System.out.println("Signer ID serial " + cert.getSerialNumber()); System.out.println("Signer ID version " + cert.getVersion()); System.out.println("Signer ID issuer " + cert.getIssuerDN()); System.out.println("Signer ID not before " + cert.getNotBefore()); System.out.println("Signer ID not after " + cert.getNotAfter()); // show days valid long ticks_now = new Date().getTime(); long ticks_to = cert.getNotAfter().getTime(); long ticks_delta = (ticks_to - ticks_now) / TICKS_PER_DAY; System.out.println("Certificate will expire in " + ticks_delta + " days."); Signature s = Signature.getInstance("SHA1withRSA"); s.initVerify(ks.getCertificate(alias)); try { cert.checkValidity(); System.out.println("Validation check passed."); } catch (Exception e) { System.out.println("Certificate expired or invalid. Abroting."); System.exit(1); } PdfReader reader = new PdfReader(src); FileOutputStream os = new FileOutputStream(dest); //PdfStamper stamper = PdfStamper.createSignature(reader, os, '\0', null, false); PdfStamper stamper = PdfStamper.createSignature(reader, os, '\0'); stamper.setEncryption(true, null, null, PdfWriter.ALLOW_PRINTING | PdfWriter.ALLOW_SCREENREADERS | PdfWriter.ALLOW_COPY); HashMap<String, String> info = reader.getInfo(); info.put("Creator", "SingPDF " + version); stamper.setMoreInfo(info); PdfSignatureAppearance appearance = stamper.getSignatureAppearance(); appearance.setReason(reason); appearance.setLocation(location); appearance.setContact(contact); appearance.setCrypto(key, chain, null, PdfSignatureAppearance.WINCER_SIGNED); appearance.setCertificationLevel(PdfSignatureAppearance.CERTIFIED_NO_CHANGES_ALLOWED); /// ts + ocsp PdfSignature dic = new PdfSignature(PdfName.ADOBE_PPKLITE, new PdfName("adbe.pkcs7.detached")); dic.setReason(appearance.getReason()); dic.setLocation(appearance.getLocation()); dic.setContact(appearance.getContact()); dic.setDate(new PdfDate(appearance.getSignDate())); appearance.setCryptoDictionary(dic); // timestamping + ocsp if (tsa_url != null && tsa_url.length() > 0) { byte[] ocsp = null; TSAClient tsc = null; int contentEstimated = 15000; HashMap<PdfName, Integer> exc = new HashMap<PdfName, Integer>(); exc.put(PdfName.CONTENTS, new Integer(contentEstimated * 2 + 2)); appearance.preClose(exc); InputStream data = appearance.getRangeStream(); MessageDigest mdig = MessageDigest.getInstance("SHA1"); byte buf[] = new byte[8192]; int n; while ((n = data.read(buf)) > 0) { mdig.update(buf, 0, n); } if (root_cert != null && root_cert.length() > 0) { String url = PdfPKCS7.getOCSPURL((X509Certificate) chain[0]); CertificateFactory cf = CertificateFactory.getInstance("X509"); FileInputStream is = new FileInputStream(root_cert); X509Certificate root = (X509Certificate) cf.generateCertificate(is); ocsp = new OcspClientBouncyCastle().getEncoded((X509Certificate) chain[0], root, url); } byte hash[] = mdig.digest(); Calendar cal = Calendar.getInstance(); PdfPKCS7 sgn = new PdfPKCS7(key, chain, null, "SHA1", null, false); byte sh[] = sgn.getAuthenticatedAttributeBytes(hash, cal, ocsp); sgn.update(sh, 0, sh.length); if (tsa_url != null && tsa_url.length() > 0) { tsc = new TSAClientBouncyCastle(tsa_url, tsa_login, tsa_passw); byte[] encodedSig = sgn.getEncodedPKCS7(hash, cal, tsc, ocsp); if (contentEstimated + 2 < 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)); appearance.close(dic2); } } // ~timestamping + ocsp File mysrc = new File(src); mysrc.delete(); File mydest = new File(dest); mydest.renameTo(mysrc); System.exit(0); } catch (Exception e) { e.printStackTrace(); System.exit(1); } }
From source file:gov.nih.nci.firebird.service.signing.DigitalSigningServiceBean.java
License:Open Source License
private PdfSignature createSignatureDictionary(PdfSignatureAppearance appearance, String name, String signReason, String signLocation) { PdfSignature pdfSig = new PdfSignature(PdfName.ADOBE_PPKLITE, PdfName.ADBE_PKCS7_DETACHED); pdfSig.setDate(new PdfDate(appearance.getSignDate())); pdfSig.setName(name);/* ww w . j a v a2 s .co m*/ pdfSig.setReason(signReason); pdfSig.setLocation(signLocation); return pdfSig; }
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 ava 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); } }