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:ec.rubrica.pdf.FirmadorPdf.java

License:Open Source License

public byte[] firmar(PrivateKey pk, X509Certificate certificado, String razon, String ubicacion)
        throws IOException {
    try {/* www.  ja  v a2  s . c  o m*/
        // Creating the reader and the stamper
        PdfReader reader = new PdfReader(pdf);

        ByteArrayOutputStream signedPdf = new ByteArrayOutputStream();
        PdfStamper stamper = PdfStamper.createSignature(reader, signedPdf, '\0');

        // Creating the appearance
        PdfSignatureAppearance appearance = stamper.getSignatureAppearance();
        appearance.setReason(razon);
        appearance.setLocation(ubicacion);

        Rectangle pageSize = reader.getPageSize(1);
        Rectangle position = new Rectangle(15, pageSize.getHeight() - 50, 250, pageSize.getHeight());
        appearance.setVisibleSignature(position, 1, "sig");

        // Creating the signature
        ExternalSignature pks = new PrivateKeySignature(pk, DigestAlgorithms.SHA1, null);

        Certificate[] chain = new Certificate[] { certificado };

        MakeSignature.signDetached(appearance, pks, chain, null, null, tsaClient,
                BouncyCastleProvider.PROVIDER_NAME, 0, MakeSignature.CMS);

        return signedPdf.toByteArray();
    } catch (DocumentException e) {
        throw new RuntimeException(e);
    } catch (GeneralSecurityException e) {
        throw new RuntimeException(e);
    }
}

From source file:ec.rubrica.pdf.FirmaPDF.java

License:Open Source License

public static byte[] firmar(byte[] pdf, PrivateKey pk, Certificate[] chain, TSAClient tsaClient)
        throws IOException {
    try {/*from  w w w. j ava2s  . c  om*/
        // Creating the reader and the stamper
        PdfReader reader = new PdfReader(pdf);
        ByteArrayOutputStream signedPdf = new ByteArrayOutputStream();
        PdfStamper stamper = PdfStamper.createSignature(reader, signedPdf, '\0');

        // Creating the appearance
        PdfSignatureAppearance appearance = stamper.getSignatureAppearance();
        appearance.setReason("Testing");
        appearance.setLocation("Quito");
        appearance.setVisibleSignature(new Rectangle(36, 748, 144, 780), 1, "sig");

        // Creating the signature
        PrivateKeySignature pks = new PrivateKeySignature(pk, DigestAlgorithms.SHA1, null);

        OcspClient ocsp = new OcspClientBouncyCastle();

        MakeSignature.signDetached(appearance, pks, chain, null, ocsp, tsaClient,
                BouncyCastleProvider.PROVIDER_NAME, 0, MakeSignature.CMS);

        return signedPdf.toByteArray();
    } catch (DocumentException e) {
        throw new RuntimeException(e);
    } catch (GeneralSecurityException e) {
        throw new RuntimeException(e);
    }
}

From source file:EplanPrinter.PDFPrint.java

License:Open Source License

public String insertSignature(String src, String dest, String Keystore, String name, String password,
        int masterHeight, int masterWidth, int pageNum)
        throws GeneralSecurityException, IOException, DocumentException {

    float[] scalar = scale(1, 1, 120, 32, masterHeight, masterWidth, pageNum);
    float[] trans = translate(1, 1, r[pageNum - 1].getHeight(), r[pageNum - 1].getWidth(), masterHeight,
            masterWidth, pageNum);//from   ww w .  j  a v a  2 s. c o m
    float[] f = commentTrans(1, 1, masterHeight, masterWidth, pageNum);

    float shift = 0;

    float pageChunk = r[pageNum - 1].getHeight() / 10;
    shift = r[pageNum - 1].getHeight() / 100;
    scalar[1] = (int) (pageChunk);
    scalar[0] = (int) (120 * pageChunk) / 32;
    trans[0] = (int) (0 + (pageChunk * widthScalar));
    trans[1] = (int) (r[pageNum - 1].getHeight() - (pageChunk * heightScalar) - (shift * (heightScalar + 2)));
    heightScalar = heightScalar + 1;
    if (heightScalar == 8) {
        heightScalar = 0;
        widthScalar = widthScalar + 2;
    }

    /* Addition. ftorres - 7/22/2015 - Added to account for rotated pages 
     *   with the origin (0,0) not set to the bottom-left of the page. [1400] */
    trans = translateRotation(trans[0], trans[1], pageNum);

    Rectangle cropBox = pds.getReader().getCropBox(1);
    Rectangle rectangle = new Rectangle(trans[0] + shift, trans[1] - scalar[1], trans[0] + shift + 120,
            trans[1] - scalar[1] + 32);
    BouncyCastleProvider provider = new BouncyCastleProvider();
    Security.addProvider(provider);
    KeyStore ks = KeyStore.getInstance(KeyStore.getDefaultType());
    ks.load(new FileInputStream(Keystore), password.toCharArray());
    String alias = (String) ks.aliases().nextElement();
    PrivateKey pk = (PrivateKey) ks.getKey(alias, password.toCharArray());
    Certificate[] chain = ks.getCertificateChain(alias);
    // Creating the reader and the stamper
    PdfReader reader = new PdfReader(src);
    FileOutputStream os = new FileOutputStream(dest);
    PdfStamper stamper = PdfStamper.createSignature(reader, os, '\0');
    // Creating the appearance
    PdfSignatureAppearance appearance = stamper.getSignatureAppearance();
    appearance.setVisibleSignature(rectangle, 1, name);
    // Creating the signature
    ExternalSignature pks = new PrivateKeySignature(pk, "SHA-256", "BC");
    ExternalDigest digest = new BouncyCastleDigest();
    MakeSignature.signDetached(appearance, digest, pks, chain, null, null, null, 0, CryptoStandard.CMS);

    return "";
}

From source file:gov.nih.nci.firebird.service.signing.DigitalSigningServiceBean.java

License:Open Source License

private PdfSignatureAppearance createPdfSigAppearance(PdfStamper stp,
        DigitalSigningAttributes signingAttributes, Certificate[] chain)
        throws IOException, BadElementException {
    PdfSignatureAppearance appearance = stp.getSignatureAppearance();
    appearance.setVisibleSignature(signingAttributes.getSigningFieldName());
    appearance.setReason(signingAttributes.getSigningReason());
    appearance.setSignDate(new GregorianCalendar());
    appearance.setCrypto(null, chain, null, null);
    appearance.setAcro6Layers(true);/*from  www.  jav a 2s. c  om*/
    appearance.setRenderingMode(PdfSignatureAppearance.RenderingMode.DESCRIPTION);

    return appearance;
}

From source file:net.pflaeging.PortableSigner.PDFSigner.java

License:Open Source License

/** Creates a new instance of DoSignPDF */
public void doSignPDF(String pdfInputFileName, String pdfOutputFileName, String pkcs12FileName, String password,
        Boolean signText, String signLanguage, String sigLogo, Boolean finalize, String sigComment,
        String signReason, String signLocation, Boolean noExtraPage, float verticalPos, float leftMargin,
        float rightMargin, Boolean signLastPage, byte[] ownerPassword) throws PDFSignerException {
    try {/*from  w ww .  jav  a 2 s . c  o  m*/
        //System.out.println("-> DoSignPDF <-");
        //System.out.println("Eingabedatei: " + pdfInputFileName);
        //System.out.println("Ausgabedatei: " + pdfOutputFileName);
        //System.out.println("Signaturdatei: " + pkcs12FileName);
        //System.out.println("Signaturblock?: " + signText);
        //System.out.println("Sprache der Blocks: " + signLanguage);
        //System.out.println("Signaturlogo: " + sigLogo);
        System.err.println("Position V:" + verticalPos + " L:" + leftMargin + " R:" + rightMargin);
        Rectangle signatureBlock;

        java.security.Security.insertProviderAt(new org.bouncycastle.jce.provider.BouncyCastleProvider(), 2);

        pkcs12 = new GetPKCS12(pkcs12FileName, password);

        PdfReader reader = null;
        try {
            //                System.out.println("Password:" + ownerPassword.toString());
            if (ownerPassword == null)
                reader = new PdfReader(pdfInputFileName);
            else
                reader = new PdfReader(pdfInputFileName, ownerPassword);
        } catch (IOException e) {

            /* MODIFY BY: Denis Torresan
             Main.setResult(
                java.util.ResourceBundle.getBundle(
                "net/pflaeging/PortableSigner/i18n").getString(
                "CouldNotBeOpened"),
                true,
                e.getLocalizedMessage());
             */

            throw new PDFSignerException(java.util.ResourceBundle.getBundle("net/pflaeging/PortableSigner/i18n")
                    .getString("CouldNotBeOpened"), true, e.getLocalizedMessage());
        }
        FileOutputStream fout = null;
        try {
            fout = new FileOutputStream(pdfOutputFileName);
        } catch (FileNotFoundException e) {

            /* MODIFY BY: Denis Torresan
             Main.setResult(
                java.util.ResourceBundle.getBundle("net/pflaeging/PortableSigner/i18n").getString("CouldNotBeWritten"),
                true,
                e.getLocalizedMessage());
             */

            throw new PDFSignerException(java.util.ResourceBundle.getBundle("net/pflaeging/PortableSigner/i18n")
                    .getString("CouldNotBeWritten"), true, e.getLocalizedMessage());

        }
        PdfStamper stp = null;
        try {
            Date datum = new Date(System.currentTimeMillis());

            int pages = reader.getNumberOfPages();

            Rectangle size = reader.getPageSize(pages);
            stp = PdfStamper.createSignature(reader, fout, '\0', null, true);
            HashMap<String, String> pdfInfo = reader.getInfo();
            // thanks to Markus Feisst
            String pdfInfoProducer = "";

            if (pdfInfo.get("Producer") != null) {
                pdfInfoProducer = pdfInfo.get("Producer").toString();
                pdfInfoProducer = pdfInfoProducer + " (signed with PortableSigner " + Version.release + ")";
            } else {
                pdfInfoProducer = "Unknown Producer (signed with PortableSigner " + Version.release + ")";
            }
            pdfInfo.put("Producer", pdfInfoProducer);
            //System.err.print("++ Producer:" + pdfInfo.get("Producer").toString());
            stp.setMoreInfo(pdfInfo);
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            XmpWriter xmp = new XmpWriter(baos, pdfInfo);
            xmp.close();
            stp.setXmpMetadata(baos.toByteArray());
            if (signText) {
                String greet, signator, datestr, ca, serial, special, note, urn, urnvalue;
                int specialcount = 0;
                int sigpage;
                int rightMarginPT, leftMarginPT;
                float verticalPositionPT;
                ResourceBundle block = ResourceBundle
                        .getBundle("net/pflaeging/PortableSigner/Signatureblock_" + signLanguage);
                greet = block.getString("greeting");
                signator = block.getString("signator");
                datestr = block.getString("date");
                ca = block.getString("issuer");
                serial = block.getString("serial");
                special = block.getString("special");
                note = block.getString("note");
                urn = block.getString("urn");
                urnvalue = block.getString("urnvalue");

                //sigcomment = block.getString(signLanguage + "-comment");
                // upper y
                float topy = size.getTop();
                System.err.println("Top: " + topy * ptToCm);
                // right x
                float rightx = size.getRight();
                System.err.println("Right: " + rightx * ptToCm);
                if (!noExtraPage) {
                    sigpage = pages + 1;
                    stp.insertPage(sigpage, size);
                    // 30pt left, 30pt right, 20pt from top
                    rightMarginPT = 30;
                    leftMarginPT = 30;
                    verticalPositionPT = topy - 20;
                } else {
                    if (signLastPage) {
                        sigpage = pages;
                    } else {
                        sigpage = 1;
                    }
                    System.err.println("Page: " + sigpage);
                    rightMarginPT = Math.round(rightMargin / ptToCm);
                    leftMarginPT = Math.round(leftMargin / ptToCm);
                    verticalPositionPT = topy - Math.round(verticalPos / ptToCm);
                }
                if (!GetPKCS12.atEgovOID.equals("")) {
                    specialcount = 1;
                }
                PdfContentByte content = stp.getOverContent(sigpage);

                float[] cellsize = new float[2];
                cellsize[0] = 100f;
                // rightx = width of page
                // 60 = 2x30 margins
                // cellsize[0] = description row
                // cellsize[1] = 0
                // 70 = logo width
                cellsize[1] = rightx - rightMarginPT - leftMarginPT - cellsize[0] - cellsize[1] - 70;

                // Pagetable = Greeting, signatureblock, comment
                // sigpagetable = outer table
                //      consist: greetingcell, signatureblock , commentcell
                PdfPTable signatureBlockCompleteTable = new PdfPTable(2);
                PdfPTable signatureTextTable = new PdfPTable(2);
                PdfPCell signatureBlockHeadingCell = new PdfPCell(
                        new Paragraph(new Chunk(greet, new Font(Font.FontFamily.HELVETICA, 12))));
                signatureBlockHeadingCell.setPaddingBottom(5);
                signatureBlockHeadingCell.setColspan(2);
                signatureBlockHeadingCell.setBorderWidth(0f);
                signatureBlockCompleteTable.addCell(signatureBlockHeadingCell);

                // inner table start
                // Line 1
                signatureTextTable.addCell(
                        new Paragraph(new Chunk(signator, new Font(Font.FontFamily.HELVETICA, 10, Font.BOLD))));
                signatureTextTable.addCell(
                        new Paragraph(new Chunk(GetPKCS12.subject, new Font(Font.FontFamily.COURIER, 10))));
                // Line 2
                signatureTextTable.addCell(
                        new Paragraph(new Chunk(datestr, new Font(Font.FontFamily.HELVETICA, 10, Font.BOLD))));
                signatureTextTable.addCell(
                        new Paragraph(new Chunk(datum.toString(), new Font(Font.FontFamily.COURIER, 10))));
                // Line 3
                signatureTextTable.addCell(
                        new Paragraph(new Chunk(ca, new Font(Font.FontFamily.HELVETICA, 10, Font.BOLD))));
                signatureTextTable.addCell(
                        new Paragraph(new Chunk(GetPKCS12.issuer, new Font(Font.FontFamily.COURIER, 10))));
                // Line 4
                signatureTextTable.addCell(
                        new Paragraph(new Chunk(serial, new Font(Font.FontFamily.HELVETICA, 10, Font.BOLD))));
                signatureTextTable.addCell(new Paragraph(
                        new Chunk(GetPKCS12.serial.toString(), new Font(Font.FontFamily.COURIER, 10))));
                // Line 5
                if (specialcount == 1) {
                    signatureTextTable.addCell(new Paragraph(
                            new Chunk(special, new Font(Font.FontFamily.HELVETICA, 10, Font.BOLD))));
                    signatureTextTable.addCell(new Paragraph(
                            new Chunk(GetPKCS12.atEgovOID, new Font(Font.FontFamily.COURIER, 10))));
                }
                signatureTextTable.addCell(
                        new Paragraph(new Chunk(urn, new Font(Font.FontFamily.HELVETICA, 10, Font.BOLD))));
                signatureTextTable
                        .addCell(new Paragraph(new Chunk(urnvalue, new Font(Font.FontFamily.COURIER, 10))));
                signatureTextTable.setTotalWidth(cellsize);
                System.err.println(
                        "signatureTextTable Width: " + cellsize[0] * ptToCm + " " + cellsize[1] * ptToCm);
                // inner table end

                signatureBlockCompleteTable.setHorizontalAlignment(PdfPTable.ALIGN_CENTER);
                Image logo;
                //                     System.out.println("Logo:" + sigLogo + ":");
                if (sigLogo == null || "".equals(sigLogo)) {
                    logo = Image.getInstance(
                            getClass().getResource("/net/pflaeging/PortableSigner/SignatureLogo.png"));
                } else {
                    logo = Image.getInstance(sigLogo);
                }

                PdfPCell logocell = new PdfPCell();
                logocell.setVerticalAlignment(PdfPCell.ALIGN_MIDDLE);
                logocell.setHorizontalAlignment(PdfPCell.ALIGN_CENTER);
                logocell.setImage(logo);
                signatureBlockCompleteTable.addCell(logocell);
                PdfPCell incell = new PdfPCell(signatureTextTable);
                incell.setBorderWidth(0f);
                signatureBlockCompleteTable.addCell(incell);
                PdfPCell commentcell = new PdfPCell(
                        new Paragraph(new Chunk(sigComment, new Font(Font.FontFamily.HELVETICA, 10))));
                PdfPCell notecell = new PdfPCell(
                        new Paragraph(new Chunk(note, new Font(Font.FontFamily.HELVETICA, 10, Font.BOLD))));
                //commentcell.setPaddingTop(10);
                //commentcell.setColspan(2);
                // commentcell.setBorderWidth(0f);
                if (!sigComment.equals("")) {
                    signatureBlockCompleteTable.addCell(notecell);
                    signatureBlockCompleteTable.addCell(commentcell);
                }
                float[] cells = { 70, cellsize[0] + cellsize[1] };
                signatureBlockCompleteTable.setTotalWidth(cells);
                System.err.println(
                        "signatureBlockCompleteTable Width: " + cells[0] * ptToCm + " " + cells[1] * ptToCm);
                signatureBlockCompleteTable.writeSelectedRows(0, 4 + specialcount, leftMarginPT,
                        verticalPositionPT, content);
                System.err.println(
                        "signatureBlockCompleteTable Position " + 30 * ptToCm + " " + (topy - 20) * ptToCm);
                signatureBlock = new Rectangle(30 + signatureBlockCompleteTable.getTotalWidth() - 20,
                        topy - 20 - 20, 30 + signatureBlockCompleteTable.getTotalWidth(), topy - 20);
                //                    //////
                //                    AcroFields af = reader.getAcroFields();
                //                    ArrayList names = af.getSignatureNames();
                //                    for (int k = 0; k < names.size(); ++k) {
                //                        String name = (String) names.get(k);
                //                        System.out.println("Signature name: " + name);
                //                        System.out.println("\tSignature covers whole document: " + af.signatureCoversWholeDocument(name));
                //                        System.out.println("\tDocument revision: " + af.getRevision(name) + " of " + af.getTotalRevisions());
                //                        PdfPKCS7 pk = af.verifySignature(name);
                //                        X509Certificate tempsigner = pk.getSigningCertificate();
                //                        Calendar cal = pk.getSignDate();
                //                        Certificate pkc[] = pk.getCertificates();
                //                        java.util.ResourceBundle tempoid =
                //                                java.util.ResourceBundle.getBundle("net/pflaeging/PortableSigner/SpecialOID");
                //                        String tmpEgovOID = "";
                //
                //                        for (Enumeration<String> o = tempoid.getKeys(); o.hasMoreElements();) {
                //                            String element = o.nextElement();
                //                            // System.out.println(element + ":" + oid.getString(element));
                //                            if (tempsigner.getNonCriticalExtensionOIDs().contains(element)) {
                //                                if (!tmpEgovOID.equals("")) {
                //                                    tmpEgovOID += ", ";
                //                                }
                //                                tmpEgovOID += tempoid.getString(element) + " (OID=" + element + ")";
                //                            }
                //                        }
                //                        //System.out.println("\tSigniert von: " + PdfPKCS7.getSubjectFields(pk.getSigningCertificate()));
                //                        System.out.println("\tSigniert von: " + tempsigner.getSubjectX500Principal().toString());
                //                        System.out.println("\tDatum: " + cal.getTime().toString());
                //                        System.out.println("\tAusgestellt von: " + tempsigner.getIssuerX500Principal().toString());
                //                        System.out.println("\tSeriennummer: " + tempsigner.getSerialNumber());
                //                        if (!tmpEgovOID.equals("")) {
                //                            System.out.println("\tVerwaltungseigenschaft: " + tmpEgovOID);
                //                        }
                //                        System.out.println("\n");
                //                        System.out.println("\tDocument modified: " + !pk.verify());
                ////                Object fails[] = PdfPKCS7.verifyCertificates(pkc, kall, null, cal);
                ////                if (fails == null) {
                ////                    System.out.println("\tCertificates verified against the KeyStore");
                ////                } else {
                ////                    System.out.println("\tCertificate failed: " + fails[1]);
                ////                }
                //                    }
                //
                //                //////
            } else {
                signatureBlock = new Rectangle(0, 0, 0, 0); // fake definition
            }
            PdfSignatureAppearance sap = stp.getSignatureAppearance();
            //                sap.setCrypto(GetPKCS12.privateKey, GetPKCS12.certificateChain, null,
            //                        PdfSignatureAppearance.WINCER_SIGNED );
            sap.setCrypto(GetPKCS12.privateKey, GetPKCS12.certificateChain, null, null);
            sap.setReason(signReason);
            sap.setLocation(signLocation);
            //                if (signText) {
            //                    sap.setVisibleSignature(signatureBlock,
            //                            pages + 1, "PortableSigner");
            //                }
            if (finalize) {
                sap.setCertificationLevel(PdfSignatureAppearance.CERTIFIED_NO_CHANGES_ALLOWED);
            } else {
                sap.setCertificationLevel(PdfSignatureAppearance.NOT_CERTIFIED);
            }
            stp.close();

            /* MODIFY BY: Denis Torresan
            Main.setResult(
              java.util.ResourceBundle.getBundle("net/pflaeging/PortableSigner/i18n").getString("IsGeneratedAndSigned"),
              false,
              "");
                */

        } catch (Exception e) {

            /* MODIFY BY: Denis Torresan
             Main.setResult(
                java.util.ResourceBundle.getBundle("net/pflaeging/PortableSigner/i18n").getString("ErrorWhileSigningFile"),
                true,
                e.getLocalizedMessage());
             */

            throw new PDFSignerException(java.util.ResourceBundle.getBundle("net/pflaeging/PortableSigner/i18n")
                    .getString("ErrorWhileSigningFile"), true, e.getLocalizedMessage());

        }
    } catch (KeyStoreException kse) {

        /* MODIFY BY: Denis Torresan
         Main.setResult(java.util.ResourceBundle.getBundle("net/pflaeging/PortableSigner/i18n").getString("ErrorCreatingKeystore"),
            true, kse.getLocalizedMessage());
         */

        throw new PDFSignerException(java.util.ResourceBundle.getBundle("net/pflaeging/PortableSigner/i18n")
                .getString("ErrorCreatingKeystore"), true, kse.getLocalizedMessage());

    }
}

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)
 *///from  w  ww.  ja v a 2 s.co m
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

/**
 * /*from w  w  w.ja va2 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 {/*from  w ww . java  2s.com*/
        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  a  v a2  s. co  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);//ww w.  j av 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;
}