In attach the source code I used from the itext book, combined with the
eidlib

/*
 * This class is part of the book "iText in Action - 2nd Edition"
 * written by Bruno Lowagie (ISBN: 9781935182610)
 * For more info, go to: http://itextpdf.com/examples/
 * This example only works with the AGPL version of iText.
 */

import java.io.ByteArrayOutputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.security.MessageDigest;
import java.security.SignatureException;
import java.security.cert.Certificate;
import java.security.cert.X509Certificate;
import java.util.HashMap;

import be.belgium.eid.eidlib.BeID;
import be.belgium.eid.eidlib.BeID.SignatureType;
import be.belgium.eid.exceptions.EIDException;
import be.belgium.eid.security.CertificateChain;

import com.itextpdf.text.Rectangle;
import com.itextpdf.text.pdf.AcroFields;
import com.itextpdf.text.pdf.PdfDate;
import com.itextpdf.text.pdf.PdfDictionary;
import com.itextpdf.text.pdf.PdfName;
import com.itextpdf.text.pdf.PdfPKCS7;
import com.itextpdf.text.pdf.PdfReader;
import com.itextpdf.text.pdf.PdfSignature;
import com.itextpdf.text.pdf.PdfSignatureAppearance;
import com.itextpdf.text.pdf.PdfStamper;
import com.itextpdf.text.pdf.PdfString;

public class SignWithBC {

        /**
         * Main program that signs and verifies the data
         * 
         * @param args
         *            1 argument needs to be given: the PIN code. This is 
needed to
         *            generate the signature
         */
        public static void main(String[] args) {
                // The first and only argument that the program should receive 
is the
                // age to verify
                if (args.length != 1) {
                        System.err.println("SignAndVerify -- Invalid number of 
arguments.");
                } else {

                        // Load the eID
                        try {
                                PdfReader reader = new PdfReader("c:/test.pdf");
                                FileOutputStream fout = new 
FileOutputStream("c:/test"
                                                + ".selfsignmode.pdf");
                                PdfStamper stamper = 
PdfStamper.createSignature(reader, fout,
                                                '\0');
                                PdfSignatureAppearance sap = 
stamper.getSignatureAppearance();

                                final BeID eID = new BeID(false); // We don't 
allow test cards
                                CertificateChain chain = 
eID.getCertificateChain();
                                Certificate[] certs = new Certificate[3];
                                certs[0] = 
chain.getSignatureCert().getX509Certificate();
                                certs[1] = chain.getCertificateAuthorityCert()
                                                .getX509Certificate();
                                certs[2] = 
chain.getRootCert().getX509Certificate();

                                sap.setCrypto(null, certs, null,
                                                
PdfSignatureAppearance.SELF_SIGNED);
                                sap.setReason("How to use iText with the new 
belgian electronic identity
card");
                                //sap.setLocation("Belgium");
                                // comment next line to have an invisible 
signature
                                sap.setVisibleSignature(new Rectangle(100, 100, 
200, 200), 1,
                                                null);
                                
                                PdfSignature dic = new 
PdfSignature(PdfName.ADOBE_PPKMS,
PdfName.ADBE_PKCS7_SHA1);
                        dic.setDate(new PdfDate(sap.getSignDate()));
                       
dic.setName(PdfPKCS7.getSubjectFields((X509Certificate)certs[0]).getField("CN"));
                        dic.setReason("Signed with BC");
                        dic.setLocation("Foobar");
                        sap.setCryptoDictionary(dic);
                        
                        int csize = 4000;
                        HashMap<PdfName,Integer> exc = new 
HashMap<PdfName,Integer>();
                        exc.put(PdfName.CONTENTS, new Integer(csize * 2 + 2));
                        sap.preClose(exc);

                                // Process of hash/digest generation
                                MessageDigest md = 
MessageDigest.getInstance("SHA1");
                                byte[] content = 
streamToByteArray(sap.getRangeStream());
                                byte[] hashedContent = md.digest(content);
                                
                                // Signs the hash, args[0] is the PIN code
                                byte[] signature = 
eID.generateSignature(hashedContent, args[0],
                                                
SignatureType.NONREPUDIATIONSIG);
                                
                                // Places the signed hash/digest in the document
                    if(signature != null){
                                //byte[] pk = signedData.getEncoded();
                                byte[] outc = new byte[csize];
                            PdfDictionary dic2 = new PdfDictionary();
                            System.arraycopy(signature, 0, outc, 0,
signature.length);
                            dic2.put(PdfName.CONTENTS, new
PdfString(outc).setHexWriting(true));
                            sap.close(dic2);
                    } 
                    
                    fout.close();
                    
                    System.out.println("Verification succeeded: "
                                                + 
eID.verifySignature(hashedContent, signature,
                                                                
SignatureType.NONREPUDIATIONSIG));

                        } catch (EIDException e) {
                                System.err.println("SignAndVerify -- 
EIDException: "
                                                + e.getMessage());
                        } catch (Throwable e) {
                                System.err.println("SignAndVerify -- Exception: 
"
                                                + e.getMessage());
                                e.printStackTrace();
                        }
                }
        }

        public static byte[] streamToByteArray(InputStream stream) throws 
Throwable
{
                if (stream == null) {
                        return null;
                } else {
                        ByteArrayOutputStream byteArray = new 
ByteArrayOutputStream();
                        byte buffer[] = new byte[1024];
                        int c = 0;
                        while ((c = stream.read(buffer)) > 0) {
                                byteArray.write(buffer, 0, c);
                        }
                        byteArray.flush();
                        
                        return byteArray.toByteArray();
                }
        }
        
        // see http://itextpdf.sourceforge.net/howtosign.html#howtoverify
    public static PdfPKCS7 verifySignature(byte[] pdfContents, String
signatureField)
            throws SignatureException, IOException {

        PdfReader reader = new PdfReader(pdfContents);
        AcroFields af = reader.getAcroFields();

        PdfPKCS7 pk = af.verifySignature(signatureField);
        if (pk == null) {
            throw new SignatureException("Signature Field " + signatureField
                    + " does not seem to be a valid signature field");
        }
        if (!pk.verify()) {
            throw new SignatureException(
                    "The signature does not belong to this document or document 
has been
modified after signing.");
        }

        // this return value can be used in the future to be able to verify the
        // certificate
        return pk;

    }
}

--
View this message in context: 
http://itext-general.2136553.n4.nabble.com/Re-HASH-SMARTCARD-and-PKCS-7-detached-tp3341984p4387319.html
Sent from the iText - General mailing list archive at Nabble.com.

------------------------------------------------------------------------------
Keep Your Developer Skills Current with LearnDevNow!
The most comprehensive online learning library for Microsoft developers
is just $99.99! Visual Studio, SharePoint, SQL - plus HTML5, CSS3, MVC3,
Metro Style Apps, more. Free future releases when you subscribe now!
http://p.sf.net/sfu/learndevnow-d2d
_______________________________________________
iText-questions mailing list
[email protected]
https://lists.sourceforge.net/lists/listinfo/itext-questions

iText(R) is a registered trademark of 1T3XT BVBA.
Many questions posted to this list can (and will) be answered with a reference 
to the iText book: http://www.itextpdf.com/book/
Please check the keywords list before you ask for examples: 
http://itextpdf.com/themes/keywords.php

Reply via email to