-
Notifications
You must be signed in to change notification settings - Fork 6
Expand file tree
/
Copy pathCreateSignatureBase.java
More file actions
308 lines (281 loc) · 11 KB
/
CreateSignatureBase.java
File metadata and controls
308 lines (281 loc) · 11 KB
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
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
package PDFSignature;
import java.io.IOException;
import java.io.InputStream;
import java.security.GeneralSecurityException;
import java.security.KeyStore;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.security.PrivateKey;
import java.security.UnrecoverableKeyException;
import java.security.cert.Certificate;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.List;
import org.apache.pdfbox.cos.COSArray;
import org.apache.pdfbox.cos.COSBase;
import org.apache.pdfbox.cos.COSDictionary;
import org.apache.pdfbox.cos.COSName;
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.ASN1Encodable;
import org.bouncycastle.asn1.ASN1EncodableVector;
import org.bouncycastle.asn1.ASN1ObjectIdentifier;
import org.bouncycastle.asn1.ASN1Primitive;
import org.bouncycastle.asn1.DERSet;
import org.bouncycastle.asn1.cms.Attribute;
import org.bouncycastle.asn1.cms.AttributeTable;
import org.bouncycastle.asn1.cms.Attributes;
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.SignerInformation;
import org.bouncycastle.cms.SignerInformationStore;
import org.bouncycastle.cms.jcajce.JcaSignerInfoGeneratorBuilder;
import org.bouncycastle.operator.ContentSigner;
import org.bouncycastle.operator.OperatorCreationException;
import org.bouncycastle.operator.jcajce.JcaContentSignerBuilder;
import org.bouncycastle.operator.jcajce.JcaDigestCalculatorProviderBuilder;
import org.bouncycastle.tsp.TSPException;
import org.bouncycastle.util.Store;
public abstract class CreateSignatureBase implements SignatureInterface {
private PrivateKey privateKey;
private Certificate certificate;
private TSAClient tsaClient;
private boolean externalSigning;
/**
* Initialize the signature creator with a keystore (pkcs12) and pin that
* should be used for the signature.
*
* @param keystore
* is a pkcs12 keystore.
* @param pin
* is the pin for the keystore / private key
* @throws KeyStoreException
* if the keystore has not been initialized (loaded)
* @throws NoSuchAlgorithmException
* if the algorithm for recovering the key cannot be found
* @throws UnrecoverableKeyException
* if the given password is wrong
* @throws CertificateException
* if the certificate is not valid as signing time
* @throws IOException
* if no certificate could be found
*/
public CreateSignatureBase(KeyStore keystore, char[] pin) throws KeyStoreException, UnrecoverableKeyException,
NoSuchAlgorithmException, IOException, CertificateException {
// grabs the first alias from the keystore and get the private key. An
// alternative method or constructor could be used for setting a
// specific
// alias that should be used.
Enumeration<String> aliases = keystore.aliases();
String alias;
Certificate cert = null;
while (aliases.hasMoreElements()) {
alias = aliases.nextElement();
setPrivateKey((PrivateKey) keystore.getKey(alias, pin));
Certificate[] certChain = keystore.getCertificateChain(alias);
if (certChain == null) {
continue;
}
cert = certChain[0];
setCertificate(cert);
if (cert instanceof X509Certificate) {
// avoid expired certificate
((X509Certificate) cert).checkValidity();
}
break;
}
if (cert == null) {
throw new IOException("Could not find certificate");
}
}
public final void setPrivateKey(PrivateKey privateKey) {
this.privateKey = privateKey;
}
public final void setCertificate(Certificate certificate) {
this.certificate = certificate;
}
public void setTsaClient(TSAClient tsaClient) {
this.tsaClient = tsaClient;
}
public TSAClient getTsaClient() {
return tsaClient;
}
/**
* We just extend CMS signed Data
*
* @param signedData
* ´Generated CMS signed data
* @return CMSSignedData Extended CMS signed data
* @throws IOException
* @throws org.bouncycastle.tsp.TSPException
*/
private CMSSignedData signTimeStamps(CMSSignedData signedData) throws IOException, TSPException {
SignerInformationStore signerStore = signedData.getSignerInfos();
List<SignerInformation> newSigners = new ArrayList<>();
for (SignerInformation signer : signerStore.getSigners()) {
newSigners.add(signTimeStamp(signer));
}
// TODO do we have to return a new store?
return CMSSignedData.replaceSigners(signedData, new SignerInformationStore(newSigners));
}
/**
* We are extending CMS Signature
*
* @param signer
* information about signer
* @return information about SignerInformation
*/
private SignerInformation signTimeStamp(SignerInformation signer) throws IOException, TSPException {
AttributeTable unsignedAttributes = signer.getUnsignedAttributes();
ASN1EncodableVector vector = new ASN1EncodableVector();
if (unsignedAttributes != null) {
vector = unsignedAttributes.toASN1EncodableVector();
}
byte[] token = getTsaClient().getTimeStampToken(signer.getSignature());
ASN1ObjectIdentifier oid = PKCSObjectIdentifiers.id_aa_signatureTimeStampToken;
ASN1Encodable signatureTimeStamp = new Attribute(oid, new DERSet(ASN1Primitive.fromByteArray(token)));
vector.add(signatureTimeStamp);
Attributes signedAttributes = new Attributes(vector);
SignerInformation newSigner = SignerInformation.replaceUnsignedAttributes(signer,
new AttributeTable(signedAttributes));
// TODO can this actually happen?
if (newSigner == null) {
return signer;
}
return newSigner;
}
/**
* SignatureInterface implementation.
*
* This method will be called from inside of the pdfbox and create the PKCS
* #7 signature. The given InputStream contains the bytes that are given by
* the byte range.
*
* This method is for internal use only.
*
* Use your favorite cryptographic library to implement PKCS #7 signature
* creation.
*
* @throws IOException
*/
@Override
public byte[] sign(InputStream content) throws IOException {
// TODO this method should be private
try {
List<Certificate> certList = new ArrayList<>();
certList.add(certificate);
Store certs = new JcaCertStore(certList);
CMSSignedDataGenerator gen = new CMSSignedDataGenerator();
org.bouncycastle.asn1.x509.Certificate cert = org.bouncycastle.asn1.x509.Certificate
.getInstance(ASN1Primitive.fromByteArray(certificate.getEncoded()));
ContentSigner sha1Signer = new JcaContentSignerBuilder("SHA256WithRSA").build(privateKey);
gen.addSignerInfoGenerator(
new JcaSignerInfoGeneratorBuilder(new JcaDigestCalculatorProviderBuilder().build())
.build(sha1Signer, new X509CertificateHolder(cert)));
gen.addCertificates(certs);
CMSProcessableInputStream msg = new CMSProcessableInputStream(content);
CMSSignedData signedData = gen.generate(msg, false);
if (tsaClient != null) {
signedData = signTimeStamps(signedData);
}
return signedData.getEncoded();
} catch (GeneralSecurityException | CMSException | TSPException | OperatorCreationException e) {
throw new IOException(e);
}
}
/**
* Set if external signing scenario should be used. If {@code false},
* SignatureInterface would be used for signing.
* <p>
* Default: {@code false}
* </p>
*
* @param externalSigning
* {@code true} if external signing should be performed
*/
public void setExternalSigning(boolean externalSigning) {
this.externalSigning = externalSigning;
}
public boolean isExternalSigning() {
return externalSigning;
}
/**
* Get the access permissions granted for this document in the DocMDP
* transform parameters dictionary. Details are described in the table
* "Entries in the DocMDP transform parameters dictionary" in the PDF
* specification.
*
* @param doc
* document.
* @return the permission value. 0 means no DocMDP transform parameters
* dictionary exists. Other return values are 1, 2 or 3. 2 is also
* returned if the DocMDP transform parameters dictionary is found
* but did not contain a /P entry, or if the value is outside the
* valid range.
*/
public int getMDPPermission(PDDocument doc) {
COSBase base = doc.getDocumentCatalog().getCOSObject().getDictionaryObject(COSName.PERMS);
if (base instanceof COSDictionary) {
COSDictionary permsDict = (COSDictionary) base;
base = permsDict.getDictionaryObject(COSName.DOCMDP);
if (base instanceof COSDictionary) {
COSDictionary signatureDict = (COSDictionary) base;
base = signatureDict.getDictionaryObject("Reference");
if (base instanceof COSArray) {
COSArray refArray = (COSArray) base;
for (int i = 0; i < refArray.size(); ++i) {
base = refArray.getObject(i);
if (base instanceof COSDictionary) {
COSDictionary sigRefDict = (COSDictionary) base;
if (COSName.DOCMDP.equals(sigRefDict.getDictionaryObject("TransformMethod"))) {
base = sigRefDict.getDictionaryObject("TransformParams");
if (base instanceof COSDictionary) {
COSDictionary transformDict = (COSDictionary) base;
int accessPermissions = transformDict.getInt(COSName.P, 2);
if (accessPermissions < 1 || accessPermissions > 3) {
accessPermissions = 2;
}
return accessPermissions;
}
}
}
}
}
}
}
return 0;
}
public void setMDPPermission(PDDocument doc, PDSignature signature, int accessPermissions) {
COSDictionary sigDict = signature.getCOSObject();
// DocMDP specific stuff
COSDictionary transformParameters = new COSDictionary();
transformParameters.setItem(COSName.TYPE, COSName.getPDFName("TransformParams"));
transformParameters.setInt(COSName.P, accessPermissions);
transformParameters.setName(COSName.V, "1.2");
transformParameters.setNeedToBeUpdated(true);
COSDictionary referenceDict = new COSDictionary();
referenceDict.setItem(COSName.TYPE, COSName.getPDFName("SigRef"));
referenceDict.setItem("TransformMethod", COSName.getPDFName("DocMDP"));
referenceDict.setItem("DigestMethod", COSName.getPDFName("SHA1"));
referenceDict.setItem("TransformParams", transformParameters);
referenceDict.setNeedToBeUpdated(true);
COSArray referenceArray = new COSArray();
referenceArray.add(referenceDict);
sigDict.setItem("Reference", referenceArray);
referenceArray.setNeedToBeUpdated(true);
// Catalog
COSDictionary catalogDict = doc.getDocumentCatalog().getCOSObject();
COSDictionary permsDict = new COSDictionary();
catalogDict.setItem(COSName.PERMS, permsDict);
permsDict.setItem(COSName.DOCMDP, signature);
catalogDict.setNeedToBeUpdated(true);
permsDict.setNeedToBeUpdated(true);
}
}