Example usage for com.lowagie.text.pdf PdfName REASON

List of usage examples for com.lowagie.text.pdf PdfName REASON

Introduction

In this page you can find the example usage for com.lowagie.text.pdf PdfName REASON.

Prototype

PdfName REASON

To view the source code for com.lowagie.text.pdf PdfName REASON.

Click Source Link

Document

A name

Usage

From source file:androidGLUESigner.pdf.PDFSigExtractor.java

License:Open Source License

/**
 * extracts the signature field for previewing.
 * @throws IOException /*from w  w w. j av  a  2 s  . c o  m*/
 */
public static ArrayList<SignatureInfo> getSignatureInfo(String inputPath) {
    PdfReader reader;
    try {
        reader = new PdfReader(inputPath);
    } catch (IOException e) {
        return new ArrayList<SignatureInfo>();
    }
    AcroFields af = reader.getAcroFields();
    ArrayList names = af.getSignatureNames();
    ArrayList<SignatureInfo> signatures = new ArrayList<SignatureInfo>();
    // For every signature :
    for (int k = 0; k < names.size(); ++k) {
        String name = (String) names.get(k);
        SignatureInfo sigInfo = new SignatureInfo();
        // get coordinates
        float[] position = af.getFieldPositions(name);
        // page number
        float page = position[0];
        // left
        float llx = position[1];
        // bottom
        float lly = position[2];
        // right
        float urx = position[3];
        // top
        float ury = position[4];

        // get size of pdf page
        Rectangle size = reader.getPageSize((int) page);
        float height = size.getHeight();
        // subtract height to translate to Android canvas coordinate system
        lly = height - lly;
        ury = height - ury;
        float ulx = llx;

        // create a Rectangle from obtained signature field coordinates
        Rect sigRect = new Rect((int) ulx, (int) ury, (int) urx, (int) lly);
        sigInfo.setGraphicRect(sigRect, 1.0f);
        // obtain additional information like reason, location, ...
        PdfDictionary sig = af.getSignatureDictionary(name);
        sigInfo.setSignatureName(sig.getAsString(PdfName.NAME).toString());
        sigInfo.setSignatureLocation(sig.getAsString(PdfName.LOCATION).toString());
        sigInfo.setSignatureReason(sig.getAsString(PdfName.REASON).toString());
        sigInfo.setSignatureType(SignatureType.NORMAL);
        sigInfo.setPageNumber((int) page);
        // add new signature information to signatures
        signatures.add(sigInfo);
    }
    return signatures;
}

From source file:org.opensignature.opensignpdf.PDFSigner.java

License:Open Source License

/**
 * Allow you to sign a PDF File with a PKCS11 session opened.
 * /*from www  .j  ava  2  s  .  c o m*/
 * @param mySign
 * @param session
 * @param pdfFiles
 * @param suffix
 * @param reason
 * @param signatureVisibility
 * @param cal
 * @throws OpenSignatureException
 * @throws TokenException
 * @throws IOException
 * @throws CertificateException
 * @throws OpenSignatureException
 * @throws KeyStoreException
 * @throws UnrecoverableKeyException
 * @throws NoSuchAlgorithmException
 * @throws FileNotFoundException
 * @throws DocumentException
 * @throws NoSuchAlgorithmException
 * @throws ExceptionConverter
 */
public void signPDFwithKS(KeyStore ks, String alias, String pwd, File[] pdfFiles, String suffix, String reason,
        boolean signatureVisibility, Calendar cal)
        throws OpenSignatureException, KeyStoreException, NoSuchAlgorithmException, UnrecoverableKeyException {

    if (pdfFiles == null || ks == null) {
        throw new OpenSignatureException("Invalid parameters.");
    }

    // -- System's date by default 
    if (cal == null) {
        cal = Calendar.getInstance();
    }

    logger.info("[signPDFwithKS.in]:: " + Arrays.asList(new Object[] { "<ks>", alias, Arrays.asList(pdfFiles),
            suffix, reason, Boolean.valueOf(signatureVisibility) }));

    if (alias == null) {

        Enumeration aliases = ks.aliases();
        while (aliases.hasMoreElements()) {
            String alTmp = (String) aliases.nextElement();
            logger.debug("[signPDFwithKS]:: alTmp: " + alTmp);

            X509Certificate x509certificate = (X509Certificate) ks.getCertificate(alTmp);
            boolean[] keyUsage = x509certificate.getKeyUsage();
            if (keyUsage != null && (keyUsage[1] || keyUsage[0])) {
                alias = alTmp;
                break;
            }

        }
    }

    logger.debug("\n\n[signPDFwithKS]:: alias: " + alias + "\n\n");
    PrivateKey key = (PrivateKey) ks.getKey(alias, pwd.toCharArray());
    Certificate[] certs = ks.getCertificateChain(alias);

    for (int i = 0; i < pdfFiles.length; i++) {

        logger.info("[signPDFwithKS]:: Signing the file: " + pdfFiles[i].getAbsolutePath());

        try {

            // -- Check the access to the PDF
            if (!pdfFiles[i].exists() || !pdfFiles[i].canRead()) {
                throw new FileNotFoundException(
                        "The file '" + pdfFiles[i].getAbsolutePath() + "' doesn't exist.");
            }

            byte signatureBytes[] = new byte[128];

            // -- Creating the OutputStream overwritting the file if it exists
            // previously
            File fOut = FileUtils.addSuffix(pdfFiles[i], suffix, true);
            FileOutputStream fos = new FileOutputStream(fOut);
            BufferedOutputStream bos = new BufferedOutputStream(fos);

            // -- Creating the reader
            PdfReader reader = createPDFReader(pdfFiles[i]);

            PdfStamperOSP stamper;

            if ("countersigner".equals(typeSignatureSelected)) {
                stamper = PdfStamperOSP.createSignature(reader, bos, '\0', null, true);
            } else {
                stamper = PdfStamperOSP.createSignature(reader, bos, '\0');
            }

            PdfSignatureAppearanceOSP sap = stamper.getSignatureAppearance();
            sap.setCrypto(null, certs, null, PdfSignatureAppearance.WINCER_SIGNED);
            sap.setReason(reason);

            if (signatureVisibility) {
                if ("countersigner".equals(typeSignatureSelected)) {
                    sap.setCertified(0);
                    sap.setVisibleSignature(fieldName);
                } else {
                    sap.setCertified(2);
                    if (!"".equals(fieldName)) {
                        sap.setVisibleSignature(fieldName);
                    } else {
                        sap.setVisibleSignature(new com.lowagie.text.Rectangle(llx, lly, urx, ury), 1, null);
                    }
                }

            }

            sap.setExternalDigest(new byte[128], new byte[20], "RSA");

            PdfDictionary dic = new PdfDictionary();
            dic.put(PdfName.FT, PdfName.SIG);
            dic.put(PdfName.FILTER, new PdfName("Adobe.PPKLite"));
            dic.put(PdfName.SUBFILTER, new PdfName("adbe.pkcs7.detached"));
            if (cal != null) {
                dic.put(PdfName.M, new PdfDate(cal));
            } else {
                dic.put(PdfName.M, new PdfNull());
            }
            dic.put(PdfName.NAME,
                    new PdfString(PdfPKCS7.getSubjectFields((X509Certificate) certs[0]).getField("CN")));
            dic.put(PdfName.REASON, new PdfString(reason));

            sap.setCryptoDictionary(dic);

            HashMap exc = new HashMap();
            exc.put(PdfName.CONTENTS, new Integer(0x5002));
            sap.preClose(exc);

            byte[] content = IOUtils.streamToByteArray(sap.getRangeStream());
            //SHA256, alias CMSSignedDataGenerator.DIGEST_SHA256,
            //        alias NISTObjectIdentifiers.id_sha256.getId(),
            //        alias "2.16.840.1.101.3.4.2.1"
            byte[] hash = MessageDigest.getInstance("2.16.840.1.101.3.4.2.1", "BC").digest(content);

            // costruzione degli authenticated attributes
            ASN1EncodableVector signedAttributes = buildSignedAttributes(hash, cal);
            byte[] bytesForSecondHash = IOUtils.toByteArray(new DERSet(signedAttributes));

            // -- Signature generated with the private key of the KS
            Signature signature = Signature.getInstance("SHA256withRSA");
            signature.initSign(key);
            signature.update(bytesForSecondHash);
            signatureBytes = signature.sign();

            byte[] encodedPkcs7 = null;
            try {

                // Create the set of Hash algorithms
                DERConstructedSet digestAlgorithms = new DERConstructedSet();

                // Creo manualmente la sequenza di digest algos
                ASN1EncodableVector algos = new ASN1EncodableVector();
                //algos.add(new DERObjectIdentifier("1.3.14.3.2.26")); // SHA1
                //SHA-256
                algos.add(new DERObjectIdentifier("2.16.840.1.101.3.4.2.1"));
                algos.add(new DERNull());
                digestAlgorithms.addObject(new DERSequence(algos));

                // Create the contentInfo.
                ASN1EncodableVector ev = new ASN1EncodableVector();
                ev.add(new DERObjectIdentifier("1.2.840.113549.1.7.1")); // PKCS7SignedData

                DERSequence contentinfo = new DERSequence(ev);

                // Get all the certificates
                //
                ASN1EncodableVector v = new ASN1EncodableVector();
                for (int c = 0; c < certs.length; c++) {
                    ASN1InputStream tempstream = new ASN1InputStream(
                            new ByteArrayInputStream(certs[c].getEncoded()));
                    v.add(tempstream.readObject());
                }

                DERSet dercertificates = new DERSet(v);

                // Create signerinfo structure.
                //
                ASN1EncodableVector signerinfo = new ASN1EncodableVector();

                // Add the signerInfo version
                //
                signerinfo.add(new DERInteger(1));

                v = new ASN1EncodableVector();
                v.add(CertUtil.getIssuer((X509Certificate) certs[0]));
                v.add(new DERInteger(((X509Certificate) certs[0]).getSerialNumber()));
                signerinfo.add(new DERSequence(v));

                // Add the digestAlgorithm
                v = new ASN1EncodableVector();
                //v.add(new DERObjectIdentifier("1.3.14.3.2.26")); // SHA1
                //SHA-256
                v.add(new DERObjectIdentifier("1.2.840.113549.1.7.1"));
                v.add(new DERNull());
                signerinfo.add(new DERSequence(v));

                // add the authenticated attribute if present
                signerinfo.add(new DERTaggedObject(false, 0, new DERSet(signedAttributes)));

                // Add the digestEncryptionAlgorithm
                v = new ASN1EncodableVector();
                v.add(new DERObjectIdentifier("1.2.840.113549.1.1.1"));// RSA
                v.add(new DERNull());
                signerinfo.add(new DERSequence(v));

                // Add the encrypted digest
                signerinfo.add(new DEROctetString(signatureBytes));

                // Add unsigned attributes (timestamp)
                if (serverTimestamp != null && !"".equals(serverTimestamp.toString())) {
                    byte[] timestampHash = MessageDigest.getInstance("SHA-256").digest(signatureBytes);
                    ASN1EncodableVector unsignedAttributes = buildUnsignedAttributes(timestampHash,
                            serverTimestamp, usernameTimestamp, passwordTimestamp);
                    if (unsignedAttributes != null) {
                        signerinfo.add(new DERTaggedObject(false, 1, new DERSet(unsignedAttributes)));
                    }
                }

                // Finally build the body out of all the components above
                ASN1EncodableVector body = new ASN1EncodableVector();
                body.add(new DERInteger(1)); // pkcs7 version, always 1
                body.add(digestAlgorithms);
                body.add(contentinfo);
                body.add(new DERTaggedObject(false, 0, dercertificates));

                // Only allow one signerInfo
                body.add(new DERSet(new DERSequence(signerinfo)));

                // Now we have the body, wrap it in it's PKCS7Signed shell
                // and return it
                //
                ASN1EncodableVector whole = new ASN1EncodableVector();
                whole.add(new DERObjectIdentifier("1.2.840.113549.1.7.2"));// PKCS7_SIGNED_DATA
                whole.add(new DERTaggedObject(0, new DERSequence(body)));

                encodedPkcs7 = IOUtils.toByteArray(new DERSequence(whole));

            } catch (Exception e) {
                throw new ExceptionConverter(e);
            }

            PdfDictionary dic2 = new PdfDictionary();

            byte out[] = new byte[0x5000 / 2];
            System.arraycopy(encodedPkcs7, 0, out, 0, encodedPkcs7.length);

            dic2.put(PdfName.CONTENTS, new PdfString(out).setHexWriting(true));
            sap.close(dic2);

            bos.close();
            fos.close();

        } catch (Exception e) {
            logger.warn("[signPDFwithKS]:: ", e);
        }

    }

    logger.info("[signPDFwithKS.out]:: ");

}

From source file:org.opensignature.opensignpdf.PDFSigner.java

License:Open Source License

/**
 * @param mySign//from ww w .j a v  a  2 s .  c o  m
 * @param session
 * @param reason
 * @param signCertKeyObject
 * @param certs
 * @param stamper
 * @throws IOException
 * @throws DocumentException
 * @throws NoSuchAlgorithmException
 * @throws TokenException
 * @throws ExceptionConverter
* @throws NoSuchProviderException 
 */
private void createSignatureAppearance(MyPkcs11 mySign, Session session, String reason, Key signCertKeyObject,
        X509Certificate[] certs, PdfStamperOSP stamper, boolean signatureVisible, Calendar cal)
        throws IOException, DocumentException, NoSuchAlgorithmException, TokenException, ExceptionConverter,
        NoSuchProviderException {

    logger.info("[createSignatureAppearance.in]:: ");

    byte[] signatureBytes = new byte[128];

    PdfSignatureAppearanceOSP sap = stamper.getSignatureAppearance();

    sap.setCrypto(null, certs, null, PdfSignatureAppearance.WINCER_SIGNED);
    sap.setReason(reason);

    if (signatureVisible) {
        if ("countersigner".equals(typeSignatureSelected)) {
            sap.setCertified(0);
            sap.setVisibleSignature(fieldName);
        } else {
            sap.setCertified(0);
            if ((fieldName != null) && (!"".equals(fieldName))) {
                sap.setVisibleSignature(fieldName);
            } else {
                sap.setVisibleSignature(new com.lowagie.text.Rectangle(llx, lly, urx, ury), 1, null);
            }
        }

    }

    //aggiunta di grafico per la firma
    if ("true".equals(graphicSignSelected)) {
        sap.setSignatureGraphic(Image.getInstance(fileImgfirma));
        sap.setRender(2);
    } else {
        sap.setRender(0);
    }
    sap.setExternalDigest(new byte[128], new byte[20], "RSA");

    PdfDictionary dic = new PdfDictionary();
    dic.put(PdfName.FT, PdfName.SIG);
    dic.put(PdfName.FILTER, new PdfName("Adobe.PPKLite"));
    dic.put(PdfName.SUBFILTER, new PdfName("adbe.pkcs7.detached"));
    if (cal != null) {
        dic.put(PdfName.M, new PdfDate(cal));
    } else {
        dic.put(PdfName.M, new PdfNull());
    }
    dic.put(PdfName.NAME, new PdfString(PdfPKCS7.getSubjectFields((X509Certificate) certs[0]).getField("CN")));
    dic.put(PdfName.REASON, new PdfString(reason));

    sap.setCryptoDictionary(dic);

    HashMap exc = new HashMap();
    exc.put(PdfName.CONTENTS, new Integer(0x5002));
    sap.preClose(exc);

    byte[] content = IOUtils.streamToByteArray(sap.getRangeStream());
    byte[] hash = MessageDigest.getInstance("2.16.840.1.101.3.4.2.1", "BC").digest(content);

    // costruzione degli authenticated attributes
    ASN1EncodableVector signedAttributes = buildSignedAttributes(hash, cal);
    byte[] bytesForSecondHash = IOUtils.toByteArray(new DERSet(signedAttributes));

    byte[] secondHash = MessageDigest.getInstance("2.16.840.1.101.3.4.2.1").digest(bytesForSecondHash);

    // -- Generatting the signature
    signatureBytes = mySign.sign(session, secondHash, signCertKeyObject);

    byte[] encodedPkcs7 = null;
    try {

        // Create the set of Hash algorithms
        DERConstructedSet digestAlgorithms = new DERConstructedSet();

        // Creo manualmente la sequenza di digest algos
        ASN1EncodableVector algos = new ASN1EncodableVector();
        //algos.add(new DERObjectIdentifier("1.3.14.3.2.26")); // SHA1
        //SHA256
        algos.add(new DERObjectIdentifier("2.16.840.1.101.3.4.2.1"));
        algos.add(new DERNull());
        digestAlgorithms.addObject(new DERSequence(algos));

        // Create the contentInfo.
        ASN1EncodableVector ev = new ASN1EncodableVector();
        ev.add(new DERObjectIdentifier("1.2.840.113549.1.7.1")); // PKCS7SignedData

        DERSequence contentinfo = new DERSequence(ev);

        // Get all the certificates
        //
        ASN1EncodableVector v = new ASN1EncodableVector();
        for (int c = 0; c < certs.length; c++) {
            ASN1InputStream tempstream = new ASN1InputStream(new ByteArrayInputStream(certs[c].getEncoded()));
            v.add(tempstream.readObject());
        }

        DERSet dercertificates = new DERSet(v);

        // Create signerinfo structure.
        //
        ASN1EncodableVector signerinfo = new ASN1EncodableVector();

        // Add the signerInfo version
        //
        signerinfo.add(new DERInteger(1));

        v = new ASN1EncodableVector();
        v.add(CertUtil.getIssuer(certs[0]));
        v.add(new DERInteger(certs[0].getSerialNumber()));
        signerinfo.add(new DERSequence(v));

        // Add the digestAlgorithm
        v = new ASN1EncodableVector();
        //v.add(new DERObjectIdentifier("1.3.14.3.2.26")); // SHA1
        //SHA-256
        v.add(new DERObjectIdentifier("2.16.840.1.101.3.4.2.1"));
        v.add(new DERNull());
        signerinfo.add(new DERSequence(v));

        // add the authenticated attribute if present
        signerinfo.add(new DERTaggedObject(false, 0, new DERSet(signedAttributes)));

        // Add the digestEncryptionAlgorithm
        v = new ASN1EncodableVector();
        v.add(new DERObjectIdentifier("1.2.840.113549.1.1.1"));// RSA
        v.add(new DERNull());
        signerinfo.add(new DERSequence(v));

        // Add the encrypted digest
        signerinfo.add(new DEROctetString(signatureBytes));

        // Add unsigned attributes (timestamp)
        if (serverTimestamp != null && !"".equals(serverTimestamp.toString())) {
            byte[] timestampHash = MessageDigest.getInstance("2.16.840.1.101.3.4.2.1", "BC")
                    .digest(signatureBytes);
            ASN1EncodableVector unsignedAttributes = buildUnsignedAttributes(timestampHash, serverTimestamp,
                    usernameTimestamp, passwordTimestamp);
            if (unsignedAttributes != null) {
                signerinfo.add(new DERTaggedObject(false, 1, new DERSet(unsignedAttributes)));
            }
        }

        // Finally build the body out of all the components above
        ASN1EncodableVector body = new ASN1EncodableVector();
        body.add(new DERInteger(1)); // pkcs7 version, always 1
        body.add(digestAlgorithms);
        body.add(contentinfo);
        body.add(new DERTaggedObject(false, 0, dercertificates));

        // Only allow one signerInfo
        body.add(new DERSet(new DERSequence(signerinfo)));

        // Now we have the body, wrap it in it's PKCS7Signed shell
        // and return it
        //
        ASN1EncodableVector whole = new ASN1EncodableVector();
        whole.add(new DERObjectIdentifier("1.2.840.113549.1.7.2"));// PKCS7_SIGNED_DATA
        whole.add(new DERTaggedObject(0, new DERSequence(body)));

        encodedPkcs7 = IOUtils.toByteArray(new DERSequence(whole));

    } catch (Exception e) {
        throw new ExceptionConverter(e);
    }

    PdfDictionary dic2 = new PdfDictionary();

    byte out[] = new byte[0x5000 / 2];
    System.arraycopy(encodedPkcs7, 0, out, 0, encodedPkcs7.length);

    dic2.put(PdfName.CONTENTS, new PdfString(out).setHexWriting(true));
    sap.close(dic2);

    logger.info("[createSignatureAppearance.retorna]:: ");

}