1 /*
   2  * Copyright (c) 2006, 2007, 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 ..
  30  */
  31 
  32 import java.io.*;
  33 import java.util.*;
  34 
  35 import java.security.*;
  36 import java.security.interfaces.*;
  37 import java.security.cert.*;
  38 import java.security.cert.Certificate;
  39 
  40 import javax.security.auth.x500.X500Principal;
  41 
  42 public class ReadPKCS12 extends PKCS11Test {
  43 
  44     private final static boolean COPY = false;
  45 
  46     public static void main(String[] args) throws Exception {
  47         main(new ReadPKCS12());
  48     }
  49 
  50     public void main(Provider p) throws Exception {
  51         if (p.getService("Signature", "SHA1withECDSA") == null) {
  52             System.out.println("Provider does not support ECDSA, skipping...");
  53             return;
  54         }
  55         Security.insertProviderAt(p, 1);
  56 
  57         CertificateFactory factory = CertificateFactory.getInstance("X.509");
  58         try {
  59             // undocumented way to clear the Sun internal certificate cache
  60             factory.generateCertificate(null);
  61         } catch (CertificateException e) {
  62             // ignore
  63         }
  64 
  65         KeyStore ks2;
  66         if (COPY) {
  67             ks2 = KeyStore.getInstance("JKS");
  68             InputStream in = new FileInputStream("keystore.old");
  69             ks2.load(in, "passphrase".toCharArray());
  70             in.close();
  71         }
  72 
  73         File dir = new File(BASE, "pkcs12");
  74         File closedDir = new File(CLOSED_BASE, "pkcs12");
  75 
  76         Map<String,char[]> passwords = new HashMap<String,char[]>();
  77         BufferedReader reader = new BufferedReader(new FileReader((new File(BASE, "p12passwords.txt"))));
  78         while (true) {
  79             String line = reader.readLine();
  80             if (line == null) {
  81                 break;
  82             }
  83             line = line.trim();
  84             if ((line.length() == 0) || line.startsWith("#")) {
  85                 continue;
  86             }
  87             String[] s = line.split(" ");
  88             passwords.put(s[0], s[1].toCharArray());
  89         }
  90         reader.close();
  91 
  92         for (File file : concat(dir.listFiles(), closedDir.listFiles())) {
  93             String name = file.getName();
  94             if (file.isFile() == false) {
  95                 continue;
  96             }
  97             System.out.println();
  98             System.out.println("Reading " + name + "...");
  99 
 100             char[] password = passwords.get(name);
 101             if (password == null) {
 102                 password = passwords.get("*");
 103             }
 104 
 105             InputStream in = new FileInputStream(file);
 106             KeyStore ks = KeyStore.getInstance("PKCS12");
 107             ks.load(in, password);
 108             in.close();
 109             List<String> aliases = Collections.list(ks.aliases());
 110             System.out.println("Aliases: " + aliases);
 111 
 112             for (String alias : aliases) {
 113                 PrivateKey privateKey = (PrivateKey)ks.getKey(alias, password);
 114                 Certificate[] certs = ks.getCertificateChain(alias);
 115                 PublicKey publicKey = certs[0].getPublicKey();
 116                 System.out.println("Certificates: " + certs.length);
 117                 System.out.println(privateKey);
 118                 System.out.println(publicKey);
 119                 if (COPY) {
 120                     ks2.setKeyEntry(alias, privateKey, "passphrase".toCharArray(), certs);
 121                 }
 122 
 123                 verifyCerts(certs);
 124 
 125                 Random random = new Random();
 126                 byte[] data = new byte[1024];
 127                 random.nextBytes(data);
 128 
 129                 Signature s = Signature.getInstance("SHA1withECDSA");
 130                 s.initSign(privateKey);
 131                 s.update(data);
 132                 byte[] sig = s.sign();
 133 
 134                 s.initVerify(publicKey);
 135                 s.update(data);
 136                 if (s.verify(sig) == false) {
 137                     throw new Exception("Signature does not verify");
 138                 }
 139                 System.out.println("Verified public/private key match");
 140             }
 141         }
 142 
 143         if (COPY) {
 144             OutputStream out = new FileOutputStream("keystore.new");
 145             ks2.store(out, "passphrase".toCharArray());
 146             out.close();
 147         }
 148 
 149         Security.removeProvider(p.getName());
 150         System.out.println("OK");
 151     }
 152 
 153     private static void verifyCerts(Certificate[] certs) throws Exception {
 154         int n = certs.length;
 155         for (int i = 0; i < n - 1; i++) {
 156             X509Certificate cert = (X509Certificate)certs[i];
 157             X509Certificate issuer = (X509Certificate)certs[i + 1];
 158             if (cert.getIssuerX500Principal().equals(issuer.getSubjectX500Principal()) == false) {
 159                 throw new Exception("Certificates do not chain");
 160             }
 161             cert.verify(issuer.getPublicKey());
 162             System.out.println("Verified: " + cert.getSubjectX500Principal());
 163         }
 164         X509Certificate last = (X509Certificate)certs[n - 1];
 165         // if self-signed, verify the final cert
 166         if (last.getIssuerX500Principal().equals(last.getSubjectX500Principal())) {
 167             last.verify(last.getPublicKey());
 168             System.out.println("Verified: " + last.getSubjectX500Principal());
 169         }
 170     }
 171 
 172 }