List of usage examples for java.security KeyStore aliases
public final Enumeration<String> aliases() throws KeyStoreException
From source file:com.app.mvc.http.ext.AuthSSLProtocolSocketFactory.java
private SSLContext createSSLContext() { try {/*from w w w. j ava2 s . c o m*/ KeyManager[] keymanagers = null; TrustManager[] trustmanagers = null; if (this.keystoreUrl != null) { KeyStore keystore = createKeyStore(this.keystoreUrl, this.keystorePassword); if (log.isDebugEnabled()) { Enumeration aliases = keystore.aliases(); while (aliases.hasMoreElements()) { String alias = (String) aliases.nextElement(); Certificate[] certs = keystore.getCertificateChain(alias); if (certs != null) { log.debug("Certificate chain '" + alias + "':"); for (int c = 0; c < certs.length; c++) { if (certs[c] instanceof X509Certificate) { X509Certificate cert = (X509Certificate) certs[c]; log.debug(" Certificate " + (c + 1) + ":"); log.debug(" Subject DN: " + cert.getSubjectDN()); log.debug(" Signature Algorithm: " + cert.getSigAlgName()); log.debug(" Valid from: " + cert.getNotBefore()); log.debug(" Valid until: " + cert.getNotAfter()); log.debug(" Issuer: " + cert.getIssuerDN()); } } } } } keymanagers = createKeyManagers(keystore, this.keystorePassword); } if (this.truststoreUrl != null) { KeyStore keystore = createKeyStore(this.truststoreUrl, this.truststorePassword); if (log.isDebugEnabled()) { Enumeration aliases = keystore.aliases(); while (aliases.hasMoreElements()) { String alias = (String) aliases.nextElement(); log.debug("Trusted certificate '" + alias + "':"); Certificate trustedcert = keystore.getCertificate(alias); if (trustedcert != null && trustedcert instanceof X509Certificate) { X509Certificate cert = (X509Certificate) trustedcert; log.debug(" Subject DN: " + cert.getSubjectDN()); log.debug(" Signature Algorithm: " + cert.getSigAlgName()); log.debug(" Valid from: " + cert.getNotBefore()); log.debug(" Valid until: " + cert.getNotAfter()); log.debug(" Issuer: " + cert.getIssuerDN()); } } } trustmanagers = createTrustManagers(keystore); } SSLContext sslcontext = SSLContext.getInstance("SSL"); sslcontext.init(keymanagers, trustmanagers, null); return sslcontext; } catch (NoSuchAlgorithmException e) { log.error(e.getMessage(), e); throw new AuthSSLInitializationError("Unsupported algorithm exception: " + e.getMessage()); } catch (KeyStoreException e) { log.error(e.getMessage(), e); throw new AuthSSLInitializationError("Keystore exception: " + e.getMessage()); } catch (GeneralSecurityException e) { log.error(e.getMessage(), e); throw new AuthSSLInitializationError("Key management exception: " + e.getMessage()); } catch (IOException e) { log.error(e.getMessage(), e); throw new AuthSSLInitializationError("I/O error reading keystore/truststore file: " + e.getMessage()); } }
From source file:org.codice.ddf.security.ocsp.checker.OcspChecker.java
/** * Returns an {@link X509CertificateHolder} containing the issuer of the given {@param name}. * Search is performed in the given {@param truststore}. * * @param name - the {@link X500Name} of the issuer. * @param truststore - the {@link KeyStore} to check. * @return {@link X509CertificateHolder} of the certificate with the given {@param name}. * @throws OcspCheckerException if the {@param name} cannot be found in the {@param truststore}. *//*from www . ja va 2 s . co m*/ private X509CertificateHolder getCertFromTruststoreWithX500Name(X500Name name, KeyStore truststore) throws OcspCheckerException { Enumeration<String> aliases; try { aliases = truststore.aliases(); } catch (KeyStoreException e) { throw new OcspCheckerException("Problem getting aliases from truststore." + NOT_VERIFIED_MSG, e); } while (aliases.hasMoreElements()) { String currentAlias = aliases.nextElement(); try { java.security.cert.Certificate currentCert = truststore.getCertificate(currentAlias); X509CertificateHolder currentCertHolder = new X509CertificateHolder(currentCert.getEncoded()); X500Name currentName = currentCertHolder.getSubject(); if (name.equals(currentName)) { return currentCertHolder; } } catch (CertificateEncodingException | IOException | KeyStoreException e) { LOGGER.debug("Problem loading truststore certificate." + CONTINUING_MSG, e); } } throw new OcspCheckerException( String.format("Could not find cert matching X500Name of %s.", name) + NOT_VERIFIED_MSG); }
From source file:org.jboss.additional.testsuite.jdkall.present.elytron.application.CredentialStoreTestCase.java
/** * Tests credential store with automatically created PKCS12 keystore. *//* w w w. ja va2 s. co m*/ @Test @Ignore public void testCredentialStoreCreating() throws Exception { String storeName = NAME; File tempFolder = Utils.createTemporaryFolder(storeName); String fileName = System.currentTimeMillis() + ".p12"; File ksFile = new File(tempFolder, fileName); assertTrue(tempFolder.isDirectory()); assertFalse(ksFile.exists()); try { try (CLIWrapper cli = new CLIWrapper(true)) { cli.sendLine(String.format("/path=%s:add(path=\"%s\")", storeName, asAbsolutePath(tempFolder))); SimpleCredentialStore storeConfig = SimpleCredentialStore.builder().withName(storeName) .withKeyStorePath(Path.builder().withPath(fileName).withRelativeTo(storeName).build()) .withCredential(CredentialReference.builder().withClearText("pkcs12pass").build()) .withKeyStoreType("PKCS12").withModifiable(true).withCreate(true) .withAlias("elytron", "rocks!").build(); try { storeConfig.create(cli); assertContainsAliases(cli, storeName, "elytron"); assertTrue(ksFile.exists()); cli.sendLine(String.format( "/subsystem=elytron/credential-store=%s:add-alias(alias=another-secret, secret-value=\"%1$s\")", storeName)); assertCredentialValue(storeName, "elytron", "rocks!"); assertCredentialValue(storeName, "another-secret", storeName); } finally { // this should remove alias "elytron" from KeyStore file and remove credential {@value NAME} from domain // model storeConfig.remove(cli); } // KeyStore file should not be removed after assertTrue(ksFile.exists()); KeyStore ks = KeyStore.getInstance("PKCS12"); try (FileInputStream fis = new FileInputStream(ksFile)) { ks.load(fis, "pkcs12pass".toCharArray()); assertEquals(1, ks.size()); assertTrue(ks.aliases().nextElement().contains("another-secret")); } } } finally { FileUtils.deleteQuietly(tempFolder); } }
From source file:org.miloss.fgsms.bueller.AuthSSLProtocolSocketFactory.java
private SSLContext createSSLContext() { try {//from w ww . j a v a2 s. c o m KeyManager[] keymanagers = null; TrustManager[] trustmanagers = null; if (this.keystoreUrl != null) { KeyStore keystore = createKeyStore(this.keystoreUrl, this.keystorePassword); if (LOG.isDebugEnabled()) { Enumeration aliases = keystore.aliases(); while (aliases.hasMoreElements()) { String alias = (String) aliases.nextElement(); Certificate[] certs = keystore.getCertificateChain(alias); if (certs != null) { LOG.debug("Certificate chain '" + alias + "':"); for (int c = 0; c < certs.length; c++) { if (certs[c] instanceof X509Certificate) { X509Certificate cert = (X509Certificate) certs[c]; LOG.debug(" Certificate " + (c + 1) + ":"); LOG.debug(" Subject DN: " + cert.getSubjectDN()); LOG.debug(" Signature Algorithm: " + cert.getSigAlgName()); LOG.debug(" Valid from: " + cert.getNotBefore()); LOG.debug(" Valid until: " + cert.getNotAfter()); LOG.debug(" Issuer: " + cert.getIssuerDN()); } } } } } keymanagers = createKeyManagers(keystore, this.keystorePassword); } if (this.truststoreUrl != null) { KeyStore keystore = createKeyStore(this.truststoreUrl, this.truststorePassword); if (LOG.isDebugEnabled()) { Enumeration aliases = keystore.aliases(); while (aliases.hasMoreElements()) { String alias = (String) aliases.nextElement(); LOG.debug("Trusted certificate '" + alias + "':"); Certificate trustedcert = keystore.getCertificate(alias); if (trustedcert != null && trustedcert instanceof X509Certificate) { X509Certificate cert = (X509Certificate) trustedcert; LOG.debug(" Subject DN: " + cert.getSubjectDN()); LOG.debug(" Signature Algorithm: " + cert.getSigAlgName()); LOG.debug(" Valid from: " + cert.getNotBefore()); LOG.debug(" Valid until: " + cert.getNotAfter()); LOG.debug(" Issuer: " + cert.getIssuerDN()); } } } trustmanagers = createTrustManagers(keystore); } SSLContext sslcontext = SSLContext.getInstance("SSL"); sslcontext.init(keymanagers, trustmanagers, null); return sslcontext; } catch (NoSuchAlgorithmException e) { LOG.error(e.getMessage(), e); // throw new AuthSSLInitializationError("Unsupported algorithm exception: " + e.getMessage()); } catch (KeyStoreException e) { LOG.error(e.getMessage(), e); // throw new AuthSSLInitializationError("Keystore exception: " + e.getMessage()); } catch (GeneralSecurityException e) { LOG.error(e.getMessage(), e); // throw new AuthSSLInitializationError("Key management exception: " + e.getMessage()); } catch (IOException e) { LOG.error(e.getMessage(), e); // throw new AuthSSLInitializationError("I/O error reading keystore/truststore file: " + e.getMessage()); } return null; }
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 www . ja 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:com.polyvi.xface.view.XWebViewClient.java
/** * android4.0???SSLContext Android 4.x//from www . ja v a 2 s . com * 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:org.ejbca.core.protocol.ws.client.NestedCrmfRequestTestCommand.java
private void init(String args[]) { FileInputStream file_inputstream; try {//from w w w. java 2 s . co m String pwd = args[ARG_KEYSTOREPASSWORD]; String certNameInKeystore = args[ARG_CERTNAMEINKEYSTORE]; file_inputstream = new FileInputStream(args[ARG_KEYSTOREPATH]); KeyStore keyStore = KeyStore.getInstance("PKCS12"); keyStore.load(file_inputstream, pwd.toCharArray()); System.out.println("Keystore size " + keyStore.size()); Enumeration aliases = keyStore.aliases(); while (aliases.hasMoreElements()) { System.out.println(aliases.nextElement()); } Key key = keyStore.getKey(certNameInKeystore, pwd.toCharArray()); getPrintStream().println("Key information " + key.getAlgorithm() + " " + key.getFormat()); PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(key.getEncoded()); KeyFactory keyFactory = KeyFactory.getInstance("RSA"); innerSignKey = keyFactory.generatePrivate(keySpec); innerCertificate = keyStore.getCertificate(certNameInKeystore); } catch (FileNotFoundException e2) { e2.printStackTrace(); } catch (KeyStoreException e) { e.printStackTrace(); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } catch (CertificateException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } catch (UnrecoverableKeyException e) { e.printStackTrace(); } catch (InvalidKeySpecException e) { e.printStackTrace(); } try { KeyPair outerSignKeys = KeyTools.genKeys("1024", "RSA"); outerSignKey = outerSignKeys.getPrivate(); X509Certificate signCert = CertTools.genSelfCert("CN=cmpTest,C=SE", 5000, null, outerSignKeys.getPrivate(), outerSignKeys.getPublic(), PKCSObjectIdentifiers.sha256WithRSAEncryption.getId(), true, "BC"); writeCertificate(signCert, "/opt/racerts", "cmpTest.pem"); /* ArrayList<Certificate> certCollection = new ArrayList<Certificate>(); certCollection.add(signCert); byte[] pemRaCert = CertTools.getPEMFromCerts(certCollection); FileOutputStream out = new FileOutputStream(new File("/opt/racerts/cmpStressTest.pem")); out.write(pemRaCert); out.close(); */ } catch (NoSuchAlgorithmException e1) { e1.printStackTrace(); } catch (NoSuchProviderException e1) { e1.printStackTrace(); } catch (InvalidAlgorithmParameterException e1) { e1.printStackTrace(); } catch (InvalidKeyException e) { e.printStackTrace(); } catch (CertificateEncodingException e) { e.printStackTrace(); } catch (SignatureException e) { e.printStackTrace(); } catch (IllegalStateException e) { e.printStackTrace(); //} catch (FileNotFoundException e) { // e.printStackTrace(); //} catch (IOException e) { // e.printStackTrace(); //} catch (CertificateException e) { // e.printStackTrace(); } }
From source file:test.integ.be.e_contract.mycarenet.genins.GenericInsurabilityClientTest.java
@Test public void testSTSNurse() throws Exception { EHealthSTSClient client = new EHealthSTSClient("https://wwwacc.ehealth.fgov.be/sts_1_1/SecureTokenService"); Security.addProvider(new BeIDProvider()); KeyStore keyStore = KeyStore.getInstance("BeID"); keyStore.load(null);/*from www . j a v a2 s . com*/ PrivateKey authnPrivateKey = (PrivateKey) keyStore.getKey("Authentication", null); X509Certificate authnCertificate = (X509Certificate) keyStore.getCertificate("Authentication"); KeyStore eHealthKeyStore = KeyStore.getInstance("PKCS12"); FileInputStream fileInputStream = new FileInputStream(this.config.getEHealthPKCS12Path()); eHealthKeyStore.load(fileInputStream, this.config.getEHealthPKCS12Password().toCharArray()); Enumeration<String> aliasesEnum = eHealthKeyStore.aliases(); String alias = aliasesEnum.nextElement(); X509Certificate eHealthCertificate = (X509Certificate) eHealthKeyStore.getCertificate(alias); PrivateKey eHealthPrivateKey = (PrivateKey) eHealthKeyStore.getKey(alias, this.config.getEHealthPKCS12Password().toCharArray()); List<Attribute> attributes = new LinkedList<Attribute>(); attributes.add(new Attribute("urn:be:fgov:identification-namespace", "urn:be:fgov:ehealth:1.0:certificateholder:person:ssin")); attributes.add(new Attribute("urn:be:fgov:identification-namespace", "urn:be:fgov:person:ssin")); List<AttributeDesignator> attributeDesignators = new LinkedList<AttributeDesignator>(); attributeDesignators.add(new AttributeDesignator("urn:be:fgov:identification-namespace", "urn:be:fgov:ehealth:1.0:certificateholder:person:ssin")); attributeDesignators .add(new AttributeDesignator("urn:be:fgov:identification-namespace", "urn:be:fgov:person:ssin")); attributeDesignators.add(new AttributeDesignator("urn:be:fgov:certified-namespace:ehealth", "urn:be:fgov:person:ssin:nurse:boolean")); Element assertion = client.requestAssertion(authnCertificate, authnPrivateKey, eHealthCertificate, eHealthPrivateKey, attributes, attributeDesignators); assertNotNull(assertion); String assertionString = client.toString(assertion); LOG.debug("SAML assertion: " + assertionString); }
From source file:test.integ.be.e_contract.mycarenet.genins.GenericInsurabilityClientTest.java
@Test public void testSTSDoctor() throws Exception { EHealthSTSClient client = new EHealthSTSClient("https://wwwacc.ehealth.fgov.be/sts_1_1/SecureTokenService"); Security.addProvider(new BeIDProvider()); KeyStore keyStore = KeyStore.getInstance("BeID"); keyStore.load(null);// ww w. jav a 2s . co m PrivateKey authnPrivateKey = (PrivateKey) keyStore.getKey("Authentication", null); X509Certificate authnCertificate = (X509Certificate) keyStore.getCertificate("Authentication"); KeyStore eHealthKeyStore = KeyStore.getInstance("PKCS12"); FileInputStream fileInputStream = new FileInputStream(this.config.getEHealthPKCS12Path()); eHealthKeyStore.load(fileInputStream, this.config.getEHealthPKCS12Password().toCharArray()); Enumeration<String> aliasesEnum = eHealthKeyStore.aliases(); String alias = aliasesEnum.nextElement(); X509Certificate eHealthCertificate = (X509Certificate) eHealthKeyStore.getCertificate(alias); PrivateKey eHealthPrivateKey = (PrivateKey) eHealthKeyStore.getKey(alias, this.config.getEHealthPKCS12Password().toCharArray()); List<Attribute> attributes = new LinkedList<Attribute>(); attributes.add(new Attribute("urn:be:fgov:identification-namespace", "urn:be:fgov:ehealth:1.0:certificateholder:person:ssin")); attributes.add(new Attribute("urn:be:fgov:identification-namespace", "urn:be:fgov:person:ssin")); List<AttributeDesignator> attributeDesignators = new LinkedList<AttributeDesignator>(); attributeDesignators.add(new AttributeDesignator("urn:be:fgov:identification-namespace", "urn:be:fgov:ehealth:1.0:certificateholder:person:ssin")); attributeDesignators .add(new AttributeDesignator("urn:be:fgov:identification-namespace", "urn:be:fgov:person:ssin")); attributeDesignators.add(new AttributeDesignator("urn:be:fgov:certified-namespace:ehealth", "urn:be:fgov:person:ssin:ehealth:1.0:doctor:nihii11")); attributeDesignators.add(new AttributeDesignator("urn:be:fgov:certified-namespace:ehealth", "urn:be:fgov:person:ssin:doctor:boolean")); Element assertion = client.requestAssertion(authnCertificate, authnPrivateKey, eHealthCertificate, eHealthPrivateKey, attributes, attributeDesignators); assertNotNull(assertion); String assertionString = client.toString(assertion); LOG.debug("SAML assertion: " + assertionString); }
From source file:org.sonatype.flexmojos.air.SignAirMojo.java
@SuppressWarnings("unchecked") public void execute() throws MojoExecutionException, MojoFailureException { AIRPackager airPackager = new AIRPackager(); try {//from w w w . ja v a 2 s. com String c = this.classifier == null ? "" : "-" + this.classifier; File output = new File(project.getBuild().getDirectory(), project.getBuild().getFinalName() + c + "." + AIR); airPackager.setOutput(output); airPackager.setDescriptor(getAirDescriptor()); KeyStore keyStore = KeyStore.getInstance(storetype); keyStore.load(new FileInputStream(keystore.getAbsolutePath()), storepass.toCharArray()); String alias = keyStore.aliases().nextElement(); airPackager.setPrivateKey((PrivateKey) keyStore.getKey(alias, storepass.toCharArray())); airPackager.setSignerCertificate(keyStore.getCertificate(alias)); airPackager.setCertificateChain(keyStore.getCertificateChain(alias)); if (this.timestampURL != null) { airPackager.setTimestampURL(TIMESTAMP_NONE.equals(this.timestampURL) ? null : this.timestampURL); } String packaging = project.getPackaging(); if (AIR.equals(packaging)) { Set<Artifact> deps = project.getDependencyArtifacts(); for (Artifact artifact : deps) { if (SWF.equals(artifact.getType())) { File source = artifact.getFile(); String path = source.getName(); if (stripVersion && path.contains(artifact.getVersion())) { path = path.replace("-" + artifact.getVersion(), ""); } getLog().debug(" adding source " + source + " with path " + path); airPackager.addSourceWithPath(source, path); } } } else if (SWF.equals(packaging)) { File source = project.getArtifact().getFile(); String path = source.getName(); getLog().debug(" adding source " + source + " with path " + path); airPackager.addSourceWithPath(source, path); } else { throw new MojoFailureException("Unexpected project packaging " + packaging); } if (includeFiles == null && includeFileSets == null) { includeFileSets = resources.toArray(new FileSet[0]); } if (includeFiles != null) { for (final String includePath : includeFiles) { String directory = project.getBuild().getOutputDirectory(); addSourceWithPath(airPackager, directory, includePath); } } if (includeFileSets != null) { for (FileSet set : includeFileSets) { DirectoryScanner scanner = new DirectoryScanner(); scanner.setBasedir(set.getDirectory()); scanner.setIncludes((String[]) set.getIncludes().toArray(new String[0])); scanner.setExcludes((String[]) set.getExcludes().toArray(new String[0])); scanner.addDefaultExcludes(); scanner.scan(); String[] files = scanner.getIncludedFiles(); for (String path : files) { addSourceWithPath(airPackager, set.getDirectory(), path); } } } if (classifier != null) { projectHelper.attachArtifact(project, project.getArtifact().getType(), classifier, output); } else if (SWF.equals(packaging)) { projectHelper.attachArtifact(project, AIR, output); } else { project.getArtifact().setFile(output); } final List<Message> messages = new ArrayList<Message>(); airPackager.setListener(new Listener() { public void message(final Message message) { messages.add(message); } public void progress(final int soFar, final int total) { getLog().info(" completed " + soFar + " of " + total); } }); airPackager.createAIR(); if (messages.size() > 0) { for (final Message message : messages) { getLog().error(" " + message.errorDescription); } throw new MojoExecutionException("Error creating AIR application"); } else { getLog().info(" AIR package created: " + output.getAbsolutePath()); } } catch (MojoExecutionException e) { // do not handle throw e; } catch (Exception e) { throw new MojoExecutionException("Error invoking AIR api", e); } finally { airPackager.close(); } }