1 /*******************************************************************************
2 * ============LICENSE_START====================================================
4 * * ===========================================================================
5 * * Copyright © 2017 AT&T Intellectual Property. All rights reserved.
6 * * ===========================================================================
7 * * Licensed under the Apache License, Version 2.0 (the "License");
8 * * you may not use this file except in compliance with the License.
9 * * You may obtain a copy of the License at
11 * * http://www.apache.org/licenses/LICENSE-2.0
13 * * Unless required by applicable law or agreed to in writing, software
14 * * distributed under the License is distributed on an "AS IS" BASIS,
15 * * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16 * * See the License for the specific language governing permissions and
17 * * limitations under the License.
18 * * ============LICENSE_END====================================================
21 ******************************************************************************/
22 package org.onap.aaf.cadi.cm.test;
24 import static org.junit.Assert.*;
25 import static org.hamcrest.CoreMatchers.*;
26 import static org.mockito.Mockito.*;
30 import java.io.BufferedReader;
32 import java.io.FileInputStream;
33 import java.io.FileReader;
34 import java.io.IOException;
35 import java.io.PrintWriter;
36 import java.nio.charset.StandardCharsets;
37 import java.security.cert.Certificate;
38 import java.security.cert.CertificateEncodingException;
39 import java.security.cert.CertificateException;
40 import java.security.cert.X509Certificate;
41 import java.security.KeyPair;
42 import java.security.Principal;
43 import java.security.PrivateKey;
44 import java.security.PublicKey;
45 import java.util.ArrayList;
46 import java.util.Collection;
47 import java.util.List;
49 import javax.crypto.Cipher;
51 import org.onap.aaf.cadi.cm.CertException;
52 import org.onap.aaf.cadi.cm.Factory;
53 import org.onap.aaf.cadi.cm.Factory.StripperInputStream;
55 import org.onap.aaf.misc.env.Env;
56 import org.onap.aaf.misc.env.LogTarget;
57 import org.onap.aaf.misc.env.TimeTaken;
58 import org.onap.aaf.misc.env.Trans;
60 public class JU_Factory {
66 TimeTaken timeTakenMock;
69 LogTarget logTargetMock;
72 X509Certificate x509CertMock;
80 private final String resourceDirName = "src/test/resources";
81 private File resourceDir;
82 private File publicKeyFile;
83 private File privateKeyFile;
84 private File certFile;
86 private static final String message = "The quick brown fox jumps over the lazy dog.";
88 private static final String subjectDNText = "subjectDN";
89 private static final String certText = "Some text that might be included in a certificate";
92 public void setup() throws CertificateEncodingException {
93 MockitoAnnotations.initMocks(this);
95 resourceDir = new File(resourceDirName);
97 publicKeyFile = new File(resourceDirName, "/publicKey");
98 privateKeyFile = new File(resourceDirName, "/privateKey");
99 publicKeyFile.delete();
100 privateKeyFile.delete();
102 certFile = new File(resourceDirName + "/exampleCertificate.cer");
104 when(transMock.start(anyString(), anyInt())).thenReturn(timeTakenMock);
105 when(transMock.debug()).thenReturn(logTargetMock);
107 when(subjectDN.toString()).thenReturn(subjectDNText);
109 when(x509CertMock.getSubjectDN()).thenReturn(subjectDN);
110 when(x509CertMock.getEncoded()).thenReturn(certText.getBytes());
112 when(certMock.getEncoded()).thenReturn(certText.getBytes());
116 public void tearDown() {
117 publicKeyFile = new File(resourceDirName, "/publicKey");
118 privateKeyFile = new File(resourceDirName, "/privateKey");
119 publicKeyFile.delete();
120 privateKeyFile.delete();
122 if (resourceDir.list().length == 0) {
123 resourceDir.delete();
128 public void generateKeyPairTest() throws Exception {
129 // This instatiation isn't actually necessary, but it gets coverage
130 Cipher encryptor = Factory.pkCipher();
131 Cipher decryptor = Factory.pkCipher();
133 KeyPair kp1 = Factory.generateKeyPair(transMock);
134 encryptor = Factory.pkCipher(kp1.getPublic(), true);
135 decryptor = Factory.pkCipher(kp1.getPrivate(), false);
136 byte[] encrypedMessage1 = encryptor.doFinal(message.getBytes(StandardCharsets.UTF_8));
137 String output1 = new String(decryptor.doFinal(encrypedMessage1));
138 assertThat(output1, is(message));
141 when(transMock.start("Generate KeyPair", Env.SUB)).thenReturn(null);
142 KeyPair kp2 = Factory.generateKeyPair(transMock);
143 encryptor = Factory.pkCipher(kp2.getPublic(), true);
144 decryptor = Factory.pkCipher(kp2.getPrivate(), false);
145 byte[] encrypedMessage2 = encryptor.doFinal(message.getBytes(StandardCharsets.UTF_8));
146 String output2 = new String(decryptor.doFinal(encrypedMessage2));
147 assertThat(output2, is(message));
149 KeyPair kp3 = Factory.generateKeyPair(null);
150 encryptor = Factory.pkCipher(kp3.getPublic(), true);
151 decryptor = Factory.pkCipher(kp3.getPrivate(), false);
152 byte[] encrypedMessage3 = encryptor.doFinal(message.getBytes(StandardCharsets.UTF_8));
153 String output3 = new String(decryptor.doFinal(encrypedMessage3));
154 assertThat(output3, is(message));
158 public void keyStringManipTest() throws Exception {
159 KeyPair kp = Factory.generateKeyPair(transMock);
161 String publicKeyString = Factory.toString(transMock, kp.getPublic());
162 String privateKeyString = Factory.toString(transMock, kp.getPrivate());
164 assertThat(publicKeyString.startsWith("-----BEGIN PUBLIC KEY-----"), is(true));
165 assertThat(publicKeyString.endsWith("-----END PUBLIC KEY-----\n"), is(true));
167 assertThat(privateKeyString.startsWith("-----BEGIN PRIVATE KEY-----"), is(true));
168 assertThat(privateKeyString.endsWith("-----END PRIVATE KEY-----\n"), is(true));
170 PublicKey publicKey = Factory.toPublicKey(transMock, cleanupString(publicKeyString));
171 PrivateKey privateKey = Factory.toPrivateKey(transMock, cleanupString(privateKeyString));
173 Cipher encryptor = Factory.pkCipher(publicKey, true);
174 Cipher decryptor = Factory.pkCipher(privateKey, false);
175 byte[] encrypedMessage = encryptor.doFinal(message.getBytes(StandardCharsets.UTF_8));
176 String output = new String(decryptor.doFinal(encrypedMessage));
177 assertThat(output, is(message));
181 public void keyFileManipTest() throws Exception {
182 KeyPair kp = Factory.generateKeyPair(transMock);
184 String privateKeyString = Factory.toString(transMock, kp.getPrivate());
185 writeToFile(privateKeyFile, privateKeyString, "Header:this line has a header");
187 PublicKey publicKey = kp.getPublic();
188 PrivateKey privateKey = Factory.toPrivateKey(transMock, privateKeyFile);
190 Cipher encryptor = Factory.pkCipher(publicKey, true);
191 Cipher decryptor = Factory.pkCipher(privateKey, false);
192 byte[] encrypedMessage = encryptor.doFinal(message.getBytes(StandardCharsets.UTF_8));
193 String output = new String(decryptor.doFinal(encrypedMessage));
194 assertThat(output, is(message));
198 public void certToStringTest() throws IOException, CertException, CertificateEncodingException {
200 when(logTargetMock.isLoggable()).thenReturn(true);
202 certString = Factory.toString(transMock, x509CertMock);
203 assertThat(certString.startsWith("-----BEGIN CERTIFICATE-----"), is(true));
204 assertThat(certString.endsWith("-----END CERTIFICATE-----\n"), is(true));
206 certString = Factory.toString(transMock, certMock);
207 assertThat(certString.startsWith("-----BEGIN CERTIFICATE-----"), is(true));
208 assertThat(certString.endsWith("-----END CERTIFICATE-----\n"), is(true));
211 certString = Factory.toString(transMock, (Certificate)null);
212 fail("Should have thrown an exception");
213 } catch (CertException e) {
214 assertThat(e.getMessage(), is("Certificate not built"));
217 when(certMock.getEncoded()).thenThrow(new CertificateEncodingException());
219 certString = Factory.toString(transMock, certMock);
220 fail("Should have thrown an exception");
221 } catch (CertException e) {
225 when(logTargetMock.isLoggable()).thenReturn(false);
226 certString = Factory.toString(transMock, x509CertMock);
230 public void toX509Test() throws CertificateException, IOException, CertException {
232 Collection<? extends Certificate> certs;
233 when(logTargetMock.isLoggable()).thenReturn(true);
235 String certString = readFromFile(certFile, false);
237 certs = Factory.toX509Certificate(certString);
238 // Contrived way of getting a Certificate out of a Collection
239 output = Factory.toString(transMock, certs.toArray(new Certificate[0])[0]);
240 assertThat(output, is(certString));
242 certs = Factory.toX509Certificate(transMock, certFile);
243 // Contrived way of getting a Certificate out of a Collection
244 output = Factory.toString(transMock, certs.toArray(new Certificate[0])[0]);
245 assertThat(output, is(certString));
247 List<String> certStrings = new ArrayList<String>();
248 certStrings.add(certString);
249 certStrings.add(certString);
250 certs = Factory.toX509Certificate(certStrings);
251 // Contrived way of getting a Certificate out of a Collection
252 // it doesn't matter which one we get - they're the same
253 output = Factory.toString(transMock, certs.toArray(new Certificate[0])[0]);
254 assertThat(output, is(certString));
258 public void stripperTest() throws Exception {
259 KeyPair kp = Factory.generateKeyPair(transMock);
260 String privateKeyString = Factory.toString(transMock, kp.getPrivate());
261 writeToFile(privateKeyFile, privateKeyString, "Header:this line has a header");
263 StripperInputStream stripper = new StripperInputStream(privateKeyFile);
265 String expected = cleanupString(privateKeyString);
266 byte[] buffer = new byte[10000];
267 stripper.read(buffer);
268 String output = new String(buffer, 0, expected.length());
269 assertThat(output, is(expected));
273 stripper = new StripperInputStream(new FileInputStream(privateKeyFile));
275 stripper = new StripperInputStream(new BufferedReader(new FileReader(privateKeyFile)));
277 stripper.close(); // also coverage...
281 public void binaryTest() throws IOException {
282 String output = new String(Factory.binary(certFile));
283 String expected = readFromFile(certFile, true);
284 assertThat(output, is(expected));
288 public void signatureTest() throws Exception {
289 KeyPair kp = Factory.generateKeyPair(transMock);
290 String signedString = "Something that needs signing";
291 byte[] signedBytes = Factory.sign(transMock, signedString.getBytes(), kp.getPrivate());
292 String output = Factory.toSignatureString(signedBytes);
293 assertThat(output.startsWith("-----BEGIN SIGNATURE-----"), is(true));
294 assertThat(output.endsWith("-----END SIGNATURE-----\n"), is(true));
295 assertThat(Factory.verify(transMock, signedString.getBytes(), signedBytes, kp.getPublic()), is(true));
298 // TODO: Ian - finish these tests
300 // public void base64ISTest() throws Exception {
301 // KeyPair kp = Factory.generateKeyPair(transMock);
303 // String privateKeyString = Factory.toString(transMock, kp.getPrivate());
304 // String cleaned = cleanupString(privateKeyString);
305 // System.out.println(cleaned);
306 // writeToFile(privateKeyFile, cleaned);
307 // Base64InputStream b64is = new Base64InputStream(privateKeyFile);
308 // byte[] buffer = new byte[10000];
309 // b64is.read(buffer);
310 // System.out.println(new String(buffer));
315 // public void getSecurityProviderTest() {
318 private String cleanupString(String str) {
319 String[] lines = str.split("\n", 0);
320 List<String> rawLines = new ArrayList<String>();
321 for (int i = 0; i < lines.length - 2; i++) {
322 rawLines.add(lines[i + 1]);
324 return join("", rawLines);
328 * Note: String.join is not part of JDK 7, which is what we compile to for CADI
330 private String join(String delim, List<String> rawLines) {
331 StringBuilder sb = new StringBuilder();
332 boolean first = true;
333 for(String s : rawLines) {
341 return sb.toString();
344 private void writeToFile(File file, String contents, String header) throws Exception {
345 PrintWriter writer = new PrintWriter(file, "UTF-8");
346 if (header != null) {
347 writer.println(header);
349 writer.println(contents);
353 private String readFromFile(File file, boolean addCR) throws IOException {
354 BufferedReader br = new BufferedReader(new FileReader(file));
355 StringBuilder sb = new StringBuilder();
357 while ((line = br.readLine()) != null) {
358 String lineEnd = (addCR) ? "\r\n" : "\n";
359 sb.append(line + lineEnd);
362 return sb.toString();