1   package org.intix.signer;
2   
3   import java.io.FileNotFoundException;
4   import java.io.FileOutputStream;
5   import java.io.IOException;
6   import java.io.InputStream;
7   import java.security.KeyStore;
8   import java.security.SignatureException;
9   import java.security.cert.Certificate;
10  import java.util.ArrayList;
11  import java.util.Calendar;
12  
13  import com.lowagie.text.pdf.AcroFields;
14  import com.lowagie.text.pdf.PdfPKCS7;
15  import com.lowagie.text.pdf.PdfReader;
16  
17  public class VerifyPdf {
18  
19  	KeyStore kall = null;
20  
21  	public VerifyPdf() {
22  		kall = PdfPKCS7.loadCacertsKeyStore();
23  	}
24  
25  	protected void printSignInfo(String name, AcroFields af) {
26  		System.out.println("Signature name: " + name);
27  		System.out.println("Signature covers whole document: "
28  				+ af.signatureCoversWholeDocument(name));
29  		System.out.println("Document revision: " + af.getRevision(name)
30  				+ " of " + af.getTotalRevisions());
31  	}
32  
33  	protected void checkRevision(String name, AcroFields af)
34  			throws FileNotFoundException, IOException {
35  		// Start revision extraction
36  		FileOutputStream out = new FileOutputStream("./test/revision_"
37  				+ af.getRevision(name) + ".pdf");
38  		byte bb[] = new byte[8192];
39  		InputStream ip = af.extractRevision(name);
40  		int n = 0;
41  		while ((n = ip.read(bb)) > 0)
42  			out.write(bb, 0, n);
43  		out.close();
44  		ip.close();
45  		// End revision extraction
46  	}
47  	
48  	protected void checkSignature(String name, AcroFields af) throws SignatureException{
49  		
50  		PdfPKCS7 pk = af.verifySignature(name);
51  		Calendar cal = pk.getSignDate();
52  		Certificate pkc[] = pk.getCertificates();
53  		System.out.println("Subject: "
54  				+ PdfPKCS7.getSubjectFields(pk.getSigningCertificate()));
55  		System.out.println("Document modified: " + !pk.verify());
56  		Object fails[] = PdfPKCS7.verifyCertificates(pkc, kall, null, cal);
57  		if (fails == null)
58  			System.out
59  					.println("Certificates verified against the KeyStore");
60  		else
61  			System.out.println("Certificate failed: " + fails[1]);
62  		
63  	}
64  
65  	public void verify(String aSignedPdf) throws IOException, SignatureException {
66  
67  		PdfReader reader = new PdfReader(aSignedPdf);
68  
69  		AcroFields af = reader.getAcroFields();
70  		ArrayList names = af.getSignatureNames();
71  
72  		for (int k = 0; k < names.size(); ++k) {
73  			String name = (String) names.get(k);
74  			printSignInfo(name, af);
75  
76  			checkRevision(name, af);
77  			
78  			checkSignature(name,af);
79  		}
80  	}
81  
82  	public static void main(String args[]) throws Exception {
83  		
84  		VerifyPdf aVerifyPdf = new VerifyPdf();
85  		aVerifyPdf.verify("./test/signed.pdf");
86  		
87  	}
88  }