Loads and returns the {@link java.security.KeyStore} from the file system.

@param file file to load from file system.
@param password password to access the keystore.

@return {@link java.security.KeyStore}

@throws KSIException
765399
public static KeyStore loadKeyStore(File file, String password) throws KSIException {
        notNull(file, "Trust store file");
        FileInputStream input = null;
        KeyStore keyStore = null;
        try {
            keyStore = KeyStore.getInstance("JKS");
            char[] passwordCharArray = password == null ? null : password.toCharArray();
            input = new FileInputStream(file);
            keyStore.load(input, passwordCharArray);
        } catch (GeneralSecurityException | IOException e) {
            throw new KSIException("Loading java key store with path " + file + " failed", e);
        } finally {
            closeQuietly(input);
        }
        return keyStore;
    }
540040
public static String readFile(File file) {
		FileInputStream inputStream;
		try {
			inputStream = new FileInputStream(file);
			return new String(readStream(inputStream));
		} catch (FileNotFoundException e) {
			JK.throww(e);
			return null;
		}
	}
441870
public static void decrypt(File file,
                             String keyBase64,
                             String ivBase64,
                             RemoteStoreFileEncryptionMaterial encMat)
  throws NoSuchAlgorithmException,
         NoSuchPaddingException,
         InvalidKeyException,
         IllegalBlockSizeException,
         BadPaddingException,
         InvalidAlgorithmParameterException,
         IOException
  {
    byte[] keyBytes = Base64.decode(keyBase64);
    byte[] ivBytes = Base64.decode(ivBase64);
    byte[] qsmkBytes = Base64.decode(encMat.getQueryStageMasterKey());
    final SecretKey fileKey;

    // Decrypt file key
    {
      final Cipher keyCipher = Cipher.getInstance(KEY_CIPHER);
      SecretKey queryStageMasterKey =
          new SecretKeySpec(qsmkBytes, 0, qsmkBytes.length, AES);
      keyCipher.init(Cipher.DECRYPT_MODE, queryStageMasterKey);
      byte[] fileKeyBytes = keyCipher.doFinal(keyBytes);

      // NB: we assume qsmk.length == fileKey.length
      //     (fileKeyBytes.length may be bigger due to padding)
      fileKey = new SecretKeySpec(fileKeyBytes, 0, qsmkBytes.length, AES);
    }

    // Decrypt file
    {
      final Cipher fileCipher = Cipher.getInstance(FILE_CIPHER);
      final IvParameterSpec iv = new IvParameterSpec(ivBytes);
      final byte[] buffer = new byte[BUFFER_SIZE];
      fileCipher.init(Cipher.DECRYPT_MODE, fileKey, iv);

      long totalBytesRead = 0;
      // Overwrite file contents buffer-wise with decrypted data
      try (InputStream is = Files.newInputStream(file.toPath(), READ);
           InputStream cis = new CipherInputStream(is, fileCipher);
           OutputStream os = Files.newOutputStream(file.toPath(), CREATE);)
      {
        int bytesRead;
        while ((bytesRead = cis.read(buffer)) > -1)
        {
          os.write(buffer, 0, bytesRead);
          totalBytesRead += bytesRead;
        }
      }

      // Discard any padding that the encrypted file had
      try (FileChannel fc = new FileOutputStream(file, true).getChannel())
      {
        fc.truncate(totalBytesRead);
      }
    }
  }
164490
public EncryptionKey generateAndSaveKeyProtectedByPassword(String password) {
        EncryptionKey dpk = null;
        if (password == null || password.equals("")) {
            throw new IllegalArgumentException("password is required to be a non-null/non-empty " +
                    "string");
        }
        try {
            if (!keyExists()) {
                byte[] dpkBytes = generateSecureRandomBytesWithLength
                        (ENCRYPTION_KEYCHAIN_ENCRYPTIONKEY_SIZE);
                byte[] salt = generateSecureRandomBytesWithLength
                        (ENCRYPTION_KEYCHAIN_PBKDF2_SALT_SIZE);
                byte[] iv = generateSecureRandomBytesWithLength
                        (ENCRYPTIONKEYCHAINMANAGER_AES_IV_SIZE);
                SecretKey aesKey = pbkdf2DerivedKeyForPassword(password, salt,
                        ENCRYPTION_KEYCHAIN_PBKDF2_ITERATIONS,
                        ENCRYPTION_KEYCHAIN_AES_KEY_SIZE);

                byte[] encryptedDpkBytes = DPKEncryptionUtil.encryptAES(aesKey, iv, dpkBytes);

                KeyData keyData = new KeyData(encryptedDpkBytes, salt, iv,
                        ENCRYPTION_KEYCHAIN_PBKDF2_ITERATIONS, ENCRYPTION_KEYCHAIN_VERSION);

                if (this.storage.saveEncryptionKeyData(keyData)) {
                    dpk = new EncryptionKey(dpkBytes);
                }
            }
        } catch (InvalidKeyException e) {
            throw new DPKException("Failed to encrypt DPK.  Cause: " + e.getLocalizedMessage(), e);
        } catch (NoSuchPaddingException e) {
            throw new DPKException("Failed to encrypt DPK.  Cause: " + e.getLocalizedMessage(), e);
        } catch (NoSuchAlgorithmException e) {
            throw new DPKException("Failed to encrypt DPK.  Cause: " + e.getLocalizedMessage(), e);
        } catch (IllegalBlockSizeException e) {
            throw new DPKException("Failed to encrypt DPK.  Cause: " + e.getLocalizedMessage(), e);
        } catch (BadPaddingException e) {
            throw new DPKException("Failed to encrypt DPK.  Cause: " + e.getLocalizedMessage(), e);
        } catch (InvalidAlgorithmParameterException e) {
            throw new DPKException("Failed to encrypt DPK.  Cause: " + e.getLocalizedMessage(), e);
        } catch (InvalidKeySpecException e) {
            throw new DPKException("Failed to encrypt DPK.  Cause: " + e.getLocalizedMessage(), e);
        }
        return dpk;
    }
747479
public static HashId createHashId(File file) throws IOException {
	try (FileInputStream stream = new FileInputStream(file)) {
	    return createHashId(stream);
	}
    }
949267
public static Properties load(File file) throws IOException {
        if (file.isFile()) {
            FileInputStream fis = null;
            try {
                Properties headers = new Properties();
                fis = new FileInputStream(file);
                headers.load(fis);
                return headers;
            } finally {
                IOUtils.closeQuietly(fis);
            }
        }
        return new Properties();
    }
1295887
public AuthenticationConfigurationBuilder password(String password) {
      this.password = password != null ? password.toCharArray() : null;
      return enable();
   }
703257
public static PublicKey loadPublicKey(File file) { 
    	FileInputStream inputStream = null;
    	try {
    		inputStream = new FileInputStream(file);			
    		return loadPublicKey(inputStream);
		} catch (FileNotFoundException e) {
			throw new RuntimeException("文件不存在");
		}finally {
			try {inputStream.close();} catch (Exception e2) {}
		}
    }
708012
@Override
    public byte[] load(String key) throws IOException {
        try {
            File f = getFileFor(key);
            if (!f.exists()) return null;

            Cipher sym = Cipher.getInstance("AES");
            sym.init(Cipher.DECRYPT_MODE, masterKey);
            try (
                    FileInputStream fis = new FileInputStream(f);
                    CipherInputStream cis = new CipherInputStream(fis, sym)
            ) {
                byte[] bytes = IOUtils.toByteArray(cis);
                return verifyMagic(bytes);
            }
        } catch (GeneralSecurityException e) {
            throw new IOException("Failed to persist the key: " + key, e);
        }
    }
764424
public SSLEngine get() {
        try {
            String pass = env.sslKeystorePassword();
            char[] password = pass == null || pass.isEmpty() ? null : pass.toCharArray();

            KeyStore ks = env.sslKeystore();
            if (ks == null) {
                String ksFile = env.sslKeystoreFile();
                if (ksFile != null && !ksFile.isEmpty()) {
                    ks = KeyStore.getInstance(KeyStore.getDefaultType());
                    ks.load(new FileInputStream(ksFile), password);
                }
            }

            KeyStore ts = env.sslTruststore();
            if (ts == null) {
                String tsFile = env.sslTruststoreFile();
                if (tsFile != null && !tsFile.isEmpty()) {
                    // filepath found, open and init
                    String tsPassword = env.sslTruststorePassword();
                    char[] tspass = tsPassword == null || tsPassword.isEmpty() ? null : tsPassword.toCharArray();
                    ts = KeyStore.getInstance(KeyStore.getDefaultType());
                    ts.load(new FileInputStream(tsFile), tspass);
                }
            }

            if (ks == null && ts == null) {
                throw new IllegalStateException("Either a KeyStore or a TrustStore " +
                    "need to be provided (or both).");
            } else if (ks == null) {
                ks = ts;
                LOGGER.debug("No KeyStore provided, using provided TrustStore to initialize both factories.");
            } else if (ts == null) {
                ts = ks;
                LOGGER.debug("No TrustStore provided, using provided KeyStore to initialize both factories.");
            }

            String defaultAlgorithm = KeyManagerFactory.getDefaultAlgorithm();
            KeyManagerFactory kmf = KeyManagerFactory.getInstance(defaultAlgorithm);
            TrustManagerFactory tmf = TrustManagerFactory.getInstance(defaultAlgorithm);
            kmf.init(ks, password);
            tmf.init(ts);

            if (!sslContextProtocol.startsWith("TLS")) {
                throw new IllegalArgumentException(
                    "SSLContext Protocol does not start with TLS, this is to prevent "
                        + "insecure protocols (Like SSL*) to be used. Potential candidates "
                        + "are TLS (default), TLSv1, TLSv1.1, TLSv1.2, TLSv1.3 depending on "
                        + "the Java version used.");
            }
            SSLContext ctx = SSLContext.getInstance(sslContextProtocol);
            ctx.init(kmf.getKeyManagers(), tmf.getTrustManagers(), null);

            SSLEngine engine = ctx.createSSLEngine();
            engine.setUseClientMode(true);
            return engine;
        } catch (Exception ex) {
            throw new SSLException("Could not create SSLEngine.", ex);
        }
    }
1053652
public Key getKey(String alias, String password) {
        try {
            return keyStore.getKey(alias, password.toCharArray());
        } catch (GeneralSecurityException e) {
            throw new IllegalStateException(e);
        }
    }
465625
private void readFile()
            throws IOException
    {
        BufferedReader reader = null;

        try {
            reader = new BufferedReader( new InputStreamReader( new FileInputStream( file ), PcsUtils.UTF8 ) );

            LOGGER.debug( "Reading credentials file {}", file );

            String line;
            int index = 1;

            while ( ( line = reader.readLine() ) != null ) {
                line = line.trim();

                if ( line.startsWith( "#" ) || line.length() == 0 ) {
                    continue;
                }

                String[] userCredentialsArray = line.split( "=", 2 );

                if ( userCredentialsArray.length != 2 ) {
                    throw new IllegalArgumentException( "Not parsable line #" + index );
                }

                // Key
                final String key = userCredentialsArray[0].trim();
                final Credentials value = Credentials.createFromJson( userCredentialsArray[1].trim() );

                credentialsMap.put( key, value );

                index++;
            }

        } finally {
            PcsUtils.closeQuietly( reader );
        }
    }
41278
public static KeyStore readKeyStore(String type, InputStream in, char[] password) {
		return KeyUtil.readKeyStore(type, in, password);
	}
529188
public static PrivateKey loadPrivateKeyFromKeyStore(KeyStore keyStore,String alias,String keyPass){
        try {			
        	return (PrivateKey) keyStore.getKey(alias, keyPass.toCharArray());
		} catch (Exception e) {
			throw new RuntimeException(e);
		}
    }
343581
public static PrivateKey loadPrivateKeyFromKeyStore(String location,String alias,String storeType,String storePass,String keyPass){
        try {			
        	storeType = null == storeType ? KeyStore.getDefaultType() : storeType;
        	keyPass = keyPass == null ? storePass : keyPass;
        	KeyStore keyStore = KeyStore.getInstance(storeType);
        	InputStream is = new FileInputStream(location);
        	keyStore.load(is, storePass.toCharArray());
        	// 由密钥库获取密钥的两种方式
        	return (PrivateKey) keyStore.getKey(alias, keyPass.toCharArray());
		} catch (Exception e) {
			throw new RuntimeException(e);
		}
    }
1281197
public static TrustManager[] initializeTrustManagers(File _trustStoreFile, String _trustStorePassword) throws IOException {
        if (_trustStoreFile == null) {
            return null;
        }

        String storeType = getStoreTypeByFileName(_trustStoreFile);

        boolean derEncoded = storeType == STORETYPE_DER_ENCODED;
        if (derEncoded) {
            storeType = STORETYPE_JKS;
        }

        String trustStorePwd = StringUtil.defaultIfBlank(_trustStorePassword, System.getProperty("javax.net.ssl.trustStorePassword"));

        LOGGER.debug("Creating trust store of type '" + storeType + "' from " + (derEncoded ? "DER-encoded" : "") + " file '" + _trustStoreFile + "'");

        try {
            TrustManagerFactory trustMgrFactory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());

            KeyStore trustStore = KeyStore.getInstance(storeType);
            if (derEncoded) {
                FileInputStream fis = new FileInputStream(_trustStoreFile);
                X509Certificate certificate = (X509Certificate) CertificateFactory.getInstance("X.509").generateCertificate(fis);
                trustStore.load(null, null);
                trustStore.setCertificateEntry("[der_cert_alias]", certificate);
            } else {
                trustStore.load(new FileInputStream(_trustStoreFile), trustStorePwd != null ? trustStorePwd.toCharArray() : null);
            }
            trustMgrFactory.init(trustStore);
            return trustMgrFactory.getTrustManagers();
        } catch (GeneralSecurityException _ex) {
            throw new IOException("Error while setting up trustStore", _ex);
        }
    }
1022610
public void setKeyStore(String keyStore, String keyPass, String keyManagerType, String keyStoreType) 
    {
        if((keyStore == null) || (keyPass == null))
        {
            this.keyStore =  System.getProperty("javax.net.ssl.keyStore");
            this.keyPass = System.getProperty("javax.net.ssl.keyStorePassword");
        }
        else
        {
            this.keyStore = keyStore;
            this.keyPass = keyPass;
        }
        
        if (keyManagerType != null) {
            this.keyManagerType = keyManagerType;
        }
        if (keyStoreType != null) {
            this.keyStoreType = keyStoreType;
        }
        isKeyStoreSet = (keyStore != null) && (keyPass != null);
    }