-
Notifications
You must be signed in to change notification settings - Fork 18
/
CreateSignature.java
170 lines (149 loc) · 6.62 KB
/
CreateSignature.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
package mkl.testarea.pdfbox1.sign;
import org.apache.pdfbox.exceptions.COSVisitorException;
import org.apache.pdfbox.exceptions.SignatureException;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.pdmodel.interactive.digitalsignature.PDSignature;
import org.apache.pdfbox.pdmodel.interactive.digitalsignature.SignatureInterface;
import org.bouncycastle.asn1.ASN1ObjectIdentifier;
import org.bouncycastle.asn1.DEROutputStream;
import org.bouncycastle.asn1.pkcs.PKCSObjectIdentifiers;
import org.bouncycastle.cert.X509CertificateHolder;
import org.bouncycastle.cert.jcajce.JcaCertStore;
import org.bouncycastle.cms.CMSException;
import org.bouncycastle.cms.CMSSignedData;
import org.bouncycastle.cms.CMSSignedDataGenerator;
import org.bouncycastle.cms.CMSTypedData;
import org.bouncycastle.cms.jcajce.JcaSignerInfoGeneratorBuilder;
import org.bouncycastle.jce.provider.BouncyCastleProvider;
import org.bouncycastle.operator.ContentSigner;
import org.bouncycastle.operator.jcajce.JcaContentSignerBuilder;
import org.bouncycastle.operator.jcajce.JcaDigestCalculatorProviderBuilder;
import org.bouncycastle.util.Store;
import java.io.*;
import java.security.GeneralSecurityException;
import java.security.KeyStore;
import java.security.KeyStoreException;
import java.security.PrivateKey;
import java.security.cert.Certificate;
import java.util.Calendar;
import java.util.Collections;
import java.util.Enumeration;
/**
* This class is the code presented by the author of the stackoverflow question
* <a href="http://stackoverflow.com/questions/30400728/signing-pdf-with-pdfbox-and-bouncycastle">
* Signing PDF with PDFBox and BouncyCastle</a> with three sets of changes:
* <ol>
* <li>Visibilities of some members have been changed to allow better testability
* <li>a new static member {@link #fixed} has been added which in {@link #signPdf(File, File)}
* switches between the original (for <code>false</code>) and the fixed (for <code>true</code>)
* code; additionally the order of creation of <code>fis</code> and <code>fos</code> has been
* swapped which does not affect the original flow but is necessary for the fixed flow.
* <li>a new static member {@link #der} has been added which in {@link #signPdf(File, File)}
* switches between the original (for <code>false</code>) and improved (for <code>true</code>)
* code which generates a completely DER-encoded object.
* </ol>
*
* @author mkl
*/
public class CreateSignature implements SignatureInterface
{
static boolean fixed = true;
static boolean der = true;
static PrivateKey privateKey;
static Certificate certificate;
boolean signPdf(File pdfFile, File signedPdfFile) {
try (
FileInputStream fis1 = new FileInputStream(pdfFile);
FileOutputStream fos = new FileOutputStream(signedPdfFile);
FileInputStream fis = new FileInputStream(fixed ? signedPdfFile : pdfFile);
PDDocument doc = PDDocument.load(pdfFile)) {
int readCount;
byte[] buffer = new byte[8 * 1024];
while ((readCount = fis1.read(buffer)) != -1) {
fos.write(buffer, 0, readCount);
}
PDSignature signature = new PDSignature();
signature.setFilter(PDSignature.FILTER_ADOBE_PPKLITE);
signature.setSubFilter(PDSignature.SUBFILTER_ADBE_PKCS7_DETACHED);
signature.setName("NAME");
signature.setLocation("LOCATION");
signature.setReason("REASON");
signature.setSignDate(Calendar.getInstance());
doc.addSignature(signature, this);
doc.saveIncremental(fis, fos);
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
@Override
public byte[] sign(InputStream is) throws SignatureException, IOException {
try {
BouncyCastleProvider BC = new BouncyCastleProvider();
Store<?> certStore = new JcaCertStore(Collections.singletonList(certificate));
CMSTypedDataInputStream input = new CMSTypedDataInputStream(is);
CMSSignedDataGenerator gen = new CMSSignedDataGenerator();
ContentSigner sha512Signer = new JcaContentSignerBuilder("SHA256WithRSA").setProvider(BC).build(privateKey);
gen.addSignerInfoGenerator(new JcaSignerInfoGeneratorBuilder(
new JcaDigestCalculatorProviderBuilder().setProvider(BC).build()).build(sha512Signer, new X509CertificateHolder(certificate.getEncoded())
));
gen.addCertificates(certStore);
CMSSignedData signedData = gen.generate(input, false);
if (der)
{
ByteArrayOutputStream baos = new ByteArrayOutputStream();
DEROutputStream dos = new DEROutputStream(baos);
dos.writeObject(signedData.toASN1Structure());
return baos.toByteArray();
}
else
return signedData.getEncoded();
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
public static void main(String[] args) throws IOException, GeneralSecurityException, SignatureException, COSVisitorException {
char[] password = "123456".toCharArray();
KeyStore keystore = KeyStore.getInstance("PKCS12");
keystore.load(new FileInputStream("/home/user/Desktop/keystore.p12"), password);
Enumeration<String> aliases = keystore.aliases();
String alias;
if (aliases.hasMoreElements()) {
alias = aliases.nextElement();
} else {
throw new KeyStoreException("Keystore is empty");
}
privateKey = (PrivateKey) keystore.getKey(alias, password);
Certificate[] certificateChain = keystore.getCertificateChain(alias);
certificate = certificateChain[0];
File inFile = new File("/home/user/Desktop/sign.pdf");
File outFile = new File("/home/user/Desktop/sign_signed.pdf");
new CreateSignature().signPdf(inFile, outFile);
}
}
class CMSTypedDataInputStream implements CMSTypedData {
InputStream in;
public CMSTypedDataInputStream(InputStream is) {
in = is;
}
@Override
public ASN1ObjectIdentifier getContentType() {
return PKCSObjectIdentifiers.data;
}
@Override
public Object getContent() {
return in;
}
@Override
public void write(OutputStream out) throws IOException,
CMSException {
byte[] buffer = new byte[8 * 1024];
int read;
while ((read = in.read(buffer)) != -1) {
out.write(buffer, 0, read);
}
in.close();
}
}