2 * Copyright 2018 Intel Corporation, Inc
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
8 * http://www.apache.org/licenses/LICENSE-2.0
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
16 import java.security.*;
17 import sun.security.pkcs11.*;
18 import javax.crypto.spec.SecretKeySpec;
20 import sun.security.pkcs11.*;
21 import java.security.interfaces.*;
22 import javax.net.ssl.*;
23 import javax.crypto.spec.*;
25 import java.security.cert.*;
26 import java.security.spec.*;
27 import sun.security.x509.*;
28 import java.security.KeyStore.PrivateKeyEntry;
30 import java.io.ByteArrayInputStream;
31 import java.io.IOException;
32 import java.math.BigInteger;
33 import java.security.InvalidKeyException;
34 import java.security.Key;
35 import java.security.KeyManagementException;
36 import java.security.KeyPair;
37 import java.security.KeyPairGenerator;
38 import java.security.KeyStore;
39 import java.security.KeyStoreException;
40 import java.security.NoSuchAlgorithmException;
41 import java.security.NoSuchProviderException;
42 import java.security.PrivateKey;
43 import java.security.PublicKey;
44 import java.security.SecureRandom;
45 import java.security.Security;
46 import java.security.SignatureException;
47 import java.security.UnrecoverableKeyException;
48 import java.security.cert.Certificate;
49 import java.security.cert.CertificateException;
50 import java.security.cert.X509Certificate;
51 import java.util.Date;
52 import java.util.Random;
54 import org.bouncycastle.pkcs.PKCS10CertificationRequest;
55 import org.bouncycastle.asn1.ASN1EncodableVector;
56 import org.bouncycastle.asn1.ASN1InputStream;
57 import org.bouncycastle.asn1.ASN1Sequence;
58 import org.bouncycastle.asn1.DERSequence;
59 import org.bouncycastle.asn1.x500.X500Name;
60 import org.bouncycastle.asn1.x500.X500NameBuilder;
61 import org.bouncycastle.asn1.x500.style.BCStyle;
62 import org.bouncycastle.asn1.x509.BasicConstraints;
63 import org.bouncycastle.asn1.x509.Extension;
64 import org.bouncycastle.asn1.x509.KeyPurposeId;
65 import org.bouncycastle.asn1.x509.KeyUsage;
66 import org.bouncycastle.asn1.x509.SubjectKeyIdentifier;
67 import org.bouncycastle.asn1.x509.SubjectPublicKeyInfo;
68 import org.bouncycastle.cert.CertIOException;
69 import org.bouncycastle.cert.X509CertificateHolder;
70 import org.bouncycastle.cert.X509v3CertificateBuilder;
71 import org.bouncycastle.cert.bc.BcX509ExtensionUtils;
72 import org.bouncycastle.cert.jcajce.JcaX509CertificateConverter;
73 import org.bouncycastle.cert.jcajce.JcaX509v3CertificateBuilder;
74 import org.bouncycastle.jce.provider.BouncyCastleProvider;
75 import org.bouncycastle.operator.ContentSigner;
76 import org.bouncycastle.operator.OperatorCreationException;
77 import org.bouncycastle.operator.jcajce.JcaContentSignerBuilder;
78 import org.bouncycastle.asn1.x509.SubjectPublicKeyInfo;
79 import org.bouncycastle.util.io.pem.PemReader;
80 import org.bouncycastle.util.io.pem.PemObject;
81 import org.bouncycastle.asn1.pkcs.CertificationRequest;
82 import org.bouncycastle.asn1.x509.ExtendedKeyUsage;
83 import org.bouncycastle.asn1.x509.Extension;
84 import org.bouncycastle.asn1.x509.GeneralName;
85 import org.bouncycastle.asn1.x509.GeneralNames;
86 import org.bouncycastle.cert.jcajce.JcaX509ExtensionUtils;
88 import javax.xml.bind.DatatypeConverter;
89 import java.security.cert.X509Certificate;
90 import java.io.StringWriter;
92 import java.nio.file.Files;
93 import java.nio.file.Path;
94 import java.nio.file.Paths;
95 import static java.nio.file.StandardCopyOption.*;
97 class ThreadDemo extends Thread {
98 private String threadName;
99 private PrivateKey key;
100 private X509Certificate caCert;
102 ThreadDemo( String name, PrivateKey privateKey, X509Certificate cacert) {
108 public static final KeyPurposeId[] ASN_WebUsage = new KeyPurposeId[] {
109 KeyPurposeId.id_kp_serverAuth,
110 KeyPurposeId.id_kp_clientAuth};
114 System.out.println("Running " + threadName);
116 String threadname = threadName+".csr";
117 System.out.println(threadName);
118 File csrf = new File(threadname);
119 Reader pemcsr = new FileReader(csrf);
120 PemReader reader = new PemReader(pemcsr);
121 PemObject pem = reader.readPemObject();
122 PKCS10CertificationRequest csr = new PKCS10CertificationRequest(pem.getContent());
124 X500NameBuilder x500NameBld = new X500NameBuilder(BCStyle.INSTANCE);
125 x500NameBld.addRDN(BCStyle.C, "US");
126 x500NameBld.addRDN(BCStyle.ST, "CA");
127 x500NameBld.addRDN(BCStyle.L, "local");
128 x500NameBld.addRDN(BCStyle.O, "onap");
129 x500NameBld.addRDN(BCStyle.CN, "test.onap.ca");
130 X500Name issuer = x500NameBld.build();
132 GregorianCalendar gc = new GregorianCalendar();
133 Date start = gc.getTime();
134 gc.add(GregorianCalendar.DAY_OF_MONTH, 1000);
135 Date end = gc.getTime();
137 X509Certificate x509;
138 byte[] serialish = new byte[24];
139 SecureRandom random = new SecureRandom();
141 bi = new BigInteger(serialish);
142 X509v3CertificateBuilder xcb = new X509v3CertificateBuilder(issuer, bi,
143 start, end, csr.getSubject(), csr.getSubjectPublicKeyInfo());
145 JcaX509ExtensionUtils extUtils = new JcaX509ExtensionUtils();
146 xcb.addExtension(Extension.basicConstraints,
147 false, new BasicConstraints(false))
148 .addExtension(Extension.keyUsage,
149 true, new KeyUsage(KeyUsage.digitalSignature
150 | KeyUsage.keyEncipherment))
151 .addExtension(Extension.extendedKeyUsage,
152 true, new ExtendedKeyUsage(ASN_WebUsage))
154 .addExtension(Extension.authorityKeyIdentifier,
155 false, extUtils.createAuthorityKeyIdentifier(caCert))
156 .addExtension(Extension.subjectKeyIdentifier,
157 false, extUtils.createSubjectKeyIdentifier(caCert.getPublicKey()));
159 ContentSigner sigGen = new JcaContentSignerBuilder("SHA256WithRSA").build(key);
161 x509 = new JcaX509CertificateConverter().getCertificate(xcb.build(sigGen));
162 StringWriter sw = new StringWriter();
163 sw.write("-----BEGIN CERTIFICATE-----\n");
164 sw.write(DatatypeConverter.printBase64Binary(x509.getEncoded()).replaceAll("(.{64})", "$1\n"));
165 sw.write("\n-----END CERTIFICATE-----\n");
166 FileWriter fw = new FileWriter(threadName +".cert");
167 fw.write(sw.toString());
170 System.out.println("Done - Signed certificate is "+ threadName +".cert");
171 System.out.println("Thread: " + threadName);
173 catch (Exception e) {
174 System.out.println("Thread " + threadName + " interrupted.");
178 System.out.println("Thread " + threadName + " exiting." + " upon Successful completion");
182 public class CaSignMultiThread {
184 public static void main(String[] args) throws Exception {
186 if ( args.length < 2 )
187 System.out.println("Arguments mismatch, Usage: CaSign <pin> <alias>");
188 for(int i = 0; i < args.length; i++) {
189 System.out.println(args[i]);
191 // Set up the Sun PKCS 11 provider
192 String configName = "pkcs11.cfg";
193 Provider p = new SunPKCS11(configName);
194 //Provider p = Security.getProvider("SunPKCS11-pkcs11Test");
196 throw new RuntimeException("could not get security provider for");
198 Security.addProvider(p);
199 // Load the key store
200 char[] pin = args[0].toCharArray();
201 KeyStore keyStore = KeyStore.getInstance("PKCS11", p);
202 keyStore.load(null, pin);
204 Enumeration<String> aliases = keyStore.aliases();
205 while(aliases.hasMoreElements()){
206 String alias = aliases.nextElement();
207 System.out.println(alias + ": " + keyStore.getKey(alias,args[0].toCharArray()));
209 PrivateKeyEntry privateKeyEntry = (PrivateKeyEntry) keyStore.getEntry(args[1], null);
210 PrivateKey privateKey = privateKeyEntry.getPrivateKey();
212 X509Certificate caCert = (X509Certificate) privateKeyEntry.getCertificate();
213 RSAPublicKey publicKey = (RSAPublicKey) caCert.getPublicKey();
215 Security.addProvider(new BouncyCastleProvider());
217 // Set the number of thread that application need to create
219 ThreadDemo[] T = new ThreadDemo[threadCount];
221 for (int i = 0; i<threadCount; i++) {
223 String command0 = "./gencsr.sh "+ i;
224 System.out.println(command0);
226 Process p0 = Runtime.getRuntime().exec(command0);
227 BufferedReader stdInput = new BufferedReader(new
228 InputStreamReader(p0.getInputStream()));
229 BufferedReader stdError = new BufferedReader(new
230 InputStreamReader(p0.getErrorStream()));
231 } catch (IOException e) {
232 System.out.println("The Error is : ");
237 String command1 = "chmod 777 *.csr";
238 System.out.println(command1);
240 Process p1 = Runtime.getRuntime().exec(command1);
241 BufferedReader stdInput = new BufferedReader(new
242 InputStreamReader(p1.getInputStream()));
243 BufferedReader stdError = new BufferedReader(new
244 InputStreamReader(p1.getErrorStream()));
245 } catch (IOException e) {
246 System.out.println("The Error is : ");
250 for (int i = 0; i<threadCount; i++) {
252 T[i] = new ThreadDemo("Thread" + Integer.toString(i), privateKey, caCert);
254 System.out.println("THe threads are started with execution");
257 int count = Thread.activeCount();
258 System.out.println("-------------currently active threads = " + count);
260 for (int i = 0; i<threadCount; i++) {
262 System.out.println("The Threads are being joined");
265 String command2 = "chmod 777 *.cert";
266 System.out.println(command2);
269 Process p2 = Runtime.getRuntime().exec(command2);
270 BufferedReader stdInput = new BufferedReader(new
271 InputStreamReader(p2.getInputStream()));
272 BufferedReader stdError = new BufferedReader(new
273 InputStreamReader(p2.getErrorStream()));
275 catch (IOException e) {
276 System.out.println("The Error is : ");
280 for (int i = 0; i<threadCount; i++) {
282 String command3 = "openssl verify -verbose -CAfile ca.cert " + "Thread" + Integer.toString(i) + ".cert";
284 Process p3 = Runtime.getRuntime().exec(command3);
286 BufferedReader stdInput = new BufferedReader(new
287 InputStreamReader(p3.getInputStream()));
289 BufferedReader stdError = new BufferedReader(new
290 InputStreamReader(p3.getErrorStream()));
292 // read the output from the command
293 while ((command3 = stdInput.readLine()) != null) {
294 System.out.println(command3);
296 // read any errors from the attempted command
297 while ((command3 = stdError.readLine()) != null) {
298 System.out.println(command3);
299 System.out.println("Here is the standard error of the command (if any):\n");
301 } catch (IOException e) {
302 System.out.println("The exception is ");