Example usage for com.itextpdf.text.pdf PdfDate toUnicodeString

List of usage examples for com.itextpdf.text.pdf PdfDate toUnicodeString

Introduction

In this page you can find the example usage for com.itextpdf.text.pdf PdfDate toUnicodeString.

Prototype

public String toUnicodeString() 

Source Link

Document

Returns the Unicode String value of this PdfString-object.

Usage

From source file:org.sinekartads.core.pdf.PDFTools.java

License:Open Source License

public static DigestSignature<SignatureType.SignCategory, SignDisposition.PDF, SecurityLevel.VerifyResult, PDFSignatureInfo> calculateFingerPrint(
        ChainSignature<SignatureType.SignCategory, SignDisposition.PDF, SecurityLevel.VerifyResult, PDFSignatureInfo> chainSignature,
        //                                                           X509Certificate certificate, 
        InputStream is) throws SignatureException {
    //      calculateFingerPrint(doc, certificate, is, null, null, null, null, null);
    //   }/*from w  ww  . j a  v a 2 s.c o  m*/
    //   
    //   public static void calculateFingerPrint(DigitalSignatureDocument doc,
    //         X509Certificate certificate, InputStream is, Collection<CrlClient> crlList, OcspClient ocspClient, String tsaUrl, String tsaUser, String tsaPassword) {
    try {

        //         TSAClient tsaClient=null;
        //         
        //         if (tsaUrl!=null) {
        //            tsaClient = new SinekartaTSAClient(tsaUrl, tsaUser, tsaPassword);
        //         }
        //
        int estimatedSize = 0;
        CryptoStandard sigtype = CryptoStandard.CMS; // FIXME qui c'era CMS
        PDFSignatureInfo signature = (PDFSignatureInfo) chainSignature;

        // creo il reader del pdf
        PdfReader reader = new PdfReader(is);

        // creo lo stamper (se il pdf e' gia' firmato, controfirma,
        // altrimenti firma
        PdfStamper stamper = null;
        if (isPdfSigned(reader)) {
            if (tracer.isDebugEnabled())
                tracer.debug("calculating finger print for document already signed");
            stamper = PdfStamper.createSignature(reader, null, '\0', null, true);
        } else {
            if (tracer.isDebugEnabled())
                tracer.debug("calculating finger print for document never signed before");
            stamper = PdfStamper.createSignature(reader, null, '\0');
        }

        // questo e' il certificato su cui lavorare
        Certificate[] chain = signature.getRawX509Certificates();
        //         Certificate[] chain = new Certificate[1];
        //         chain[0] = certificate;

        // creo la signature apparence
        PdfSignatureAppearance sap = stamper.getSignatureAppearance();
        ExternalDigest externalDigest = new BouncyCastleDigest();

        // inizio codice copiato da MakeSignature

        //         Collection<byte[]> crlBytes = null;
        //           int i = 0;
        //           while (crlBytes == null && i < chain.length)
        //              crlBytes = MakeSignature.processCrl(chain[i++], crlList);
        if (estimatedSize == 0) {
            estimatedSize = 8192;
            //               if (crlBytes != null) {
            //                   for (byte[] element : crlBytes) {
            //                       estimatedSize += element.length + 10;
            //                   }
            //               }
            //               if (ocspClient != null)
            estimatedSize += 4192;
            //               if (tsaClient != null)
            estimatedSize += 4192;
        }
        Calendar now = Calendar.getInstance();
        PdfDate date = new PdfDate(now);

        sap.setSignDate(now);
        signature.setSigningTime(now.getTime());
        signature.setUnicodeModDate(date.toUnicodeString());

        sap.setCertificate(chain[0]);
        sap.setReason(signature.getReason());
        sap.setLocation(signature.getLocation());

        PdfSignature dic = new PdfSignature(PdfName.ADOBE_PPKLITE, PdfName.ADBE_PKCS7_DETACHED);
        dic.setReason(sap.getReason());
        dic.setLocation(sap.getLocation());
        dic.setContact(sap.getContact());
        dic.setDate(date); // time-stamp will over-rule this
        sap.setCryptoDictionary(dic);

        HashMap<PdfName, Integer> exc = new HashMap<PdfName, Integer>();
        exc.put(PdfName.CONTENTS, new Integer(estimatedSize * 2 + 2));
        sap.preClose(exc);

        String hashAlgorithm = signature.getDigestAlgorithm().getName();
        PdfPKCS7 sgn = new PdfPKCS7(null, chain, hashAlgorithm, BouncyCastleProvider.PROVIDER_NAME,
                externalDigest, false);
        //           String hashAlgorithm = Constants.SHA256;
        //           PdfPKCS7 sgn = new PdfPKCS7(null, chain, hashAlgorithm, Constants.BC, externalDigest, false);
        InputStream data = sap.getRangeStream();
        byte hash[] = DigestAlgorithms.digest(data, externalDigest.getMessageDigest(hashAlgorithm));
        //           byte[] ocsp = null;
        //           if (chain.length >= 2 && ocspClient != null) {
        //               ocsp = ocspClient.getEncoded((X509Certificate) chain[0], (X509Certificate) chain[1], null);
        //           }
        //           byte[] authenticatedAttributeBytes = sgn.getAuthenticatedAttributeBytes(hash, now, ocsp, crlBytes, sigtype);
        byte[] authenticatedAttributeBytes = sgn.getAuthenticatedAttributeBytes(hash, now, null, null, sigtype);

        // calcolo dell'impronta
        MessageDigest digester = MessageDigest.getInstance(signature.getDigestAlgorithm().getName());
        byte[] fingerPrint = digester.digest(authenticatedAttributeBytes);

        //           byte[] fingerPrint = Util.digest256(authenticatedAttributeBytes);

        signature.setAuthenticatedAttributeBytes(authenticatedAttributeBytes);
        signature.setFileId(sap.getStamper().getFileId());
        //           signature.setFileIDByteContent(TextUtil.byteToHex(sap.getStamper().getFileID().getBytes()));
        signature.setUnicodeModDate(sap.getStamper().getUnicodeModDate());
        //         signature.setModDateUnicodeString(sap.getStamper().getModDate().toUnicodeString());
        signature.setSigningTime(now.getTime());
        //         SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmssSSSZ");
        //         signature.setSignDate(sdf.format(now.getTime()));

        // this should be already done, but ...
        // closing streams
        try {
            is.close();
        } catch (IOException e) {
            tracer.error("error on input stream", e);
        }

        return signature.toDigestSignature(DigestInfo.getInstance(signature.getDigestAlgorithm(), fingerPrint));
    } catch (Exception e) {
        tracer.error("Unable to calculate finger print of PDF.", e);
        //         throw new PDFException("Unable calculate finger print of PDF.", e);
        throw new SignatureException("Unable calculate finger print of PDF.", e);
    }
}