001/** 002 * Copyright 2017 Emmanuel Bourg 003 * 004 * Licensed under the Apache License, Version 2.0 (the "License"); 005 * you may not use this file except in compliance with the License. 006 * You may obtain a copy of the License at 007 * 008 * http://www.apache.org/licenses/LICENSE-2.0 009 * 010 * Unless required by applicable law or agreed to in writing, software 011 * distributed under the License is distributed on an "AS IS" BASIS, 012 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 013 * See the License for the specific language governing permissions and 014 * limitations under the License. 015 */ 016 017package net.jsign; 018 019import java.io.File; 020import java.io.FileInputStream; 021import java.security.KeyStore; 022import java.security.KeyStoreException; 023import java.security.Provider; 024 025/** 026 * Helper class for loading KeyStores (JKS, PKCS#12 or PKCS#11). 027 * 028 * @author Emmanuel Bourg 029 * @since 2.0 030 */ 031public class KeyStoreUtils { 032 033 private KeyStoreUtils() { 034 } 035 036 /** 037 * Load the keystore from the specified file. 038 * 039 * @param keystore the file containing the keystore 040 * @param storetype the type of the keystore (either JKS, PKCS12 or PKCS11). 041 * If null the type is inferred from the extension of the file (.p12 or .pfx for PKCS#12 keystores) 042 * @param storepass The password of the keystore 043 * @param provider The security provider used to load the keystore (must be specified for PKCS#11 keystores) 044 * @return the keystore loaded 045 * @throws KeyStoreException thrown if the keystore cannot be loaded 046 */ 047 public static KeyStore load(File keystore, String storetype, String storepass, Provider provider) throws KeyStoreException { 048 if (keystore != null && storetype == null) { 049 // guess the type of the keystore from the extension of the file 050 String filename = keystore.getName().toLowerCase(); 051 if (filename.endsWith(".p12") || filename.endsWith(".pfx")) { 052 storetype = "PKCS12"; 053 } else { 054 storetype = "JKS"; 055 } 056 } 057 058 KeyStore ks; 059 try { 060 if ("PKCS11".equals(storetype)) { 061 ks = KeyStore.getInstance(storetype, provider); 062 } else { 063 ks = KeyStore.getInstance(storetype); 064 } 065 } catch (KeyStoreException e) { 066 throw new KeyStoreException("keystore type '" + storetype + "' is not supported", e); 067 } 068 069 if (keystore == null || !keystore.exists()) { 070 throw new KeyStoreException("The keystore " + keystore + " couldn't be found"); 071 } 072 073 try { 074 FileInputStream in = "PKCS11".equals(storetype) ? null : new FileInputStream(keystore); 075 try { 076 ks.load(in, storepass != null ? storepass.toCharArray() : null); 077 } finally { 078 if (in != null) { 079 in.close(); 080 } 081 } 082 } catch (Exception e) { 083 throw new KeyStoreException("Unable to load the keystore " + keystore, e); 084 } 085 086 return ks; 087 } 088}