1 package org.intix.signer;
2
3 import java.io.FileInputStream;
4 import java.io.FileOutputStream;
5 import java.io.IOException;
6 import java.security.KeyStore;
7 import java.security.KeyStoreException;
8 import java.security.NoSuchAlgorithmException;
9 import java.security.PrivateKey;
10 import java.security.UnrecoverableKeyException;
11 import java.security.cert.Certificate;
12
13 import com.lowagie.text.DocumentException;
14 import com.lowagie.text.Rectangle;
15 import com.lowagie.text.pdf.PdfName;
16 import com.lowagie.text.pdf.PdfReader;
17 import com.lowagie.text.pdf.PdfSignatureAppearance;
18 import com.lowagie.text.pdf.PdfStamper;
19
20 public class SignPdf {
21
22 private KeyStore ks = null;
23
24 public SignPdf(String aKeystore_Path, String aKeystore_Pass)
25 throws Exception {
26 ks = KeyStore.getInstance(KeyStore.getDefaultType());
27 ks.load(new FileInputStream(aKeystore_Path), aKeystore_Pass
28 .toCharArray());
29 }
30
31 protected Certificate[] getCertificate(String aAlias) throws KeyStoreException {
32 return ks.getCertificateChain(aAlias);
33
34 }
35
36 protected PrivateKey getPrivateKey(String aAlias, String aPrivateKey_Pass)
37 throws NoSuchAlgorithmException, UnrecoverableKeyException,
38 KeyStoreException {
39 return (PrivateKey) ks.getKey(aAlias, aPrivateKey_Pass.toCharArray());
40
41 }
42
43 public void sign(String aPdf, String aPdfSign, String aAlias,
44 String aPrivateKey_Pass, boolean visible) throws IOException, DocumentException,
45 KeyStoreException, NoSuchAlgorithmException,
46 UnrecoverableKeyException {
47
48 PdfReader reader = new PdfReader(aPdf);
49 FileOutputStream fout = new FileOutputStream(aPdfSign);
50
51 PdfStamper stp = PdfStamper.createSignature(reader, fout, '\0');
52 PdfSignatureAppearance sap = stp.getSignatureAppearance();
53
54 sap.setCrypto(getPrivateKey(aAlias, aPrivateKey_Pass),
55 getCertificate(aAlias), null,
56 PdfSignatureAppearance.SELF_SIGNED);
57 sap.setReason("El autor");
58 sap.setLocation("Barcelona");
59
60 if( visible ) {
61
62 sap.setVisibleSignature(new Rectangle(100, 100, 200, 200), 1, null);
63 stp.close();
64 }
65 }
66
67 public static void main(String args[]) throws Exception {
68 String KEYSTORE_PATH = "./test/keystore.ks";
69 String KEYSTORE_PASS = "in2pass";
70 String PRIVATEKEY_PASS = "in2pass";
71 String PDF_ORGINAL = "./test/original.pdf";
72 String PDF_FINAL = "./test/signed.pdf";
73 String CERT_ALIAS = "juancarlos";
74 boolean visible = true;
75
76 SignPdf aSigner = new SignPdf(KEYSTORE_PATH, KEYSTORE_PASS);
77 aSigner.sign(PDF_ORGINAL, PDF_FINAL, CERT_ALIAS, PRIVATEKEY_PASS, visible);
78 }
79 }