Path: blob/master/src/java.base/share/classes/sun/security/tools/KeyStoreUtil.java
41159 views
/*1* Copyright (c) 2005, 2020, Oracle and/or its affiliates. All rights reserved.2* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.3*4* This code is free software; you can redistribute it and/or modify it5* under the terms of the GNU General Public License version 2 only, as6* published by the Free Software Foundation. Oracle designates this7* particular file as subject to the "Classpath" exception as provided8* by Oracle in the LICENSE file that accompanied this code.9*10* This code is distributed in the hope that it will be useful, but WITHOUT11* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or12* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License13* version 2 for more details (a copy is included in the LICENSE file that14* accompanied this code).15*16* You should have received a copy of the GNU General Public License version17* 2 along with this work; if not, write to the Free Software Foundation,18* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.19*20* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA21* or visit www.oracle.com if you need additional information or have any22* questions.23*/2425package sun.security.tools;262728import java.io.BufferedReader;29import java.io.File;30import java.io.FileInputStream;31import java.io.IOException;32import java.io.InputStreamReader;3334import java.io.StreamTokenizer;35import java.io.StringReader;36import java.net.URL;3738import java.security.KeyStore;3940import java.security.Provider;41import java.security.Security;42import java.security.cert.X509Certificate;43import java.text.Collator;4445import java.util.ArrayList;46import java.util.Arrays;47import java.util.List;48import java.util.Locale;49import java.util.Properties;50import java.util.ResourceBundle;51import java.util.ServiceLoader;5253import sun.security.util.FilePaths;54import sun.security.util.PropertyExpander;5556/**57* <p> This class provides several utilities to <code>KeyStore</code>.58*59* @since 1.6.060*/61public class KeyStoreUtil {6263private KeyStoreUtil() {64// this class is not meant to be instantiated65}6667/**68* Returns true if the certificate is self-signed, false otherwise.69*/70public static boolean isSelfSigned(X509Certificate cert) {71return signedBy(cert, cert);72}7374public static boolean signedBy(X509Certificate end, X509Certificate ca) {75if (!ca.getSubjectX500Principal().equals(end.getIssuerX500Principal())) {76return false;77}78try {79end.verify(ca.getPublicKey());80return true;81} catch (Exception e) {82return false;83}84}8586/**87* Returns true if KeyStore has a password. This is true except for88* MSCAPI KeyStores89*/90public static boolean isWindowsKeyStore(String storetype) {91return storetype != null92&& (storetype.equalsIgnoreCase("Windows-MY")93|| storetype.equalsIgnoreCase("Windows-ROOT"));94}9596/**97* Returns standard-looking names for storetype98*/99public static String niceStoreTypeName(String storetype) {100if (storetype.equalsIgnoreCase("Windows-MY")) {101return "Windows-MY";102} else if(storetype.equalsIgnoreCase("Windows-ROOT")) {103return "Windows-ROOT";104} else {105return storetype.toUpperCase(Locale.ENGLISH);106}107}108109/**110* Returns the file name of the keystore with the configured CA certificates.111*/112public static String getCacerts() {113return FilePaths.cacerts();114}115116/**117* Returns the keystore with the configured CA certificates.118*/119public static KeyStore getCacertsKeyStore() throws Exception {120File file = new File(getCacerts());121if (!file.exists()) {122return null;123}124return KeyStore.getInstance(file, (char[])null);125}126127public static char[] getPassWithModifier(String modifier, String arg,128ResourceBundle rb,129Collator collator) {130if (modifier == null) {131return arg.toCharArray();132} else if (collator.compare(modifier, "env") == 0) {133String value = System.getenv(arg);134if (value == null) {135System.err.println(rb.getString(136"Cannot.find.environment.variable.") + arg);137return null;138} else {139return value.toCharArray();140}141} else if (collator.compare(modifier, "file") == 0) {142try {143URL url = null;144try {145url = new URL(arg);146} catch (java.net.MalformedURLException mue) {147File f = new File(arg);148if (f.exists()) {149url = f.toURI().toURL();150} else {151System.err.println(rb.getString(152"Cannot.find.file.") + arg);153return null;154}155}156157try (BufferedReader br =158new BufferedReader(new InputStreamReader(159url.openStream()))) {160String value = br.readLine();161162if (value == null) {163return new char[0];164}165166return value.toCharArray();167}168} catch (IOException ioe) {169System.err.println(ioe);170return null;171}172} else {173System.err.println(rb.getString("Unknown.password.type.") +174modifier);175return null;176}177}178179/**180* Parses a option line likes181* -genkaypair -dname "CN=Me"182* and add the results into a list183* @param list the list to fill into184* @param s the line185*/186private static void parseArgsLine(List<String> list, String s)187throws IOException, PropertyExpander.ExpandException {188StreamTokenizer st = new StreamTokenizer(new StringReader(s));189190st.resetSyntax();191st.whitespaceChars(0x00, 0x20);192st.wordChars(0x21, 0xFF);193// Everything is a word char except for quotation and apostrophe194st.quoteChar('"');195st.quoteChar('\'');196197while (true) {198if (st.nextToken() == StreamTokenizer.TT_EOF) {199break;200}201list.add(PropertyExpander.expand(st.sval));202}203}204205/**206* Prepends matched options from a pre-configured options file.207*208* @param tool the name of the tool, can be "keytool" or "jarsigner"209* @param file the pre-configured options file210* @param c1 the name of the command, with the "-" prefix,211* must not be null212* @param c2 the alternative command name, with the "-" prefix,213* null if none. For example, "genkey" is alt name for214* "genkeypair". A command can only have one alt name now.215* @param args existing arguments216* @return arguments combined217* @throws IOException if there is a file I/O or format error218* @throws PropertyExpander.ExpandException219* if there is a property expansion error220*/221public static String[] expandArgs(String tool, String file,222String c1, String c2, String[] args)223throws IOException, PropertyExpander.ExpandException {224225List<String> result = new ArrayList<>();226Properties p = new Properties();227p.load(new FileInputStream(file));228229String s = p.getProperty(tool + ".all");230if (s != null) {231parseArgsLine(result, s);232}233234// Cannot provide both -genkey and -genkeypair235String s1 = p.getProperty(tool + "." + c1.substring(1));236String s2 = null;237if (c2 != null) {238s2 = p.getProperty(tool + "." + c2.substring(1));239}240if (s1 != null && s2 != null) {241throw new IOException("Cannot have both " + c1 + " and "242+ c2 + " as pre-configured options");243}244if (s1 == null) {245s1 = s2;246}247if (s1 != null) {248parseArgsLine(result, s1);249}250251if (result.isEmpty()) {252return args;253} else {254result.addAll(Arrays.asList(args));255return result.toArray(new String[result.size()]);256}257}258259/**260* Loads a security provider as a service.261*262* @param provName the name263* @param arg optional arg264* @throws IllegalArgumentException if no provider matches the name265*/266public static void loadProviderByName(String provName, String arg) {267Provider loaded = Security.getProvider(provName);268if (loaded != null) {269if (arg != null) {270loaded = loaded.configure(arg);271Security.addProvider(loaded);272}273return;274}275for (Provider p : ServiceLoader.load(Provider.class,276ClassLoader.getSystemClassLoader())) {277if (p.getName().equals(provName)) {278if (arg != null) {279p = p.configure(arg);280}281Security.addProvider(p);282return;283}284}285throw new IllegalArgumentException("No provider found");286}287288/**289* Loads a security provider by a fully-qualified class name.290*291* @param provClass the class name292* @param arg optional arg293* @param cl optional class loader294* @throws IllegalArgumentException if no provider matches the class name295* @throws ClassCastException if the class has not extended Provider296*/297public static void loadProviderByClass(298String provClass, String arg, ClassLoader cl) {299300// For compatibility, SunPKCS11, and SunMSCAPI301// can still be loadable with -providerClass.302if (provClass.equals("sun.security.pkcs11.SunPKCS11")) {303loadProviderByName("SunPKCS11", arg);304return;305} else if (provClass.equals("sun.security.mscapi.SunMSCAPI")) {306loadProviderByName("SunMSCAPI", arg);307return;308}309310Provider prov;311try {312Class<?> clazz = Class.forName(provClass, false, cl);313prov = (Provider) clazz.getConstructor().newInstance();314} catch (ReflectiveOperationException e) {315throw new IllegalArgumentException(e);316}317if (arg != null) {318prov = prov.configure(arg);319}320Security.addProvider(prov);321}322}323324325