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
|
/* ====================================================================
Licensed to the Apache Software Foundation (ASF) under one or more
contributor license agreements. See the NOTICE file distributed with
this work for additional information regarding copyright ownership.
The ASF licenses this file to You under the Apache License, Version 2.0
(the "License"); you may not use this file except in compliance with
the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==================================================================== */
package org.apache.poi.poifs.crypt;
import static org.hamcrest.core.IsEqual.equalTo;
import static org.junit.Assert.assertThat;
import static org.junit.Assert.assertTrue;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.math.BigInteger;
import java.security.GeneralSecurityException;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.KeyStore;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.SecureRandom;
import java.security.cert.Certificate;
import java.security.cert.X509Certificate;
import java.util.Date;
import org.apache.poi.POIDataSamples;
import org.apache.poi.poifs.crypt.agile.AgileDecryptor;
import org.apache.poi.poifs.crypt.agile.AgileEncryptionVerifier;
import org.apache.poi.poifs.filesystem.POIFSFileSystem;
import org.apache.poi.util.IOUtils;
import org.junit.BeforeClass;
import org.junit.Test;
import sun.security.x509.AlgorithmId;
import sun.security.x509.CertificateAlgorithmId;
import sun.security.x509.CertificateIssuerName;
import sun.security.x509.CertificateSerialNumber;
import sun.security.x509.CertificateSubjectName;
import sun.security.x509.CertificateValidity;
import sun.security.x509.CertificateVersion;
import sun.security.x509.CertificateX509Key;
import sun.security.x509.X500Name;
import sun.security.x509.X509CertImpl;
import sun.security.x509.X509CertInfo;
/**
* {@linkplain http://stackoverflow.com/questions/1615871/creating-an-x509-certificate-in-java-without-bouncycastle}
*/
public class TestCertificateEncryption {
/**
* how many days from now the Certificate is valid for
*/
static final int days = 1000;
/**
* the signing algorithm, eg "SHA1withRSA"
*/
static final String algorithm = "SHA1withRSA";
static final String password = "foobaa";
static final String certAlias = "poitest";
/**
* the X.509 Distinguished Name, eg "CN=Test, L=London, C=GB"
*/
static final String certDN = "CN=poitest";
// static final File pfxFile = TempFile.createTempFile("poitest", ".pfx");
static byte pfxFileBytes[];
static class CertData {
KeyPair keypair;
X509Certificate x509;
}
/**
* Create a self-signed X.509 Certificate
*
* The keystore generation / loading is split, because normally the keystore would
* already exist.
*/
@BeforeClass
public static void initKeystore() throws GeneralSecurityException, IOException {
CertData certData = new CertData();
KeyPairGenerator keyGen = KeyPairGenerator.getInstance("RSA");
keyGen.initialize(1024);
certData.keypair = keyGen.generateKeyPair();
PrivateKey privkey = certData.keypair.getPrivate();
PublicKey publkey = certData.keypair.getPublic();
X509CertInfo info = new X509CertInfo();
Date from = new Date();
Date to = new Date(from.getTime() + days * 86400000l);
CertificateValidity interval = new CertificateValidity(from, to);
BigInteger sn = new BigInteger(64, new SecureRandom());
X500Name owner = new X500Name(certDN);
info.set(X509CertInfo.VALIDITY, interval);
info.set(X509CertInfo.SERIAL_NUMBER, new CertificateSerialNumber(sn));
info.set(X509CertInfo.SUBJECT, new CertificateSubjectName(owner));
info.set(X509CertInfo.ISSUER, new CertificateIssuerName(owner));
info.set(X509CertInfo.KEY, new CertificateX509Key(publkey));
info.set(X509CertInfo.VERSION, new CertificateVersion(CertificateVersion.V3));
AlgorithmId algo = new AlgorithmId(AlgorithmId.md5WithRSAEncryption_oid);
info.set(X509CertInfo.ALGORITHM_ID, new CertificateAlgorithmId(algo));
// Sign the cert to identify the algorithm that's used.
X509CertImpl cert = new X509CertImpl(info);
cert.sign(privkey, algorithm);
// Update the algorith, and resign.
algo = (AlgorithmId)cert.get(X509CertImpl.SIG_ALG);
info.set(CertificateAlgorithmId.NAME + "." + CertificateAlgorithmId.ALGORITHM, algo);
cert = new X509CertImpl(info);
cert.sign(privkey, algorithm);
certData.x509 = cert;
KeyStore keystore = KeyStore.getInstance("PKCS12");
keystore.load(null, password.toCharArray());
keystore.setKeyEntry(certAlias, certData.keypair.getPrivate(), password.toCharArray(), new Certificate[]{certData.x509});
ByteArrayOutputStream bos = new ByteArrayOutputStream();
keystore.store(bos, password.toCharArray());
pfxFileBytes = bos.toByteArray();
}
public CertData loadKeystore()
throws GeneralSecurityException, IOException {
KeyStore keystore = KeyStore.getInstance("PKCS12");
InputStream fis = new ByteArrayInputStream(pfxFileBytes);
keystore.load(fis, password.toCharArray());
X509Certificate x509 = (X509Certificate)keystore.getCertificate(certAlias);
PrivateKey privateKey = (PrivateKey)keystore.getKey(certAlias, password.toCharArray());
PublicKey publicKey = x509.getPublicKey();
CertData certData = new CertData();
certData.keypair = new KeyPair(publicKey, privateKey);
certData.x509 = x509;
return certData;
}
@Test
public void testCertificateEncryption() throws Exception {
POIFSFileSystem fs = new POIFSFileSystem();
EncryptionInfo info = new EncryptionInfo(fs, EncryptionMode.agile, CipherAlgorithm.aes192, HashAlgorithm.sha1, -1, -1, ChainingMode.cbc);
AgileEncryptionVerifier aev = (AgileEncryptionVerifier)info.getVerifier();
CertData certData = loadKeystore();
aev.addCertificate(certData.x509);
Encryptor enc = info.getEncryptor();
enc.confirmPassword("foobaa");
File file = POIDataSamples.getDocumentInstance().getFile("VariousPictures.docx");
InputStream fis = new FileInputStream(file);
byte byteExpected[] = IOUtils.toByteArray(fis);
fis.close();
OutputStream os = enc.getDataStream(fs);
IOUtils.copy(new ByteArrayInputStream(byteExpected), os);
os.close();
ByteArrayOutputStream bos = new ByteArrayOutputStream();
fs.writeFilesystem(bos);
bos.close();
fs = new POIFSFileSystem(new ByteArrayInputStream(bos.toByteArray()));
info = new EncryptionInfo(fs);
AgileDecryptor agDec = (AgileDecryptor)info.getDecryptor();
boolean passed = agDec.verifyPassword(certData.keypair, certData.x509);
assertTrue("certificate verification failed", passed);
fis = agDec.getDataStream(fs);
byte byteActual[] = IOUtils.toByteArray(fis);
fis.close();
assertThat(byteExpected, equalTo(byteActual));
}
}
|