Example usage for com.lowagie.text.pdf PdfSignatureAppearance setCrypto

List of usage examples for com.lowagie.text.pdf PdfSignatureAppearance setCrypto

Introduction

In this page you can find the example usage for com.lowagie.text.pdf PdfSignatureAppearance setCrypto.

Prototype

public void setCrypto(PrivateKey privKey, Certificate[] certChain, CRL[] crlList, PdfName filter) 

Source Link

Document

Sets the cryptographic parameters.

Usage

From source file:org.webpki.pdf.PDFSigner.java

License:Apache License

public byte[] addDocumentSignature(byte[] indoc, boolean certified) throws IOException {
    try {/*from  ww w . ja va  2s  . c o m*/
        PdfReader reader = new PdfReader(indoc);
        ByteArrayOutputStream bout = new ByteArrayOutputStream(8192);
        PdfStamper stp = PdfStamper.createSignature(reader, bout, '\0', null, true);

        for (Attachment file : attachments) {
            stp.addFileAttachment(file.description, file.data, "dummy", file.filename);
        }

        PdfSignatureAppearance sap = stp.getSignatureAppearance();
        sap.setCrypto(null, signer.getCertificatePath(), null, PdfSignatureAppearance.WINCER_SIGNED);

        if (reason != null) {
            sap.setReason(reason);
        }
        if (location != null) {
            sap.setLocation(location);
        }

        if (enable_signature_graphics) {
            sap.setVisibleSignature(new Rectangle(100, 100, 400, 130), reader.getNumberOfPages(), null);
        }

        sap.setCertified(certified);

        //           sap.setExternalDigest (new byte[128], new byte[20], "RSA");
        sap.setExternalDigest(new byte[512], new byte[20], "RSA");
        sap.preClose();
        MessageDigest messageDigest = MessageDigest.getInstance("SHA1");
        byte buf[] = new byte[8192];
        int n;
        InputStream inp = sap.getRangeStream();
        while ((n = inp.read(buf)) > 0) {
            messageDigest.update(buf, 0, n);
        }
        byte hash[] = messageDigest.digest();
        PdfSigGenericPKCS sg = sap.getSigStandard();
        PdfLiteral slit = (PdfLiteral) sg.get(PdfName.CONTENTS);
        byte[] outc = new byte[(slit.getPosLength() - 2) / 2];
        PdfPKCS7 sig = sg.getSigner();
        sig.setExternalDigest(signer.signData(hash, AsymSignatureAlgorithms.RSA_SHA1), hash, "RSA");
        PdfDictionary dic = new PdfDictionary();
        byte[] ssig = sig.getEncodedPKCS7();
        System.arraycopy(ssig, 0, outc, 0, ssig.length);
        dic.put(PdfName.CONTENTS, new PdfString(outc).setHexWriting(true));
        sap.close(dic);

        return bout.toByteArray();
    } catch (NoSuchAlgorithmException nsae) {
        throw new IOException(nsae.getMessage());
    } catch (DocumentException de) {
        throw new IOException(de.getMessage());
    }
}

From source file:questions.stamppages.CertificationSig.java

public static void main(String[] args) {

    PdfReader reader;//  w  ww .  j  a v  a  2 s.  c  o  m
    try {
        KeyStore ks = KeyStore.getInstance(KeyStore.getDefaultType());
        ks.load(new FileInputStream(KEYSTORE), "f00b4r".toCharArray());
        PrivateKey key = (PrivateKey) ks.getKey("foobar", "r4b00f".toCharArray());
        Certificate[] chain = ks.getCertificateChain("foobar");
        reader = new PdfReader(RESOURCE);
        FileOutputStream os = new FileOutputStream(RESULT);
        PdfStamper stamper = PdfStamper.createSignature(reader, os, '\0');
        PdfSignatureAppearance appearance = stamper.getSignatureAppearance();
        appearance.setCrypto(key, chain, null, PdfSignatureAppearance.SELF_SIGNED);
        appearance.setCertificationLevel(PdfSignatureAppearance.CERTIFIED_FORM_FILLING);
        appearance.setReason("It's personal.");
        appearance.setLocation("Foobar");
        appearance.setVisibleSignature("Certifier_Signature");
        stamper.close();
    } catch (KeyStoreException e) {
        e.printStackTrace();
    } catch (NoSuchAlgorithmException e) {
        e.printStackTrace();
    } catch (CertificateException e) {
        e.printStackTrace();
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    } catch (UnrecoverableKeyException e) {
        e.printStackTrace();
    } catch (DocumentException e) {
        e.printStackTrace();
    }
}

From source file:si.vsrs.cif.svev.example.utils.PDFSignature.java

License:EUPL

public File signPDF(File document, InputStream keystore, String password, String keyPassord,
        String keystoreType, String alias, boolean bshowVisualization) {
    if (document == null || !document.exists()) {
        throw new RuntimeException("Error reading pdf");
    }//from   ww  w. ja v  a 2s  . c om

    String name = document.getName();
    String substring = name.substring(0, name.lastIndexOf("."));

    File outputDocument = new File(document.getParent(), substring + "_signed.pdf");

    try (FileInputStream fis = new FileInputStream(document);
            FileOutputStream fout = new FileOutputStream(outputDocument)) {

        KeyStore ks = KeyStore.getInstance(keystoreType);
        ks.load(keystore, password.toCharArray());
        PrivateKey key = (PrivateKey) ks.getKey(alias, keyPassord.toCharArray());
        Certificate[] chain = ks.getCertificateChain(alias);
        X509Certificate xcert = (X509Certificate) chain[0];
        PdfReader reader = new PdfReader(fis);

        char tmpPdfVersion = '\0'; // default version - the same as input
        final PdfStamper stp = PdfStamper.createSignature(reader, fout, tmpPdfVersion, null, true);
        final PdfSignatureAppearance sap = stp.getSignatureAppearance();
        sap.setCrypto(key, chain, null, PdfSignatureAppearance.WINCER_SIGNED);
        sap.setReason("Testni podpis");
        sap.setLocation("Maribor");
        sap.setContact(xcert.getSubjectDN().getName());

        //            sap.setLayer2Text("");
        //          sap.setLayer4Text("");
        sap.setAcro6Layers(true); // --:> 

        Rectangle rc = reader.getPageSize(1);
        if (bshowVisualization) {
            sap.setVisibleSignature(new Rectangle(5, rc.getHeight() - 40, 240, rc.getHeight() - 5), 1, null);
        }

        final PdfSignature dic = new PdfSignature(PdfName.ADOBE_PPKLITE, new PdfName("adbe.pkcs7.detached"));

        dic.setReason(sap.getReason());
        dic.setLocation(sap.getLocation());
        dic.setContact(sap.getContact());
        dic.setDate(new PdfDate(sap.getSignDate()));
        sap.setCryptoDictionary(dic);
        final int contentEstimated = 15000;
        final HashMap<PdfName, Integer> exc = new HashMap<>();
        exc.put(PdfName.CONTENTS, contentEstimated * 2 + 2);
        sap.preClose(exc);

        PdfPKCS7 sgn = new PdfPKCS7(key, chain, null, "SHA-256", null, false);
        InputStream data = sap.getRangeStream();
        final MessageDigest messageDigest = MessageDigest.getInstance("SHA-256");
        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();

        byte sh[] = sgn.getAuthenticatedAttributeBytes(hash, cal, null);
        sgn.update(sh, 0, sh.length);

        byte[] encodedSig = sgn.getEncodedPKCS7(hash, cal, null, null);

        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));

        sap.close(dic2);
    } catch (IOException | KeyStoreException | NoSuchAlgorithmException | CertificateException
            | UnrecoverableKeyException | DocumentException | InvalidKeyException | NoSuchProviderException
            | SignatureException ex) {
        throw new RuntimeException(ex.getMessage(), ex);
    }

    return outputDocument;
}

From source file:sos.util.security.SOSPDFSignatur.java

License:Apache License

/**
 * PDF Signatur erzeugen/*w  w w  .j  a v  a  2s.  co m*/
 * 
 * @param privateKey      Private Key
 * @param chain            Certificate Chain
 * @param originalPdfName   Original PDF Datei zur Signierung
 * @param outputPdfName      Output (signierte) PDF Datei
 * @throws Exception
 */
public static void createSignatur(PrivateKey privateKey, Certificate[] chain, String originalPdfName,
        String outputPdfName) throws Exception {

    PdfReader reader = new PdfReader(originalPdfName);
    FileOutputStream fout = new FileOutputStream(outputPdfName);

    //createSignature(PdfReader reader, OutputStream os, char pdfVersion)
    //pdfVersion - the new pdf version or '\0' to keep the same version as
    // the original document

    PdfStamper stp = PdfStamper.createSignature(reader, fout, '\0');
    PdfSignatureAppearance sap = stp.getSignatureAppearance();

    //setCrypto(PrivateKey privKey, Certificate[] certChain, CRL[] crlList, PdfName filter) 
    // CRL - certificate revocation lists (CRLs) that have different formats but important common uses.
    //       For example, all CRLs share the functionality of listing revoked certificates, and can be queried on whether or not they list a given certificate.
    // PdfName
    // SELF_SIGNED       -    The self signed filter
    // VERISIGN_SIGNED  -    The VeriSign filter
    // WINCER_SIGNED    -    The Windows Certificate Security
    sap.setCrypto(privateKey, chain, null, PdfSignatureAppearance.SELF_SIGNED);
    //sap.setCrypto(privateKey, chain, null,PdfSignatureAppearance.WINCER_SIGNED);

    sap.setReason(SOSPDFSignatur.reason);
    sap.setContact(SOSPDFSignatur.contact);
    sap.setLocation(SOSPDFSignatur.location);

    //GregorianCalendar cal = new GregorianCalendar();
    //sap.setSignDate(cal);

    //             comment next line to have an invisible signature
    //setVisibleSignature(Rectangle pageRect, int page, String fieldName)

    //sap.setVisibleSignature(new Rectangle(100, 100, 200, 200), 1, null);
    //sap.setVisibleSignature(new Rectangle(100,100,200, 200), 1, null);

    if (SOSPDFSignatur.visible) {// todo
        //sap.setVisibleSignature(new Rectangle(200, 200, 400, 400), 1, null);
    }

    stp.close();

}

From source file:vn.vfossa.signature.PdfContent.java

License:Open Source License

@Override
public void addSignature(X509Certificate certificate, PrivateKey key) throws Exception {
    // TODO Auto-generated method stub
    Certificate cer[] = { certificate };
    for (int index = path.length() - 1; index >= 0; index--)
        if (path.charAt(index) == '.') {
            signedPath = path.substring(0, index) + "_signed" + path.substring(index);
            break;
        }/*from w  w  w .  j  a v  a2 s.  c  o  m*/
    File file = new File(signedPath);
    FileOutputStream out = new FileOutputStream(file);

    int numOfPages = content.getNumberOfPages();
    int numOfSignatures = content.getAcroFields().getSignatureNames().size() + 1;
    PdfStamper stp = PdfStamper.createSignature(content, out, '\0', null, true);
    PdfSignatureAppearance sap = stp.getSignatureAppearance();
    int m = (numOfPages - 1) * 5 + (numOfSignatures - 1) * 200;

    try {
        Calendar ca = Calendar.getInstance();
        ca.setTime(new Date());
        sap.setSignDate(ca);
    } catch (Exception ex) {
        ex.printStackTrace();
    }
    sap.setCrypto(key, cer, null, PdfSignatureAppearance.WINCER_SIGNED);
    sap.setVisibleSignature(new com.lowagie.text.Rectangle(m, 0, m + 200, 30), 1, null);

    stp.close();
    //Files.delete(Paths.get(path));
    content = new PdfReader(signedPath);
}