*
Stores the keystore onto HDFS. Overwrites existing one.


@param path
@param keyStorePassword
@throws KeyStoreException
@throws NoSuchAlgorithmException
@throws CertificateException
@throws IOException
771579
public void store(Path path, String keyStorePassword) throws KeyStoreException, NoSuchAlgorithmException, CertificateException, IOException {
		OutputStream os = this.fs.create(path, true);
		this.keystore.store(os,keyStorePassword.toCharArray());
		if (os!=null) {
			os.close();
		}
	}
415916
public TLSBuilder withTrustStore(final String trustStoreType, final InputStream trustStoreStream, final char[] trustStorePassword)
    {
        return withKeyStore(trustStoreType, trustStoreStream, trustStorePassword);
    }
183613
@Override
	public void engineSetCertificateEntry(String alias, Certificate certificate)
			throws KeyStoreException {

		if (!(certificate instanceof X509Certificate)) {
			throw new KeyStoreException(
					"Certificate must be instance of X509Certificate");
		}
		File file;
		ResourceTrustAnchor trustAnchor = getCertificateEntry(alias);
		if (trustAnchor != null) {
			file = trustAnchor.getFile();
		} else {
			file = new File(defaultDirectory, alias);
		}
		X509Certificate x509Cert = (X509Certificate) certificate;
		try {
			if(!inMemoryOnly){
				writeCertificate(x509Cert, file);
			}
			ResourceTrustAnchor anchor = new ResourceTrustAnchor(inMemoryOnly,
					new GlobusResource(file.getAbsolutePath()), new TrustAnchor(x509Cert,
							null));
			this.aliasObjectMap.put(alias, anchor);
			this.certFilenameMap.put(x509Cert, alias);
		} catch (ResourceStoreException e) {
			throw new KeyStoreException(e);
		} catch (IOException e) {
			throw new KeyStoreException(e);
		} catch (CertificateEncodingException e) {
			throw new KeyStoreException(e);
		}
	}
1898
private KeyStore createKeyStore(String fileName, String password)  {
        File file = new File(fileName);
        KeyStore keyStore = null;
        try {
            keyStore = KeyStore.getInstance("JCEKS");
            if (file.exists()) {
                keyStore.load(new FileInputStream(file), password.toCharArray());
            } else {
                keyStore.load(null, null);
                keyStore.store(new FileOutputStream(fileName), password.toCharArray());
            }
        } catch (CertificateException | IOException | KeyStoreException | NoSuchAlgorithmException e) {
            logger.error("Unable to create key store", e);
        }

        return keyStore;
    }
439964
public KeyStoreCredentialResolverBuilder addKeyPasswords(Map<String, String> keyPasswords) {
        requireNonNull(keyPasswords, "keyPasswords");
        keyPasswords.forEach(this::addKeyPassword);
        return this;
    }
320439
public static KeyStore createTrustStore(String capem) throws IOException, CertificateException,
            KeyStoreException, NoSuchAlgorithmException {
        try (Reader certReader = new StringReader(capem)) {
            return createTrustStore(certReader);
        }
    }
483324
@Override
    public FileStore getFileStore(final Path path) throws IOException {
        final FileStore fileStore = path.getFileSystem().getFileStores().iterator().next();
        return fileStore;
    }
853558
public void setTrustStore(String trustStore, String trustPass) {
        setTrustStore(trustStore, trustPass, null, null);
    }
1306631
public boolean saveKeyTo(String path)
    {
        LinkedList<String> keyList = new LinkedList<String>();
        for (Map.Entry<String, TermFrequency> entry : trie.entrySet())
        {
            keyList.add(entry.getKey());
        }
        return IOUtil.saveCollectionToTxt(keyList, path);
    }
13796
public void setCertificate() throws KeyStoreException, IOException, NoSuchAlgorithmException,
                    CertificateException, NoSuchPaddingException, InvalidKeyException,
                    IllegalBlockSizeException, BadPaddingException, UnrecoverableEntryException {
        KeyStore store = KeyStore.getInstance(this.keystore_type);
        InputStream inputStream=Thread.currentThread().getContextClassLoader().getResourceAsStream(this.keystore_path);
        if(inputStream == null)
            inputStream=new FileInputStream(this.keystore_path);
        store.load(inputStream, this.keystore_password);

        this.cipher = Cipher.getInstance(this.cipher_type);
        this.certificate = (X509Certificate) store.getCertificate(this.cert_alias);

        log.debug("certificate = " + this.certificate.toString());

        this.cipher.init(Cipher.ENCRYPT_MODE, this.certificate);
        this.encryptedToken = this.cipher.doFinal(this.auth_value.getBytes());

        KeyStore.PrivateKeyEntry privateKey = (KeyStore.PrivateKeyEntry) store.getEntry(
                        this.cert_alias, new KeyStore.PasswordProtection(this.cert_password));
        this.certPrivateKey = privateKey.getPrivateKey();

        this.valueSet=true;
    }
539091
@Override
  public final void decryptFile(final String pEncryptedPath,
    final String pDecryptedPath) throws Exception {
    FileInputStream fis = null;
    byte[] encryptedSsk = null;
    try {
      fis = new FileInputStream(pEncryptedPath + ".sken");
      ByteArrayOutputStream baus = new ByteArrayOutputStream();
      int b;
      while ((b = fis.read()) != -1) {
        baus.write(b);
      }
      encryptedSsk = baus.toByteArray();
    } finally {
      if (fis != null) {
        try {
          fis.close();
        } catch (Exception e) {
          e.printStackTrace();
        }
      }
    }
    fis = null;
    byte[] sigSsk = null;
    try {
      fis = new FileInputStream(pEncryptedPath + ".sken.sig");
      ByteArrayOutputStream baus = new ByteArrayOutputStream();
      int b;
      while ((b = fis.read()) != -1) {
        baus.write(b);
      }
      sigSsk = baus.toByteArray();
    } finally {
      if (fis != null) {
        try {
          fis.close();
        } catch (Exception e) {
          e.printStackTrace();
        }
      }
    }
    fis = null;
    byte[] sigDt = null;
    try {
      fis = new FileInputStream(pEncryptedPath + ".sig");
      ByteArrayOutputStream baus = new ByteArrayOutputStream();
      int b;
      while ((b = fis.read()) != -1) {
        baus.write(b);
      }
      sigDt = baus.toByteArray();
    } finally {
      if (fis != null) {
        try {
          fis.close();
        } catch (Exception e) {
          e.printStackTrace();
        }
      }
    }
    if (encryptedSsk != null && sigSsk != null && sigDt != null) {
      Signature sigMk = Signature.getInstance("SHA256withRSA");
      sigMk.initVerify(lazyGetPublicKeyAnotherAjetty());
      sigMk.update(encryptedSsk);
      if (sigMk.verify(sigSsk)) {
        sigMk.initVerify(lazyGetPublicKeyAnotherAjetty());
        BufferedInputStream bis = null;
        byte[] buffer = new byte[1024];
        int len;
        try {
          bis = new BufferedInputStream(new FileInputStream(
            pEncryptedPath));
          while ((len = bis.read(buffer)) > 0) {
            sigMk.update(buffer, 0, len);
          }
        } finally {
          if (bis != null) {
            try {
              bis.close();
            } catch (Exception e) {
              e.printStackTrace();
            }
          }
        }
        if (sigMk.verify(sigDt)) {
          Cipher cipherRsa = Cipher.getInstance("RSA", this.cryptoProvider);
          cipherRsa.init(Cipher.DECRYPT_MODE, lazyGetOurPrivateKey());
          byte[] decryptedSsk = cipherRsa.doFinal(encryptedSsk);
          SecretKeySpec sskAesRec = new SecretKeySpec(decryptedSsk, "AES");
          Cipher cipherAes = Cipher.getInstance("AES/ECB/PKCS7Padding",
            this.cryptoProvider);
          cipherAes.init(Cipher.DECRYPT_MODE, sskAesRec);
          CipherOutputStream cous = null;
          try {
            bis = new BufferedInputStream(new FileInputStream(pEncryptedPath));
            cous = new CipherOutputStream(new FileOutputStream(pDecryptedPath),
              cipherAes);
            while ((len = bis.read(buffer)) > 0) {
              cous.write(buffer, 0, len);
            }
            cous.flush();
          } finally {
            if (bis != null) {
              try {
                bis.close();
              } catch (Exception e) {
                e.printStackTrace();
              }
            }
            if (cous != null) {
              try {
                cous.close();
              } catch (Exception e) {
                e.printStackTrace();
              }
            }
          }
        }
      }
    }
  }
543633
public function setSSLKey($certificateFile, $password = null)
    {
        if ($password) {
            $this->options[GuzzleRequestOptions::SSL_KEY] = [$certificateFile, $password];
        } else {
            $this->options[GuzzleRequestOptions::SSL_KEY] = $certificateFile;
        }
    }
694415
public static PrivateKey getSignCertPrivateKeyByStoreMap(String certPath,
			String certPwd) {
		if (!keyStoreMap.containsKey(certPath)) {
			loadSignCert(certPath, certPwd);
		}
		try {
			Enumeration<String> aliasenum = keyStoreMap.get(certPath)
					.aliases();
			String keyAlias = null;
			if (aliasenum.hasMoreElements()) {
				keyAlias = aliasenum.nextElement();
			}
			PrivateKey privateKey = (PrivateKey) keyStoreMap.get(certPath)
					.getKey(keyAlias, certPwd.toCharArray());
			return privateKey;
		} catch (KeyStoreException e) {
			LogUtil.writeErrorLog("getSignCertPrivateKeyByStoreMap Error", e);
			return null;
		} catch (UnrecoverableKeyException e) {
			LogUtil.writeErrorLog("getSignCertPrivateKeyByStoreMap Error", e);
			return null;
		} catch (NoSuchAlgorithmException e) {
			LogUtil.writeErrorLog("getSignCertPrivateKeyByStoreMap Error", e);
			return null;
		}
	}
153896
public static KeyStore openKeyStore(File storeFile, String storePassword) {
        String lc = storeFile.getName().toLowerCase();
        String type = "JKS";
        String provider = null;
        if (lc.endsWith(".p12") || lc.endsWith(".pfx")) {
            type = "PKCS12";
            provider = BC;
        }

        try {
            KeyStore store;
            if (provider == null) {
                store = KeyStore.getInstance(type);
            } else {
                store = KeyStore.getInstance(type, provider);
            }
            storeFile.getParentFile().mkdirs();
            if (storeFile.exists()) {
                FileInputStream fis = null;
                try {
                    fis = new FileInputStream(storeFile);
                    store.load(fis, storePassword.toCharArray());
                } finally {
                    if (fis != null) {
                        fis.close();
                    }
                }
            } else {
                store.load(null);
            }
            return store;
        } catch (Exception e) {
            throw new RuntimeException("Could not open keystore " + storeFile, e);
        }
    }
879321
public void setTrustStore(String pathToTrustStore, String trustStorePassword) {
        File tsFD = new File(pathToTrustStore != null && !pathToTrustStore.trim().isEmpty() ? pathToTrustStore : "");
        if (!tsFD.exists() || !tsFD.isFile() || !tsFD.canRead()) {
            throw new IllegalArgumentException("Trust store " + pathToTrustStore + " is not a read accessible file");
        }
        m_sslConfig = new SSLConfiguration.SslConfig(null, null, pathToTrustStore, trustStorePassword);
    }
44749
private void readKeyStore(Configuration conf) throws IOException, FormatNotUnderstoodException {
	if ((this.hocr.getCryptKeystoreFile()!=null) && (!"".equals(this.hocr.getCryptKeystoreFile()))) {
		LOG.info("Using keystore to obtain credentials instead of passwords");
		HadoopKeyStoreManager hksm = new HadoopKeyStoreManager(conf);
		try {
			hksm.openKeyStore(new Path(this.hocr.getCryptKeystoreFile()), this.hocr.getCryptKeystoreType(), this.hocr.getCryptKeystorePassword());
			String pw="";
			if ((this.hocr.getCryptKeystoreAlias()!=null) && (!"".equals(this.hocr.getCryptKeystoreAlias()))) {
				pw=hksm.getPassword(this.hocr.getCryptKeystoreAlias(), this.hocr.getCryptKeystorePassword());
			} else {
				pw=hksm.getPassword(this.hocr.getFileName(), this.hocr.getCryptKeystorePassword());
			}
			this.hocr.setPassword(pw);
		} catch (NoSuchAlgorithmException | CertificateException | KeyStoreException | IllegalArgumentException | UnrecoverableEntryException | InvalidKeySpecException e) {
			LOG.error("Cannopt read keystore. Exception: ",e);
			throw new FormatNotUnderstoodException("Cannot read keystore to obtain credentials to access encrypted documents "+e);
		}
		
	}
}
873131
public void setCertificateEntry(String alias, Certificate cert) throws KeyStoreException, KeyException {
        if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) {
            Tr.entry(this, tc, "setCertificateEntry", new Object[] { alias, cert });
        }
        if (Boolean.parseBoolean(getProperty(Constants.SSLPROP_KEY_STORE_READ_ONLY))) {
            if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) {
                Tr.debug(this, tc, "Unable to update readonly store");
            }
            throw new KeyStoreException("Unable to add to read-only store");
        }
        final KeyStoreManager mgr = KeyStoreManager.getInstance();

        try {
            KeyStore jKeyStore = getKeyStore(false, false);
            if (null == jKeyStore) {
                final String keyStoreLocation = getProperty(Constants.SSLPROP_KEY_STORE);
                if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) {
                    Tr.debug(tc, "Cannot load the Java keystore at location \"" + keyStoreLocation + "\"");
                }
                throw new KeyStoreException("Cannot load the Java keystore at location \"" + keyStoreLocation + "\"");
            }

            // store the cert... errors are thrown if conflicts or errors occur
            jKeyStore.setCertificateEntry(alias, cert);

            try {
                store();
            } catch (IOException e) {
                // Note: debug + ffdc in store() itself

                // on z/OS we have an issue where the certificate may be stored but the
                // alias
                // already exists in RACF so the keystore API will through an
                // IOException
                // we need to catch this condition on z/OS and if the certs is in the
                // keystore
                // prior after adding the certificate then we know the cert was actually
                // added and its not
                // a true failure. If the cert was not added then we need to rethrow the
                // exception.
                final String ksType = getProperty(Constants.SSLPROP_KEY_STORE_TYPE);
                if ((ksType.equals(Constants.KEYSTORE_TYPE_JCERACFKS) || ksType.equals(Constants.KEYSTORE_TYPE_JCECCARACFKS)
                     || ksType.equals(Constants.KEYSTORE_TYPE_JCEHYBRIDRACFKS))) {
                    KeyStore ks = getKeyStore(true, false);

                    if (mgr.checkIfSignerAlreadyExistsInTrustStore((X509Certificate) cert, ks)) {
                        if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) {
                            Tr.debug(tc, "Certificate already exists in RACF: " + e.getMessage());
                        }
                    } else {
                        throw new KeyException(e.getMessage(), e);
                    }
                } else {
                    throw new KeyException(e.getMessage(), e);
                }
            }
        } catch (KeyStoreException kse) {
            throw kse;
        } catch (KeyException ke) {
            throw ke;
        } catch (Exception e) {
            throw new KeyException(e.getMessage(), e);
        }

        // after adding the certificate, clear the keystore and SSL caches so it
        // reloads it.
        AbstractJSSEProvider.clearSSLContextCache();
        mgr.clearJavaKeyStoresFromKeyStoreMap();

        if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) {
            Tr.exit(this, tc, "setCertificateEntry");
        }
    }