Example usage for com.itextpdf.text.pdf PdfSignatureAppearance setLocation

List of usage examples for com.itextpdf.text.pdf PdfSignatureAppearance setLocation

Introduction

In this page you can find the example usage for com.itextpdf.text.pdf PdfSignatureAppearance setLocation.

Prototype

public void setLocation(String location) 

Source Link

Document

Sets the signing location.

Usage

From source file:SignPDF.java

License:Open Source License

public static void main(String args[]) {
    try {//from   w  w  w.  ja  v a 2s  .co  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:com.bluexml.side.Framework.alfresco.signature.repo.action.executer.PDFSignatureActionExecuter.java

License:Open Source License

/**
 * //from  ww  w  .  j a  va 2s.c  om
 * @param ruleAction
 * @param actionedUponNodeRef
 * @param actionedUponContentReader
 * @throws Exception 
 */
protected void doSignature(Action ruleAction, NodeRef actionedUponNodeRef,
        ContentReader actionedUponContentReader) throws Exception {

    NodeRef privateKey = (NodeRef) ruleAction.getParameterValue(PARAM_PRIVATE_KEY);
    String location = (String) ruleAction.getParameterValue(PARAM_LOCATION);
    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);
    String signedName = (String) ruleAction.getParameterValue(PARAM_SIGNED_NAME);
    int height = Integer.parseInt((String) ruleAction.getParameterValue(PARAM_HEIGHT));
    int width = Integer.parseInt((String) ruleAction.getParameterValue(PARAM_WIDTH));

    // New keystore parameters
    String alias = (String) ruleAction.getParameterValue(PARAM_ALIAS);
    String storePassword = (String) ruleAction.getParameterValue(PARAM_STORE_PASSWORD);

    // Ugly and verbose, but fault-tolerant
    String locationXStr = (String) ruleAction.getParameterValue(PARAM_LOCATION_X);
    String locationYStr = (String) ruleAction.getParameterValue(PARAM_LOCATION_Y);
    int locationX = 0;
    int locationY = 0;
    try {
        locationX = locationXStr != null ? Integer.parseInt(locationXStr) : 0;
    } catch (NumberFormatException e) {
        locationX = 0;
    }
    try {
        locationY = locationXStr != null ? Integer.parseInt(locationYStr) : 0;
    } catch (NumberFormatException e) {
        locationY = 0;
    }

    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 Exception("Unknown key type " + keyType + " specified");
        }

        // open the reader to the key and load it
        ContentReader keyReader = serviceRegistry.getContentService().getReader(privateKey,
                ContentModel.PROP_CONTENT);
        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)) {
            sap.setVisibleSignature(new Rectangle(locationX + width, locationY - height, locationX, locationY),
                    1, null);
        }

        stamp.close();

        String[] splitedFilename = file.getName().split("\\.");
        String name = "-" + signedName + "." + splitedFilename[splitedFilename.length - 1];
        for (int i = splitedFilename.length - 2; i >= 0; i--) {
            if (name.equals("-" + signedName + "." + splitedFilename[splitedFilename.length - 1])) {
                name = splitedFilename[i] + name;
            } else {
                name = splitedFilename[i] + "." + name;
            }
        }

        writer = getWriter(name, (NodeRef) ruleAction.getParameterValue(PARAM_DESTINATION_FOLDER));
        writer.setEncoding(actionedUponContentReader.getEncoding());
        writer.setMimetype(FILE_MIMETYPE);
        writer.putContent(file);

        file.delete();
    } catch (Exception e) {
        throw e;
    } finally {
        if (tempDir != null) {
            try {
                tempDir.delete();
            } catch (Exception ex) {
            }
        }
    }
}

From source file:com.vectorprint.report.itext.style.stylers.DocumentSettings.java

License:Open Source License

/**
 * adds a visible signature of 200 / 100 at top left of the first page of the pdf with "verify origin" as reason, the
 * localhost name as location. Uses MakeSignature.signDetached(psa, as, pks, certificateChain, null, null, null, 0,
 * MakeSignature.CryptoStandard.CMS)//from   w  w  w  .j  a  va2 s  .  c o  m
 *
 * @see #loadKeyStore(char[])
 * @see #getKey(java.security.KeyStore, java.lang.String, char[]) }
 * @param psa
 * @throws KeyStoreException
 * @throws NoSuchAlgorithmException
 * @throws UnrecoverableKeyException
 * @throws VectorPrintException
 */
@Override
public void configureVisualSignature(PdfSignatureAppearance psa)
        throws KeyStoreException, NoSuchAlgorithmException, UnrecoverableKeyException, VectorPrintException {
    psa.setReason("verify origin");
    try {
        psa.setLocation(InetAddress.getLocalHost().getHostName());
    } catch (UnknownHostException ex) {
        log.log(Level.WARNING, "unable to set location for pdf signature", ex);
    }

    char[] pw = getValue(KEYSTORE_PASSWORD, char[].class);
    char[] clone = pw.clone();
    KeyStore ks = loadKeyStore(pw);

    PrivateKey key = getKey(ks, (String) ks.aliases().nextElement(), clone);
    Certificate[] certificateChain = ks.getCertificateChain((String) ks.aliases().nextElement());

    PrivateKeySignature pks = new PrivateKeySignature(key, getValue(DIGESTPARAM, DIGESTALGORITHM.class).name(),
            "BC");
    ExternalDigest as = new BouncyCastleDigest();

    psa.setVisibleSignature(new Rectangle(0, getHeight() - 100, 200, getHeight()), 1, "signature");
    try {
        MakeSignature.signDetached(psa, as, pks, certificateChain, null, null, null, 0,
                MakeSignature.CryptoStandard.CMS);
    } catch (IOException | DocumentException | GeneralSecurityException ex) {
        throw new VectorPrintException(ex);
    }
}

From source file:controller.CCInstance.java

License:Open Source License

public final boolean signPdf(final String pdfPath, final String destination, final CCSignatureSettings settings,
        final SignatureListener sl) throws CertificateException, IOException, DocumentException,
        KeyStoreException, SignatureFailedException, FileNotFoundException, NoSuchAlgorithmException,
        InvalidAlgorithmParameterException {
    PrivateKey pk;/* w  w  w.  ja  va2s . com*/

    final PdfReader reader = new PdfReader(pdfPath);
    pk = getPrivateKeyFromAlias(settings.getCcAlias().getAlias());

    if (getCertificationLevel(pdfPath) == PdfSignatureAppearance.CERTIFIED_NO_CHANGES_ALLOWED) {
        String message = Bundle.getBundle().getString("fileDoesNotAllowChanges");
        if (sl != null) {
            sl.onSignatureComplete(pdfPath, false, message);
        }
        throw new SignatureFailedException(message);
    }

    if (reader.getNumberOfPages() - 1 < settings.getPageNumber()) {
        settings.setPageNumber(reader.getNumberOfPages() - 1);
    }

    if (null == pk) {
        String message = Bundle.getBundle().getString("noSmartcardFound");
        if (sl != null) {
            sl.onSignatureComplete(pdfPath, false, message);
        }
        throw new CertificateException(message);
    }

    if (null == pkcs11ks.getCertificateChain(settings.getCcAlias().getAlias())) {
        String message = Bundle.getBundle().getString("certificateNullChain");
        if (sl != null) {
            sl.onSignatureComplete(pdfPath, false, message);
        }
        throw new CertificateException(message);
    }
    final ArrayList<Certificate> embeddedCertificateChain = settings.getCcAlias().getCertificateChain();
    final Certificate owner = embeddedCertificateChain.get(0);
    final Certificate lastCert = embeddedCertificateChain.get(embeddedCertificateChain.size() - 1);

    if (null == owner) {
        String message = Bundle.getBundle().getString("certificateNameUnknown");
        if (sl != null) {
            sl.onSignatureComplete(pdfPath, false, message);
        }
        throw new CertificateException(message);
    }

    final X509Certificate X509C = ((X509Certificate) lastCert);
    final Calendar now = Calendar.getInstance();
    final Certificate[] filledMissingCertsFromChainInTrustedKeystore = getCompleteTrustedCertificateChain(
            X509C);

    final Certificate[] fullCertificateChain;
    if (filledMissingCertsFromChainInTrustedKeystore.length < 2) {
        fullCertificateChain = new Certificate[embeddedCertificateChain.size()];
        for (int i = 0; i < embeddedCertificateChain.size(); i++) {
            fullCertificateChain[i] = embeddedCertificateChain.get(i);
        }
    } else {
        fullCertificateChain = new Certificate[embeddedCertificateChain.size()
                + filledMissingCertsFromChainInTrustedKeystore.length - 1];
        int i = 0;
        for (i = 0; i < embeddedCertificateChain.size(); i++) {
            fullCertificateChain[i] = embeddedCertificateChain.get(i);
        }
        for (int f = 1; f < filledMissingCertsFromChainInTrustedKeystore.length; f++, i++) {
            fullCertificateChain[i] = filledMissingCertsFromChainInTrustedKeystore[f];
        }
    }

    // Leitor e Stamper
    FileOutputStream os = null;
    try {
        os = new FileOutputStream(destination);
    } catch (FileNotFoundException e) {
        String message = Bundle.getBundle().getString("outputFileError");
        if (sl != null) {
            sl.onSignatureComplete(pdfPath, false, message);
        }
        throw new IOException(message);
    }

    // Aparncia da Assinatura
    final char pdfVersion;
    switch (Settings.getSettings().getPdfVersion()) {
    case "/1.2":
        pdfVersion = PdfWriter.VERSION_1_2;
        break;
    case "/1.3":
        pdfVersion = PdfWriter.VERSION_1_3;
        break;
    case "/1.4":
        pdfVersion = PdfWriter.VERSION_1_4;
        break;
    case "/1.5":
        pdfVersion = PdfWriter.VERSION_1_5;
        break;
    case "/1.6":
        pdfVersion = PdfWriter.VERSION_1_6;
        break;
    case "/1.7":
        pdfVersion = PdfWriter.VERSION_1_7;
        break;
    default:
        pdfVersion = PdfWriter.VERSION_1_7;
    }

    final PdfStamper stamper = (getNumberOfSignatures(pdfPath) == 0
            ? PdfStamper.createSignature(reader, os, pdfVersion)
            : PdfStamper.createSignature(reader, os, pdfVersion, null, true));

    final PdfSignatureAppearance appearance = stamper.getSignatureAppearance();
    appearance.setSignDate(now);
    appearance.setReason(settings.getReason());
    appearance.setLocation(settings.getLocation());
    appearance.setCertificationLevel(settings.getCertificationLevel());
    appearance.setSignatureCreator(SIGNATURE_CREATOR);
    appearance.setCertificate(owner);

    final String fieldName = settings.getPrefix() + " " + (1 + getNumberOfSignatures(pdfPath));
    if (settings.isVisibleSignature()) {
        appearance.setVisibleSignature(settings.getPositionOnDocument(), settings.getPageNumber() + 1,
                fieldName);
        appearance.setRenderingMode(PdfSignatureAppearance.RenderingMode.DESCRIPTION);
        if (null != settings.getAppearance().getImageLocation()) {
            appearance.setImage(Image.getInstance(settings.getAppearance().getImageLocation()));
        }

        com.itextpdf.text.Font font = new com.itextpdf.text.Font(FontFactory
                .getFont(settings.getAppearance().getFontLocation(), BaseFont.IDENTITY_H, BaseFont.EMBEDDED, 0)
                .getBaseFont());

        font.setColor(new BaseColor(settings.getAppearance().getFontColor().getRGB()));
        if (settings.getAppearance().isBold() && settings.getAppearance().isItalic()) {
            font.setStyle(Font.BOLD + Font.ITALIC);
        } else if (settings.getAppearance().isBold()) {
            font.setStyle(Font.BOLD);
        } else if (settings.getAppearance().isItalic()) {
            font.setStyle(Font.ITALIC);
        } else {
            font.setStyle(Font.PLAIN);
        }

        appearance.setLayer2Font(font);
        String text = "";
        if (settings.getAppearance().isShowName()) {
            if (!settings.getCcAlias().getName().isEmpty()) {
                text += settings.getCcAlias().getName() + "\n";
            }
        }
        if (settings.getAppearance().isShowReason()) {
            if (!settings.getReason().isEmpty()) {
                text += settings.getReason() + "\n";
            }
        }
        if (settings.getAppearance().isShowLocation()) {
            if (!settings.getLocation().isEmpty()) {
                text += settings.getLocation() + "\n";
            }
        }
        if (settings.getAppearance().isShowDate()) {
            DateFormat df = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
            SimpleDateFormat sdf = new SimpleDateFormat("Z");
            text += df.format(now.getTime()) + " " + sdf.format(now.getTime()) + "\n";
        }
        if (!settings.getText().isEmpty()) {
            text += settings.getText();
        }

        PdfTemplate layer2 = appearance.getLayer(2);
        Rectangle rect = settings.getPositionOnDocument();
        Rectangle sr = new Rectangle(rect.getWidth(), rect.getHeight());
        float size = ColumnText.fitText(font, text, sr, 1024, PdfWriter.RUN_DIRECTION_DEFAULT);
        ColumnText ct = new ColumnText(layer2);
        ct.setRunDirection(PdfWriter.RUN_DIRECTION_DEFAULT);
        ct.setAlignment(Element.ALIGN_MIDDLE);
        int align;
        switch (settings.getAppearance().getAlign()) {
        case 0:
            align = Element.ALIGN_LEFT;
            break;
        case 1:
            align = Element.ALIGN_CENTER;
            break;
        case 2:
            align = Element.ALIGN_RIGHT;
            break;
        default:
            align = Element.ALIGN_LEFT;
        }

        ct.setSimpleColumn(new Phrase(text, font), sr.getLeft(), sr.getBottom(), sr.getRight(), sr.getTop(),
                size, align);
        ct.go();
    } else {
        appearance.setVisibleSignature(new Rectangle(0, 0, 0, 0), 1, fieldName);
    }

    // CRL <- Pesado!
    final ArrayList<CrlClient> crlList = null;

    // OCSP
    OcspClient ocspClient = new OcspClientBouncyCastle();

    // TimeStamp
    TSAClient tsaClient = null;
    if (settings.isTimestamp()) {
        tsaClient = new TSAClientBouncyCastle(settings.getTimestampServer(), null, null);
    }

    final String hashAlg = getHashAlgorithm(X509C.getSigAlgName());

    final ExternalSignature es = new PrivateKeySignature(pk, hashAlg, pkcs11Provider.getName());
    final ExternalDigest digest = new ProviderDigest(pkcs11Provider.getName());

    try {
        MakeSignature.signDetached(appearance, digest, es, fullCertificateChain, crlList, ocspClient, tsaClient,
                0, MakeSignature.CryptoStandard.CMS);
        if (sl != null) {
            sl.onSignatureComplete(pdfPath, true, "");
        }
        return true;
    } catch (Exception e) {
        os.flush();
        os.close();
        new File(destination).delete();
        if ("sun.security.pkcs11.wrapper.PKCS11Exception: CKR_FUNCTION_CANCELED".equals(e.getMessage())) {
            throw new SignatureFailedException(Bundle.getBundle().getString("userCanceled"));
        } else if ("sun.security.pkcs11.wrapper.PKCS11Exception: CKR_GENERAL_ERROR".equals(e.getMessage())) {
            throw new SignatureFailedException(Bundle.getBundle().getString("noPermissions"));
        } else if (e instanceof ExceptionConverter) {
            String message = Bundle.getBundle().getString("timestampFailed");
            if (sl != null) {
                sl.onSignatureComplete(pdfPath, false, message);
            }
            throw new SignatureFailedException(message);
        } else {
            if (sl != null) {
                sl.onSignatureComplete(pdfPath, false, Bundle.getBundle().getString("unknownErrorLog"));
            }
            controller.Logger.getLogger().addEntry(e);
        }
        return false;
    }
}

From source file:cz.hobrasoft.pdfmu.operation.signature.SignatureAppearanceParameters.java

License:Open Source License

public void configureSignatureAppearance(PdfSignatureAppearance sap) {
    assert sap != null;
    // Configure signature metadata
    if (reason != null) {
        logger.info(String.format("Reason: %s", reason));
        sap.setReason(reason);/*  w w w  .  j ava2  s .co  m*/
    }
    if (location != null) {
        logger.info(String.format("Location: %s", location));
        sap.setLocation(location);
    }
    if (contact != null) {
        logger.info(String.format("Contact: %s", contact));
        sap.setContact(contact);
    }
    if (signDate != null) {
        // `setSignDate(null)` crashes
        logger.info(String.format("Date: %s", signDate));
        sap.setSignDate(signDate);
    }
    sap.setCertificationLevel(certificationLevel);

    // TODO?: Set signer's name
    // digitalsignatures20130304.pdf : Code sample 2.12
}

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   ww w  . j  a  v a  2 s .c  om
                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:de.sign.SignMain.java

License:Open Source License

public void sign() throws DocumentException, IOException, GeneralSecurityException {

    PdfReader reader = new PdfReader(this.orgFile);
    OutputStream os = new FileOutputStream(this.orgFile.replace(".pdf", "SIGN.pdf"));
    PdfStamper stamper = PdfStamper.createSignature(reader, os, '\0');

    // Create appearance
    PdfSignatureAppearance appearance = stamper.getSignatureAppearance();
    Rectangle cropBox = reader.getCropBox(1);
    float width = 50;
    float height = 50;
    Rectangle rectangle = new Rectangle(cropBox.getRight(width) - 20, cropBox.getTop(height) - 20,
            cropBox.getRight() - 20, cropBox.getTop() - 20);
    appearance.setVisibleSignature(rectangle, 1, "sig");
    appearance.setLocation(getHostname());
    appearance.setReason("Evidence of document integrity");
    appearance.setCertificationLevel(1); // 1 = CERTIFIED_NO_CHANGES_ALLOWED
    appearance.setAcro6Layers(false);/*from w w  w .j  a  va 2  s . com*/
    appearance.setLayer2Text("");

    //Sign
    Security.addProvider(new BouncyCastleProvider());
    TSAClient tsc = new TSAClientBouncyCastle(this.tsa_URL);
    ExternalDigest digest = new BouncyCastleDigest();
    ExternalSignature signature = new PrivateKeySignature(getPrivateKey(), "SHA-1", "BC");
    MakeSignature.signDetached(appearance, digest, signature, getCertificateChain(), null, null, tsc, 0,
            CryptoStandard.CMS);
}

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 {//from  w  w w.j  a  va2 s  .  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(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 {// ww w  . j  a v  a2 s . 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: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 {//  w  w w . java 2 s. co 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());

    }
}