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