1 /*
2  * Copyright (c) 2006, 2018, Oracle and/or its affiliates. All rights reserved.
3  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
4  *
5  * This code is free software; you can redistribute it and/or modify it
6  * under the terms of the GNU General Public License version 2 only, as
7  * published by the Free Software Foundation.
8  *
9  * This code is distributed in the hope that it will be useful, but WITHOUT
10  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
11  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
12  * version 2 for more details (a copy is included in the LICENSE file that
13  * accompanied this code).
14  *
15  * You should have received a copy of the GNU General Public License version
16  * 2 along with this work; if not, write to the Free Software Foundation,
17  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
18  *
19  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
20  * or visit www.oracle.com if you need additional information or have any
21  * questions.
22  */
23 
24 /*
25  * @test
26  * @bug 6405536
27  * @summary Verify that we can parse ECPrivateKeys from PKCS#12 and use them
28  * @author Andreas Sterbenz
29  * @library /test/lib ..
30  * @library ../../../../java/security/testlibrary
31  * @key randomness
32  * @modules jdk.crypto.cryptoki
33  * @run main/othervm ReadPKCS12
34  * @run main/othervm ReadPKCS12 sm policy
35  */
36 
37 import java.io.BufferedReader;
38 import java.io.File;
39 import java.io.FileInputStream;
40 import java.io.FileOutputStream;
41 import java.io.FileReader;
42 import java.io.InputStream;
43 import java.io.OutputStream;
44 import java.security.KeyStore;
45 import java.security.PrivateKey;
46 import java.security.Provider;
47 import java.security.PublicKey;
48 import java.security.Signature;
49 import java.security.cert.Certificate;
50 import java.security.cert.CertificateException;
51 import java.security.cert.CertificateFactory;
52 import java.security.cert.X509Certificate;
53 import java.util.Collections;
54 import java.util.HashMap;
55 import java.util.List;
56 import java.util.Map;
57 import java.util.Random;
58 
59 public class ReadPKCS12 extends PKCS11Test {
60 
61     private final static boolean COPY = false;
62 
main(String[] args)63     public static void main(String[] args) throws Exception {
64         main(new ReadPKCS12(), args);
65     }
66 
67     @Override
main(Provider p)68     public void main(Provider p) throws Exception {
69         if (p.getService("Signature", "SHA1withECDSA") == null) {
70             System.out.println("Provider does not support ECDSA, skipping...");
71             return;
72         }
73 
74         /*
75          * PKCS11Test.main will remove this provider if needed
76          */
77         Providers.setAt(p, 1);
78 
79         CertificateFactory factory = CertificateFactory.getInstance("X.509");
80         try {
81             // undocumented way to clear the Sun internal certificate cache
82             factory.generateCertificate(null);
83         } catch (CertificateException e) {
84             // ignore
85         }
86 
87         KeyStore ks2;
88         if (COPY) {
89             ks2 = KeyStore.getInstance("JKS");
90             try (InputStream in = new FileInputStream("keystore.old")) {
91                 ks2.load(in, "passphrase".toCharArray());
92             }
93         }
94 
95         File dir = new File(BASE, "pkcs12");
96         File closedDir = new File(CLOSED_BASE, "pkcs12");
97 
98         Map<String,char[]> passwords = new HashMap<>();
99         try (BufferedReader reader = new BufferedReader(
100                 new FileReader(new File(BASE, "p12passwords.txt")))) {
101             while (true) {
102                 String line = reader.readLine();
103                 if (line == null) {
104                     break;
105                 }
106                 line = line.trim();
107                 if ((line.length() == 0) || line.startsWith("#")) {
108                     continue;
109                 }
110                 String[] s = line.split(" ");
111                 passwords.put(s[0], s[1].toCharArray());
112             }
113         }
114 
115         for (File file : concat(dir.listFiles(), closedDir.listFiles())) {
116             String name = file.getName();
117             if (file.isFile() == false) {
118                 continue;
119             }
120             System.out.println();
121             System.out.println("Reading " + name + "...");
122 
123             char[] password = passwords.get(name);
124             if (password == null) {
125                 password = passwords.get("*");
126             }
127 
128             KeyStore ks;
129             try (InputStream in = new FileInputStream(file)) {
130                 ks = KeyStore.getInstance("PKCS12");
131                 ks.load(in, password);
132             }
133             List<String> aliases = Collections.list(ks.aliases());
134             System.out.println("Aliases: " + aliases);
135 
136             for (String alias : aliases) {
137                 PrivateKey privateKey = (PrivateKey)ks.getKey(alias, password);
138                 Certificate[] certs = ks.getCertificateChain(alias);
139                 PublicKey publicKey = certs[0].getPublicKey();
140                 System.out.println("Certificates: " + certs.length);
141                 System.out.println(privateKey);
142                 System.out.println(publicKey);
143                 if (COPY) {
144                     ks2.setKeyEntry(alias, privateKey, "passphrase".toCharArray(), certs);
145                 }
146 
147                 verifyCerts(certs);
148 
149                 Random random = new Random();
150                 byte[] data = new byte[1024];
151                 random.nextBytes(data);
152 
153                 Signature s = Signature.getInstance("SHA1withECDSA");
154                 s.initSign(privateKey);
155                 s.update(data);
156                 byte[] sig = s.sign();
157 
158                 s.initVerify(publicKey);
159                 s.update(data);
160                 if (s.verify(sig) == false) {
161                     throw new Exception("Signature does not verify");
162                 }
163                 System.out.println("Verified public/private key match");
164             }
165         }
166 
167         if (COPY) {
168             try (OutputStream out = new FileOutputStream("keystore.new")) {
169                 ks2.store(out, "passphrase".toCharArray());
170             }
171         }
172 
173         System.out.println("OK");
174     }
175 
verifyCerts(Certificate[] certs)176     private static void verifyCerts(Certificate[] certs) throws Exception {
177         int n = certs.length;
178         for (int i = 0; i < n - 1; i++) {
179             X509Certificate cert = (X509Certificate)certs[i];
180             X509Certificate issuer = (X509Certificate)certs[i + 1];
181             if (cert.getIssuerX500Principal().equals(issuer.getSubjectX500Principal()) == false) {
182                 throw new Exception("Certificates do not chain");
183             }
184             cert.verify(issuer.getPublicKey());
185             System.out.println("Verified: " + cert.getSubjectX500Principal());
186         }
187         X509Certificate last = (X509Certificate)certs[n - 1];
188         // if self-signed, verify the final cert
189         if (last.getIssuerX500Principal().equals(last.getSubjectX500Principal())) {
190             last.verify(last.getPublicKey());
191             System.out.println("Verified: " + last.getSubjectX500Principal());
192         }
193     }
194 
195 }
196