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

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

Introduction

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

Prototype

public static PdfStamper createSignature(final PdfReader reader, final OutputStream os, final char pdfVersion)
        throws DocumentException, IOException 

Source Link

Document

Applies a digital signature to a document.

Usage

From source file:org.alfresco.extension.pdftoolkit.repo.action.executer.PDFSignatureActionExecuter.java

License:Apache License

/**
 * /*from   ww w.j a  v a  2  s .  c  om*/
 * @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 {/*from   ww  w.j  av a  2s. 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 w  w . jav  a2 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 .j a v a  2  s .co 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();// ww  w  .  j  av a2 s  . c o  m
        }
    }

    return signedPDF;
}

From source file:pdf.Sign.java

License:Open Source License

private String doSignPdf(String pdfFile, String pdfFileSigned) {
    try {/*w  w  w.jav a 2  s  . c om*/
        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);// w  ww  . java2 s.c  om

    //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();
}