List of usage examples for java.security KeyStore isKeyEntry
public final boolean isKeyEntry(String alias) throws KeyStoreException
From source file:edu.vt.middleware.crypt.KeyStoreCli.java
/** * Lists keystore contents on STDOUT. Output is similar to keytool -list -v. * * @param line Parsed command line arguments container. * * @throws Exception On errors./* www . jav a 2s . c o m*/ */ protected void list(final CommandLine line) throws Exception { validateOptions(line); final KeyStore store = readKeyStore(line); final Enumeration<String> aliases = store.aliases(); System.out.println(""); while (aliases.hasMoreElements()) { final String alias = aliases.nextElement(); System.out.println("Alias name: " + alias); System.out.println("Creation date: " + store.getCreationDate(alias)); if (store.isKeyEntry(alias)) { System.out.println("Entry type: keyEntry"); final Certificate[] chain = store.getCertificateChain(alias); System.out.println("Certificate chain length: " + chain.length); for (int i = 0; i < chain.length; i++) { System.out.println("===== Certificate [" + i + "] ====="); printCertificate(chain[i]); } } else { System.out.println("Entry type: trustedCertEntry"); System.out.println("Certificate details:"); printCertificate(store.getCertificate(alias)); } System.out.println(""); System.out.println(""); } }
From source file:com.polyvi.xface.view.XWebViewClient.java
/** * android4.0???SSLContext Android 4.x//from w ww . j a va2 s . co m * WebView???WebKit?ClientCertRequestHandler * ?jar/cer.jar? */ @TargetApi(14) public void onReceivedClientCertRequest(WebView view, ClientCertRequestHandler handler, String host_and_port) { try { KeyStore store = XSSLManager.getInstace().getKeyStore(); // ? if (store == null) { return; } PrivateKey privateKey = null; X509Certificate[] certificates = null; Enumeration<String> e = store.aliases(); while (e.hasMoreElements()) { String alias = e.nextElement(); if (store.isKeyEntry(alias)) { KeyStore.PrivateKeyEntry entry = (KeyStore.PrivateKeyEntry) store.getEntry(alias, null); privateKey = entry.getPrivateKey(); certificates = (X509Certificate[]) entry.getCertificateChain(); break; } } handler.proceed(privateKey, certificates); } catch (Exception e) { e.printStackTrace(); XLog.e(CLASS_NAME, e.getMessage()); } }
From source file:eu.europa.esig.dss.token.Pkcs12SignatureToken.java
@Override public List<DSSPrivateKeyEntry> getKeys() throws DSSException { List<DSSPrivateKeyEntry> list = new ArrayList<DSSPrivateKeyEntry>(); InputStream input = null;//from w ww.j a v a 2 s . co m try { KeyStore keyStore = KeyStore.getInstance("PKCS12"); if (pkcs12Data != null) { input = new ByteArrayInputStream(pkcs12Data); } else { input = new FileInputStream(pkcs12File); } keyStore.load(input, password); PasswordProtection pp = new KeyStore.PasswordProtection(password); Enumeration<String> aliases = keyStore.aliases(); while (aliases.hasMoreElements()) { String alias = aliases.nextElement(); if (keyStore.isKeyEntry(alias)) { PrivateKeyEntry entry = (PrivateKeyEntry) keyStore.getEntry(alias, pp); final KSPrivateKeyEntry privateKeyEntry = new KSPrivateKeyEntry(entry); list.add(privateKeyEntry); } } } catch (Exception e) { if (e.getCause() instanceof BadPaddingException) { throw new DSSBadPasswordException(MSG.PKCS12_BAD_PASSWORD); } throw new DSSException("Can't initialize Sun PKCS#12 security provider. Reason: " + e.getMessage(), e); } finally { IOUtils.closeQuietly(input); } return list; }
From source file:eu.europa.ec.markt.dss.signature.token.Pkcs12SignatureToken.java
@Override public List<DSSPrivateKeyEntry> getKeys() throws KeyStoreException { List<DSSPrivateKeyEntry> list = new ArrayList<DSSPrivateKeyEntry>(); InputStream input = null;/*from ww w . ja va2s.c om*/ try { KeyStore keyStore = KeyStore.getInstance("PKCS12"); if (pkcs12Data != null) { input = new ByteArrayInputStream(pkcs12Data); } else { input = new FileInputStream(pkcs12File); } keyStore.load(input, password); PasswordProtection pp = new KeyStore.PasswordProtection(password); Enumeration<String> aliases = keyStore.aliases(); while (aliases.hasMoreElements()) { String alias = aliases.nextElement(); if (keyStore.isKeyEntry(alias)) { PrivateKeyEntry entry = (PrivateKeyEntry) keyStore.getEntry(alias, pp); list.add(new KSPrivateKeyEntry(entry)); } } } catch (Exception e) { if (e.getCause() instanceof BadPaddingException) { throw new BadPasswordException(MSG.PKCS12_BAD_PASSWORD); } throw new KeyStoreException( "Can't initialize Sun PKCS#12 security provider. Reason: " + getCauseMessage(e), e); } finally { DSSUtils.closeQuietly(input); } return list; }
From source file:org.kuali.rice.ksb.security.admin.service.impl.JavaSecurityManagementServiceImpl.java
public List<KeyStoreEntryDataContainer> getListOfModuleKeyStoreEntries() { List<KeyStoreEntryDataContainer> keyStoreEntries = new ArrayList<KeyStoreEntryDataContainer>(); try {//from ww w . j a v a 2 s . c o m KeyStore moduleKeyStore = getModuleKeyStore(); // List the aliases for (Enumeration<String> enumer = moduleKeyStore.aliases(); enumer.hasMoreElements();) { String alias = (String) enumer.nextElement(); KeyStoreEntryDataContainer dataContainer = new KeyStoreEntryDataContainer(alias, moduleKeyStore.getCreationDate(alias)); KeyStore.PasswordProtection passwordProtection = null; if (moduleKeyStore.isKeyEntry(alias)) { passwordProtection = new KeyStore.PasswordProtection(getModuleKeyStorePassword().toCharArray()); } KeyStore.Entry entry = moduleKeyStore.getEntry(alias, passwordProtection); dataContainer.setType(entry.getClass()); keyStoreEntries.add(dataContainer); } } catch (KeyStoreException e) { e.printStackTrace(); throw new RuntimeException(e); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); throw new RuntimeException(e); } catch (UnrecoverableEntryException e) { e.printStackTrace(); throw new RuntimeException(e); } return keyStoreEntries; }
From source file:com.predic8.membrane.core.transport.ssl.SSLContext.java
public SSLContext(SSLParser sslParser, ResolverMap resourceResolver, String baseLocation) { this.sslParser = sslParser; try {/* w w w. j av a 2 s .c om*/ String algorihm = KeyManagerFactory.getDefaultAlgorithm(); if (sslParser.getAlgorithm() != null) algorihm = sslParser.getAlgorithm(); KeyManagerFactory kmf = null; String keyStoreType = "JKS"; if (sslParser.getKeyStore() != null) { if (sslParser.getKeyStore().getKeyAlias() != null) throw new InvalidParameterException("keyAlias is not yet supported."); char[] keyPass = "changeit".toCharArray(); if (sslParser.getKeyStore().getKeyPassword() != null) keyPass = sslParser.getKeyStore().getKeyPassword().toCharArray(); if (sslParser.getKeyStore().getType() != null) keyStoreType = sslParser.getKeyStore().getType(); KeyStore ks = openKeyStore(sslParser.getKeyStore(), "JKS", keyPass, resourceResolver, baseLocation); kmf = KeyManagerFactory.getInstance(algorihm); kmf.init(ks, keyPass); Enumeration<String> aliases = ks.aliases(); while (aliases.hasMoreElements()) { String alias = aliases.nextElement(); if (ks.isKeyEntry(alias)) { // first key is used by the KeyManagerFactory Certificate c = ks.getCertificate(alias); if (c instanceof X509Certificate) { X509Certificate x = (X509Certificate) c; dnsNames = new ArrayList<String>(); Collection<List<?>> subjectAlternativeNames = x.getSubjectAlternativeNames(); if (subjectAlternativeNames != null) for (List<?> l : subjectAlternativeNames) { if (l.get(0) instanceof Integer && ((Integer) l.get(0) == 2)) dnsNames.add(l.get(1).toString()); } } break; } } } TrustManagerFactory tmf = null; if (sslParser.getTrustStore() != null) { String trustAlgorithm = TrustManagerFactory.getDefaultAlgorithm(); if (sslParser.getTrustStore().getAlgorithm() != null) trustAlgorithm = sslParser.getTrustStore().getAlgorithm(); KeyStore ks = openKeyStore(sslParser.getTrustStore(), keyStoreType, null, resourceResolver, baseLocation); tmf = TrustManagerFactory.getInstance(trustAlgorithm); tmf.init(ks); } TrustManager[] tms = tmf != null ? tmf.getTrustManagers() : null /* trust anyone: new TrustManager[] { new NullTrustManager() } */; if (sslParser.isIgnoreTimestampCheckFailure()) tms = new TrustManager[] { new TrustManagerWrapper(tms, true) }; if (sslParser.getProtocol() != null) sslc = javax.net.ssl.SSLContext.getInstance(sslParser.getProtocol()); else sslc = javax.net.ssl.SSLContext.getInstance("TLS"); sslc.init(kmf != null ? kmf.getKeyManagers() : null, tms, null); if (sslParser.getCiphers() != null) { ciphers = sslParser.getCiphers().split(","); Set<String> supportedCiphers = Sets.newHashSet(sslc.getSocketFactory().getSupportedCipherSuites()); for (String cipher : ciphers) { if (!supportedCiphers.contains(cipher)) throw new InvalidParameterException("Unknown cipher " + cipher); if (cipher.contains("_RC4_")) log.warn("Cipher " + cipher + " uses RC4, which is deprecated."); } } else { // use all default ciphers except those using RC4 String supportedCiphers[] = sslc.getSocketFactory().getDefaultCipherSuites(); ArrayList<String> ciphers = new ArrayList<String>(supportedCiphers.length); for (String cipher : supportedCiphers) if (!cipher.contains("_RC4_")) ciphers.add(cipher); sortCiphers(ciphers); this.ciphers = ciphers.toArray(new String[ciphers.size()]); } if (setUseCipherSuitesOrderMethod == null) log.warn( "Cannot set the cipher suite order before Java 8. This prevents Forward Secrecy with some SSL clients."); if (sslParser.getProtocols() != null) { protocols = sslParser.getProtocols().split(","); } else { protocols = null; } if (sslParser.getClientAuth() == null) { needClientAuth = false; wantClientAuth = false; } else if (sslParser.getClientAuth().equals("need")) { needClientAuth = true; wantClientAuth = true; } else if (sslParser.getClientAuth().equals("want")) { needClientAuth = false; wantClientAuth = true; } else { throw new RuntimeException("Invalid value '" + sslParser.getClientAuth() + "' in clientAuth: expected 'want', 'need' or not set."); } } catch (Exception e) { throw new RuntimeException(e); } }
From source file:ch.cyberduck.core.ssl.CertificateStoreX509KeyManager.java
@Override public List<String> list() { // List of issuer distinguished name final List<String> list = new ArrayList<String>(); try {/*w w w. j a va 2 s . c o m*/ final KeyStore store; try { store = this.getKeystore(); } catch (IOException e) { log.warn(String.format("Failure listing aliases. %s", e.getMessage())); return Collections.emptyList(); } final Enumeration<String> aliases = store.aliases(); while (aliases.hasMoreElements()) { final String alias = aliases.nextElement(); if (log.isDebugEnabled()) { log.debug(String.format("Alias in Keychain %s", alias)); } if (store.isKeyEntry(alias)) { if (log.isInfoEnabled()) { log.info(String.format("Found private key for %s", alias)); } list.add(alias); } else { log.warn(String.format("Missing private key for alias %s", alias)); } } } catch (KeyStoreException e) { log.error(String.format("Keystore not loaded %s", e.getMessage())); } return list; }
From source file:org.cesecore.keys.util.KeyTools.java
/** * Convert a KeyStore to PEM format.//from w ww . j av a2 s . c o m */ public static byte[] getSinglePemFromKeyStore(final KeyStore ks, final char[] password) throws KeyStoreException, CertificateEncodingException, IOException, UnrecoverableKeyException, NoSuchAlgorithmException { final ByteArrayOutputStream buffer = new ByteArrayOutputStream(); // Find the key private key entry in the keystore final Enumeration<String> e = ks.aliases(); Object o = null; String alias = ""; PrivateKey serverPrivKey = null; while (e.hasMoreElements()) { o = e.nextElement(); if (o instanceof String) { if ((ks.isKeyEntry((String) o)) && ((serverPrivKey = (PrivateKey) ks.getKey((String) o, password)) != null)) { alias = (String) o; break; } } } byte[] privKeyEncoded = "".getBytes(); if (serverPrivKey != null) { privKeyEncoded = serverPrivKey.getEncoded(); } final Certificate[] chain = KeyTools.getCertChain(ks, (String) o); final X509Certificate userX509Certificate = (X509Certificate) chain[0]; final byte[] output = userX509Certificate.getEncoded(); String sn = CertTools.getSubjectDN(userX509Certificate); String subjectdnpem = sn.replace(',', '/'); String issuerdnpem = CertTools.getIssuerDN(userX509Certificate).replace(',', '/'); buffer.write(BAG_ATTRIBUTES); buffer.write(FRIENDLY_NAME); buffer.write(alias.getBytes()); buffer.write(NL); buffer.write(BEGIN_PRIVATE_KEY); buffer.write(NL); final byte[] privKey = Base64.encode(privKeyEncoded); buffer.write(privKey); buffer.write(NL); buffer.write(END_PRIVATE_KEY); buffer.write(NL); buffer.write(BAG_ATTRIBUTES); buffer.write(FRIENDLY_NAME); buffer.write(alias.getBytes()); buffer.write(NL); buffer.write(SUBJECT_ATTRIBUTE); buffer.write(subjectdnpem.getBytes()); buffer.write(NL); buffer.write(ISSUER_ATTRIBUTE); buffer.write(issuerdnpem.getBytes()); buffer.write(NL); buffer.write(BEGIN_CERTIFICATE); buffer.write(NL); final byte[] userCertB64 = Base64.encode(output); buffer.write(userCertB64); buffer.write(NL); buffer.write(END_CERTIFICATE); buffer.write(NL); if (!CertTools.isSelfSigned(userX509Certificate)) { for (int num = 1; num < chain.length; num++) { final X509Certificate tmpX509Cert = (X509Certificate) chain[num]; sn = CertTools.getSubjectDN(tmpX509Cert); String cn = CertTools.getPartFromDN(sn, "CN"); if (StringUtils.isEmpty(cn)) { cn = "Unknown"; } subjectdnpem = sn.replace(',', '/'); issuerdnpem = CertTools.getIssuerDN(tmpX509Cert).replace(',', '/'); buffer.write(BAG_ATTRIBUTES); buffer.write(FRIENDLY_NAME); buffer.write(cn.getBytes()); buffer.write(NL); buffer.write(SUBJECT_ATTRIBUTE); buffer.write(subjectdnpem.getBytes()); buffer.write(NL); buffer.write(ISSUER_ATTRIBUTE); buffer.write(issuerdnpem.getBytes()); buffer.write(NL); final byte[] tmpOutput = tmpX509Cert.getEncoded(); buffer.write(BEGIN_CERTIFICATE); buffer.write(NL); final byte[] tmpCACertB64 = Base64.encode(tmpOutput); buffer.write(tmpCACertB64); buffer.write(NL); buffer.write(END_CERTIFICATE); buffer.write(NL); } } return buffer.toByteArray(); }
From source file:org.nuxeo.ecm.core.storage.sql.S3BinaryManager.java
@Override protected void setupCloudClient() throws IOException { // Get settings from the configuration bucketName = getProperty(BUCKET_NAME_PROPERTY); bucketNamePrefix = MoreObjects.firstNonNull(getProperty(BUCKET_PREFIX_PROPERTY), StringUtils.EMPTY); String bucketRegion = getProperty(BUCKET_REGION_PROPERTY); if (isBlank(bucketRegion)) { bucketRegion = DEFAULT_BUCKET_REGION; }/*from w ww.ja v a 2 s .c om*/ String awsID = getProperty(AWS_ID_PROPERTY); String awsSecret = getProperty(AWS_SECRET_PROPERTY); String proxyHost = Framework.getProperty(Environment.NUXEO_HTTP_PROXY_HOST); String proxyPort = Framework.getProperty(Environment.NUXEO_HTTP_PROXY_PORT); String proxyLogin = Framework.getProperty(Environment.NUXEO_HTTP_PROXY_LOGIN); String proxyPassword = Framework.getProperty(Environment.NUXEO_HTTP_PROXY_PASSWORD); int maxConnections = getIntProperty(CONNECTION_MAX_PROPERTY); int maxErrorRetry = getIntProperty(CONNECTION_RETRY_PROPERTY); int connectionTimeout = getIntProperty(CONNECTION_TIMEOUT_PROPERTY); int socketTimeout = getIntProperty(SOCKET_TIMEOUT_PROPERTY); String keystoreFile = getProperty(KEYSTORE_FILE_PROPERTY); String keystorePass = getProperty(KEYSTORE_PASS_PROPERTY); String privkeyAlias = getProperty(PRIVKEY_ALIAS_PROPERTY); String privkeyPass = getProperty(PRIVKEY_PASS_PROPERTY); String endpoint = getProperty(ENDPOINT_PROPERTY); String sseprop = getProperty(SERVERSIDE_ENCRYPTION_PROPERTY); if (isNotBlank(sseprop)) { userServerSideEncryption = Boolean.parseBoolean(sseprop); } // Fallback on default env keys for ID and secret if (isBlank(awsID)) { awsID = System.getenv(AWS_ID_ENV); } if (isBlank(awsSecret)) { awsSecret = System.getenv(AWS_SECRET_ENV); } if (isBlank(bucketName)) { throw new RuntimeException("Missing conf: " + BUCKET_NAME_PROPERTY); } if (!isBlank(bucketNamePrefix) && !bucketNamePrefix.endsWith("/")) { log.warn(String.format("%s %s S3 bucket prefix should end by '/' " + ": added automatically.", BUCKET_PREFIX_PROPERTY, bucketNamePrefix)); bucketNamePrefix += "/"; } // set up credentials if (isBlank(awsID) || isBlank(awsSecret)) { awsCredentialsProvider = new InstanceProfileCredentialsProvider(); try { awsCredentialsProvider.getCredentials(); } catch (AmazonClientException e) { throw new RuntimeException("Missing AWS credentials and no instance role found"); } } else { awsCredentialsProvider = new BasicAWSCredentialsProvider(awsID, awsSecret); } // set up client configuration clientConfiguration = new ClientConfiguration(); if (isNotBlank(proxyHost)) { clientConfiguration.setProxyHost(proxyHost); } if (isNotBlank(proxyPort)) { clientConfiguration.setProxyPort(Integer.parseInt(proxyPort)); } if (isNotBlank(proxyLogin)) { clientConfiguration.setProxyUsername(proxyLogin); } if (proxyPassword != null) { // could be blank clientConfiguration.setProxyPassword(proxyPassword); } if (maxConnections > 0) { clientConfiguration.setMaxConnections(maxConnections); } if (maxErrorRetry >= 0) { // 0 is allowed clientConfiguration.setMaxErrorRetry(maxErrorRetry); } if (connectionTimeout >= 0) { // 0 is allowed clientConfiguration.setConnectionTimeout(connectionTimeout); } if (socketTimeout >= 0) { // 0 is allowed clientConfiguration.setSocketTimeout(socketTimeout); } // set up encryption encryptionMaterials = null; if (isNotBlank(keystoreFile)) { boolean confok = true; if (keystorePass == null) { // could be blank log.error("Keystore password missing"); confok = false; } if (isBlank(privkeyAlias)) { log.error("Key alias missing"); confok = false; } if (privkeyPass == null) { // could be blank log.error("Key password missing"); confok = false; } if (!confok) { throw new RuntimeException("S3 Crypto configuration incomplete"); } try { // Open keystore File ksFile = new File(keystoreFile); FileInputStream ksStream = new FileInputStream(ksFile); KeyStore keystore = KeyStore.getInstance(KeyStore.getDefaultType()); keystore.load(ksStream, keystorePass.toCharArray()); ksStream.close(); // Get keypair for alias if (!keystore.isKeyEntry(privkeyAlias)) { throw new RuntimeException("Alias " + privkeyAlias + " is missing or not a key alias"); } PrivateKey privKey = (PrivateKey) keystore.getKey(privkeyAlias, privkeyPass.toCharArray()); Certificate cert = keystore.getCertificate(privkeyAlias); PublicKey pubKey = cert.getPublicKey(); KeyPair keypair = new KeyPair(pubKey, privKey); // Get encryptionMaterials from keypair encryptionMaterials = new EncryptionMaterials(keypair); cryptoConfiguration = new CryptoConfiguration(); } catch (IOException | GeneralSecurityException e) { throw new RuntimeException("Could not read keystore: " + keystoreFile + ", alias: " + privkeyAlias, e); } } isEncrypted = encryptionMaterials != null; // Try to create bucket if it doesn't exist if (!isEncrypted) { amazonS3 = new AmazonS3Client(awsCredentialsProvider, clientConfiguration); } else { amazonS3 = new AmazonS3EncryptionClient(awsCredentialsProvider, new StaticEncryptionMaterialsProvider(encryptionMaterials), clientConfiguration, cryptoConfiguration); } if (isNotBlank(endpoint)) { amazonS3.setEndpoint(endpoint); } // Set region explicitely for regions that reguire Version 4 signature ArrayList<String> V4_ONLY_REGIONS = new ArrayList<String>(); V4_ONLY_REGIONS.add("eu-central-1"); V4_ONLY_REGIONS.add("ap-northeast-2"); if (V4_ONLY_REGIONS.contains(bucketRegion)) { amazonS3.setRegion(Region.getRegion(Regions.fromName(bucketRegion))); } try { if (!amazonS3.doesBucketExist(bucketName)) { amazonS3.createBucket(bucketName, bucketRegion); amazonS3.setBucketAcl(bucketName, CannedAccessControlList.Private); } } catch (AmazonClientException e) { throw new IOException(e); } // compat for NXP-17895, using "downloadfroms3", to be removed // these two fields have already been initialized by the base class initialize() // using standard property "directdownload" String dd = getProperty(DIRECTDOWNLOAD_PROPERTY_COMPAT); if (dd != null) { directDownload = Boolean.parseBoolean(dd); } int dde = getIntProperty(DIRECTDOWNLOAD_EXPIRE_PROPERTY_COMPAT); if (dde >= 0) { directDownloadExpire = dde; } transferManager = new TransferManager(amazonS3); abortOldUploads(); }
From source file:com.adito.keystore.actions.ShowKeyStoreDispatchAction.java
/** * @param mapping// w ww .j a v a 2 s .c om * @param form * @param request * @param response * @return ActionForward * @throws Exception */ public ActionForward exportPrivate(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { String sel = ((ShowKeyStoreForm) form).getSelectedItem(); KeyStore systemClientStore = ((ShowKeyStoreForm) form).getSelectedKeyStore().getKeyStore(); FileDownloadPageInterceptListener l = (FileDownloadPageInterceptListener) CoreUtil .getPageInterceptListenerById(request.getSession(), "fileDownload"); if (l == null) { l = new FileDownloadPageInterceptListener(); CoreUtil.addPageInterceptListener(request.getSession(), l); } File clientCertFile = new File(CoreUtil.getTempDownloadDirectory(getSessionInfo(request)), sel + ".p12"); FileOutputStream out = new FileOutputStream(clientCertFile); char[] password = ((ShowKeyStoreForm) form).getSelectedKeyStore().getKeyStorePassword().toCharArray(); if (systemClientStore.isKeyEntry(sel)) { PrivateKey keypair = ((ShowKeyStoreForm) form).getSelectedKeyStore().getPrivateKey(sel, password); KeyStore userStore = KeyStore.getInstance("PKCS12", "BC"); userStore.load(null, null); userStore.setKeyEntry(sel, keypair, ((ShowKeyStoreForm) form).getPassword().toCharArray(), ((ShowKeyStoreForm) form).getSelectedKeyStore().getCertificateChain(sel)); userStore.store(out, ((ShowKeyStoreForm) form).getPassword().toCharArray()); out.close(); } l.addDownload(new CSRDownload(clientCertFile, clientCertFile.getName(), "application/octet-stream", mapping.findForward("success"), "exportPrivateKey.message", "keystore", sel)); return mapping.findForward("success"); }