Example usage for com.itextpdf.text.pdf PdfStamper getSignatureAppearance

List of usage examples for com.itextpdf.text.pdf PdfStamper getSignatureAppearance

Introduction

In this page you can find the example usage for com.itextpdf.text.pdf PdfStamper getSignatureAppearance.

Prototype

public PdfSignatureAppearance getSignatureAppearance() 

Source Link

Document

Gets the signing instance.

Usage

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 w  w  w  . j  a v a2s. c  om*/
        }
    }

    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  v  a 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);
    //   }//from w w  w. jav a  2 s .  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);
    }
}

From source file:pdf.Sign.java

License:Open Source License

private String doSignPdf(String pdfFile, String pdfFileSigned) {
    try {//  w w w.  j  a  v  a 2 s  .  co m
        PdfReader reader = new PdfReader(pdfFile);
        FileOutputStream fout = new FileOutputStream(pdfFileSigned);
        PdfStamper stp = PdfStamper.createSignature(reader, fout, '\0');
        PdfSignatureAppearance sap = stp.getSignatureAppearance();
        sap.setCrypto(null, _chain, null, PdfSignatureAppearance.SELF_SIGNED);
        sap.setReason("Declaratie unica");
        sap.setVisibleSignature(new Rectangle(500, 775, 600, 675), 1, null);
        sap.setExternalDigest(
                new byte[((RSAPublicKey) _certAlias._cert.getPublicKey()).getModulus().bitLength() / 8], null,
                "RSA");
        sap.preClose();
        byte[] content = streamToByteArray(sap.getRangeStream());
        Signature signature = Signature.getInstance("SHA1withRSA", _etpkcs11);
        signature.initSign((PrivateKey) _privateKey);
        signature.update(content);
        byte[] signatureBytes = signature.sign();
        // Self-Sign mode
        PdfPKCS7 sig = sap.getSigStandard().getSigner();
        sig.setExternalDigest(signatureBytes, null, "RSA");
        PdfDictionary dic = new PdfDictionary();
        dic.put(PdfName.CONTENTS, new PdfString(sig.getEncodedPKCS1()).setHexWriting(true));
        sap.close(dic);
    } catch (FileNotFoundException ex) {
        return ex.toString();
    } catch (ProviderException ex) {
        if (ex.getMessage().equals("Initialization failed")) {
            return ex.toString()
                    + " (Probabil aveti un alt tip de SmartCard conectat. Deconectati alte tipuri de SmartCarduri (daca exista) si folositi optiunea \"*autoDetect\")";
        } else if (ex.getMessage().equals("Error parsing configuration")) {
            return ex.toString()
                    + " (Calea catre driverul SmartCardului (care se afla inscrisa in fisierul .cfg corespunzator acestuia) contine unul din urmatoarele caractere: \"~()\". Solutie: Copiati continutul intregului folder in alta locatie si modificati corespunzator calea din fisierul .cfg. (vezi si http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=6581254))";
        }
        return ex.toString();
    } catch (NoSuchAlgorithmException ex) {
        return ex.toString();
    } catch (IOException ex) {
        return ex.toString();
    } catch (DocumentException ex) {
        return ex.toString();
    } catch (InvalidKeyException ex) {
        return ex.toString();
    } catch (SignatureException ex) {
        return ex.toString();
    } catch (Throwable ex) {
        return ex.toString();
    } finally {
        //wwww: eliminare key pt a putea introduce un nou pin
        //            String str = pin.getPassword().toString();
        //            pin.destroy();
        //            Security.removeProvider(_etpkcs11.getName());//"SunPKCS11-SmartCard");
        //wwww
    }
    return "";
}

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);//  www .j  a  va 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();
}