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

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

Introduction

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

Prototype

PdfName M

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

Click Source Link

Document

A name

Usage

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   w  w  w .j a  v a  2  s. c om
 * @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   w  w w. j a  va2 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]:: ");

}