List of usage examples for com.itextpdf.text.pdf PdfSignatureAppearance setCryptoDictionary
public void setCryptoDictionary(com.itextpdf.text.pdf.PdfDictionary cryptoDictionary)
From source file:SignPDF.java
License:Open Source License
public static void main(String args[]) { try {//from ww w. j a va 2 s.c o m 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: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(/*from w w w . jav a 2 s .c o m*/ 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); } // 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:gov.nih.nci.firebird.service.signing.DigitalSigningServiceBean.java
License:Open Source License
@Override // This is minimal parameter list for signing. public void signPdf(InputStream srcPdf, OutputStream destPdf, DigitalSigningAttributes signingAttributes) throws DigitalSigningException, IOException { try {/* w ww . j a v a2s. co m*/ KeyStore ks = KeyStore.getInstance(KEYSTORE_TYPE, BOUNCY_CASTLE_PROVIDER); ks.load(signingAttributes.getSigningKeyStore(), signingAttributes.getSigningPassword().toCharArray()); String alias = ks.aliases().nextElement(); PrivateKey key = (PrivateKey) ks.getKey(alias, null); Certificate[] chain = ks.getCertificateChain(alias); // reader and stamper PdfReader reader = new PdfReader(srcPdf); PdfStamper stamper = PdfStamper.createSignature(reader, destPdf, '\0'); PdfSignatureAppearance appearance = createPdfSigAppearance(stamper, signingAttributes, chain); // create signature dictionary PdfSignature dic = createSignatureDictionary(appearance, PdfPKCS7.getSubjectFields((X509Certificate) chain[0]).getField("CN"), signingAttributes.getSigningReason(), signingAttributes.getSigningLocation()); appearance.setCryptoDictionary(dic); // Reserve space for signature content. HashMap<PdfName, Integer> exc = new HashMap<PdfName, Integer>(); exc.put(PdfName.CONTENTS, Integer.valueOf(CONTENT_SIZE * 2 + 2)); appearance.preClose(exc); // Create hash of content. byte[] digest = createMessageDigest(appearance); // Creates signed hash. byte[] signedHash = generateSignedHash(key, chain, digest); // add signature contents. PdfDictionary dic2 = new PdfDictionary(); dic2.put(PdfName.CONTENTS, new PdfString(signedHash).setHexWriting(true)); appearance.close(dic2); } catch (GeneralSecurityException e) { throw new DigitalSigningException("Failed signing pdf.", e); } catch (DocumentException de) { throw new DigitalSigningException("Failed signing pdf.", de); } }
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); // }//from w w w . jav a 2s .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); // }//from w w w. j a va2s . c o 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); } }