List of usage examples for java.security KeyStore getCertificate
public final Certificate getCertificate(String alias) throws KeyStoreException
From source file:org.apache.directory.studio.connection.core.StudioKeyStoreManager.java
/** * Gets the certificates contained in the key store. * //from w w w . j ava 2 s . c o m * @return the certificates */ public X509Certificate[] getCertificates() throws CertificateException { try { List<X509Certificate> certificateList = new ArrayList<X509Certificate>(); KeyStore keyStore = getKeyStore(); Enumeration<String> aliases = keyStore.aliases(); while (aliases.hasMoreElements()) { String alias = aliases.nextElement(); Certificate certificate = keyStore.getCertificate(alias); if (certificate instanceof X509Certificate) { certificateList.add((X509Certificate) certificate); } } return certificateList.toArray(new X509Certificate[0]); } catch (KeyStoreException e) { throw new CertificateException(Messages.StudioKeyStoreManager_CantReadTrustStore, e); } }
From source file:com.aaasec.sigserv.cssigapp.KeyStoreFactory.java
public KeyStoreObjects getKeyStoreObjects(String reserver) { String keyStoreId = ""; File privateKsFile = new File(tempKeyStoreDir, reserver); File[] listFiles = new File(keyStoreDir).listFiles(noLeadingDot); int cnt = listFiles.length; int select = rng.nextInt(cnt); File selected;//from w w w .j a v a 2 s . co m boolean success = false; // try to claim a ks file; try { selected = listFiles[select]; keyStoreId = selected.getName(); selected.renameTo(privateKsFile); success = privateKsFile.canRead(); } catch (Exception ex) { } // If not successful - generate a new key store if (!success) { createKeyStore(privateKsFile); keyStoreId = reserver; } try { KeyStore ks = getKeyStore(privateKsFile, keyStoreId); PrivateKey pk = (PrivateKey) ks.getKey(K_NAME, getKsPass(keyStoreId)); Certificate cert = ks.getCertificate(K_NAME); iaik.x509.X509Certificate x509cert = CertificateUtils.getCertificate(cert.getEncoded()); privateKsFile.delete(); return new KeyStoreObjects(pk, x509cert); } catch (Exception ex) { LOG.log(Level.WARNING, null, ex); privateKsFile.delete(); return null; } }
From source file:org.opendaylight.aaa.cert.impl.ODLMdsalKeyTool.java
public String getCertificate(final KeyStore keyStore, final String keyStorePwd, final String certAlias, final boolean withTag) { try {//from ww w .j a v a 2 s . c o m if (keyStore.containsAlias(certAlias)) { final X509Certificate odlCert = (X509Certificate) keyStore.getCertificate(certAlias); final String cert = DatatypeConverter.printBase64Binary(odlCert.getEncoded()); if (withTag) { final StringBuilder sb = new StringBuilder(); sb.append(KeyStoreConstant.BEGIN_CERTIFICATE); sb.append("\n"); sb.append(cert); sb.append("\n"); sb.append(KeyStoreConstant.END_CERTIFICATE); return sb.toString(); } return cert; } LOG.info("KeyStore does not contain alias {}", certAlias); return null; } catch (final CertificateException | KeyStoreException e) { LOG.error("Failed to get Certificate", e); return null; } }
From source file:test.integ.be.agiv.security.CrabReadTest.java
@Test public void testServiceBeID() throws Exception { Security.addProvider(new BeIDProvider()); KeyStore keyStore = KeyStore.getInstance("BeID"); keyStore.load(null);/*from ww w . j a va2 s. c o m*/ PrivateKey privateKey = (PrivateKey) keyStore.getKey("Authentication", null); X509Certificate certificate = (X509Certificate) keyStore.getCertificate("Authentication"); CrabReadService crabReadService = new CrabReadService(); ICrabRead iCrabRead = crabReadService.getWS2007FederationHttpBindingICrabRead(new AddressingFeature()); AGIVSecurity agivSecurity = new AGIVSecurity( "https://auth.beta.agiv.be/ipsts/Services/DaliSecurityTokenServiceConfiguration.svc/CertificateMessage", "https://auth.beta.agiv.be/sts/Services/SalvadorSecurityTokenServiceConfiguration.svc/IWSTrust13", AGIVSecurity.BETA_REALM, certificate, privateKey); BindingProvider bindingProvider = (BindingProvider) iCrabRead; agivSecurity.enable(bindingProvider, "https://crab.beta.agiv.be/read/crabreadservice.svc/wsfed", false, "urn:agiv.be/crab/beta"); ArrayOfstring gemeentes = iCrabRead.listGemeente(); List<String> gemeenteList = gemeentes.getString(); for (String gemeente : gemeenteList) { LOG.debug("gemeente: " + gemeente); } assertTrue(gemeenteList.contains("Vilvoorde")); agivSecurity.refreshSecurityTokens(); }
From source file:net.solarnetwork.node.setup.test.DefaultSetupServiceTest.java
@Test public void renewNetworkCertificate() throws Exception { SetupIdentityInfo info = new SetupIdentityInfo(1L, TEST_CONF_VALUE, TEST_SOLARIN_HOST, getHttpServerPort(), false, TEST_PW_VALUE);/*from w w w . j a va 2s .co m*/ expect(setupIdentityDao.getSetupIdentityInfo()).andReturn(info).atLeastOnce(); replayAll(); keystoreService.saveCACertificate(CA_CERT); keystoreService.generateNodeSelfSignedCertificate(TEST_DN); String csr = keystoreService.generateNodePKCS10CertificateRequestString(); X509Certificate originalCert; PemReader pemReader = new PemReader(new StringReader(csr)); try { PemObject pem = pemReader.readPemObject(); PKCS10CertificationRequest req = new PKCS10CertificationRequest(pem.getContent()); originalCert = PKITestUtils.sign(req, CA_CERT, CA_KEY_PAIR.getPrivate()); String signedPem = PKITestUtils.getPKCS7Encoding(new X509Certificate[] { originalCert }); keystoreService.saveNodeSignedCertificate(signedPem); log.debug("Saved signed node certificate {}:\n{}", originalCert.getSerialNumber(), signedPem); assertThat("Generated CSR", csr, notNullValue()); } finally { pemReader.close(); } // now let's renew! AbstractTestHandler handler = new AbstractTestHandler() { @Override protected boolean handleInternal(String target, HttpServletRequest request, HttpServletResponse response, int dispatch) throws Exception { assertEquals("POST", request.getMethod()); assertEquals("/solarin/api/v1/sec/cert/renew", target); String password = request.getParameter("password"); assertEquals("foobar", password); String keystoreData = request.getParameter("keystore"); assertNotNull(keystoreData); byte[] data = Base64.decodeBase64(keystoreData); KeyStore keyStore = KeyStore.getInstance("pkcs12"); keyStore.load(new ByteArrayInputStream(data), password.toCharArray()); Certificate cert = keyStore.getCertificate("node"); assertNotNull(cert); assertTrue(cert instanceof X509Certificate); X509Certificate nodeCert = (X509Certificate) cert; assertEquals(new X500Principal(TEST_DN), nodeCert.getSubjectX500Principal()); assertEquals(CA_CERT.getSubjectX500Principal(), nodeCert.getIssuerX500Principal()); response.setContentType("application/json"); PrintWriter out = response.getWriter(); out.write("{\"success\":true}"); out.flush(); response.flushBuffer(); return true; } }; httpServer.addHandler(handler); service.renewNetworkCertificate("foobar"); }
From source file:KeystoreGeneratorTest.java
@Test public void test() throws Exception { File dir = null;//w w w . ja v a2 s . c om FileInputStream fis = null; try { dir = Files.createTempDir(); File keystoreFile = new File(dir, KEYSTORE_NAME); String config = GSON.toJson(ImmutableMap.builder().put("password", KEYSTORE_PASSWORD) .put("entries", ImmutableList.builder() .add(ImmutableMap.builder().put("label", "rsatest1").put("algorithm", "SHA256WithRSA") .put("keyAlgorithm", "RSA").put("rsaKeySize", "2048").build()) .add(ImmutableMap.builder().put("label", "ecdsatest1") .put("algorithm", "SHA256WithECDSA").put("keyAlgorithm", "ECDSA") .put("ecdsaNamedCurve", "secp192r1").build()) .add(ImmutableMap.builder().put("label", "ecdsatest2") .put("algorithm", "SHA256WithECDSA").put("keyAlgorithm", "ECDSA") .put("ecdsaNamedCurve", "secp256r1").build()) .build()) .build()); // generate KeyStore store = new KeystoreGenerator().generate(GSON.fromJson(config, KeystoreConfig.class)); // write to disk try (FileOutputStream out = new FileOutputStream(keystoreFile)) { store.store(out, KEYSTORE_PASSWORD.toCharArray()); } // load fis = new FileInputStream(keystoreFile); KeyStore ks = KeyStore.getInstance("PKCS12", "SunJSSE"); ks.load(fis, KEYSTORE_PASSWORD.toCharArray()); Enumeration<String> aliases = ks.aliases(); while (aliases.hasMoreElements()) { String al = aliases.nextElement(); System.out.println("Label: [" + al + "]"); X509Certificate cert = (X509Certificate) ks.getCertificate(al); System.out.println(" Algorithm: [" + cert.getSigAlgName() + "]"); PublicKey key = cert.getPublicKey(); if (key instanceof ECKey) { ECKey eckey = (ECKey) key; ECParameterSpec spec = eckey.getParams(); System.out.println(" EC spec: [" + spec + "]"); } } } finally { closeQuietly(fis); FileUtils.deleteDirectory(dir); } }
From source file:com.example.bbbbbb.http.sample.util.SecureSocketFactory.java
/** * Instantiate a new secured factory pertaining to the passed store. Be sure to initialize the * store with the password using {@link KeyStore#load(InputStream, * char[])} method./*from w w w. j a v a 2 s.c o m*/ * * @param store The key store holding the certificate details * @param alias The alias of the certificate to use */ public SecureSocketFactory(KeyStore store, String alias) throws CertificateException, NoSuchAlgorithmException, KeyManagementException, KeyStoreException, UnrecoverableKeyException { super(store); // Loading the CA certificate from store. final Certificate rootca = store.getCertificate(alias); // Turn it to X509 format. InputStream is = new ByteArrayInputStream(rootca.getEncoded()); X509Certificate x509ca = (X509Certificate) CertificateFactory.getInstance("X.509").generateCertificate(is); AsyncHttpClient.silentCloseInputStream(is); if (null == x509ca) { throw new CertificateException("Embedded SSL certificate has expired."); } // Check the CA's validity. x509ca.checkValidity(); // Accepted CA is only the one installed in the store. acceptedIssuers = new X509Certificate[] { x509ca }; sslCtx = SSLContext.getInstance("TLS"); sslCtx.init(null, new TrustManager[] { new X509TrustManager() { @Override public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException { } @Override public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException { Exception error = null; if (null == chain || 0 == chain.length) { error = new CertificateException("Certificate chain is invalid."); } else if (null == authType || 0 == authType.length()) { error = new CertificateException("Authentication type is invalid."); } else { Log.i(LOG_TAG, "Chain includes " + chain.length + " certificates."); try { for (X509Certificate cert : chain) { Log.i(LOG_TAG, "Server Certificate Details:"); Log.i(LOG_TAG, "---------------------------"); Log.i(LOG_TAG, "IssuerDN: " + cert.getIssuerDN().toString()); Log.i(LOG_TAG, "SubjectDN: " + cert.getSubjectDN().toString()); Log.i(LOG_TAG, "Serial Number: " + cert.getSerialNumber()); Log.i(LOG_TAG, "Version: " + cert.getVersion()); Log.i(LOG_TAG, "Not before: " + cert.getNotBefore().toString()); Log.i(LOG_TAG, "Not after: " + cert.getNotAfter().toString()); Log.i(LOG_TAG, "---------------------------"); // Make sure that it hasn't expired. cert.checkValidity(); // Verify the certificate's public key chain. cert.verify(rootca.getPublicKey()); } } catch (InvalidKeyException e) { error = e; } catch (NoSuchAlgorithmException e) { error = e; } catch (NoSuchProviderException e) { error = e; } catch (SignatureException e) { error = e; } } if (null != error) { Log.e(LOG_TAG, "Certificate error", error); throw new CertificateException(error); } } @Override public X509Certificate[] getAcceptedIssuers() { return acceptedIssuers; } } }, null); setHostnameVerifier(SSLSocketFactory.STRICT_HOSTNAME_VERIFIER); }
From source file:org.obm.sync.push.client.SSLContextFactoryTest.java
@Test public void testKeyStoreIsPKCS12() throws Exception { InputStream pkcs12Stream = ClassLoader.getSystemClassLoader().getResourceAsStream("pkcs_pwd_toto.p12"); char[] pkcs12Password = "toto".toCharArray(); KeyStore keyStore = SSLContextFactory.loadPKCS12KeyStore(pkcs12Stream, pkcs12Password); InputStream pkcs12InnerX509 = ClassLoader.getSystemClassLoader().getResourceAsStream("pkcs_inner_x509.crt"); Certificate pkcs12InnerCertificate = CertificateFactory.getInstance("x509") .generateCertificate(pkcs12InnerX509); assertThat(keyStore.getType()).isEqualToIgnoringCase("pkcs12"); assertThat(keyStore.getCertificate("client2")).isEqualTo(pkcs12InnerCertificate); }
From source file:org.jaggeryjs.modules.sso.common.util.SSOAgentCarbonX509Credential.java
protected void readCarbonX509Credentials(int tenantId, String tenantDomain) throws Exception { KeyStoreManager tenantKSM = KeyStoreManager.getInstance(tenantId); if (!tenantDomain.equals(MultitenantConstants.SUPER_TENANT_DOMAIN_NAME)) { // derive key store name String ksName = tenantDomain.trim().replace(".", "-"); // derive JKS name String jksName = ksName + ".jks"; KeyStore keyStore = null; try {//from w w w .j a v a2s. c o m keyStore = tenantKSM.getKeyStore(jksName); } catch (Exception e) { // getKeyStore() method throws a generic Exception handleException("Error occurred while retrieving key store of tenant " + tenantDomain, e); return; } try { entityCertificate = (X509Certificate) keyStore.getCertificate(tenantDomain); } catch (KeyStoreException e) { handleException("Error occurred while retrieving public certificate with alias " + tenantDomain + " of tenant " + tenantDomain, e); } privateKey = (PrivateKey) tenantKSM.getPrivateKey(jksName, tenantDomain); } else { try { entityCertificate = tenantKSM.getDefaultPrimaryCertificate(); } catch (Exception e) { // getDefaultPrimaryCertificate() method throws a generic Exception handleException("Error retrieving default primary certificate of " + MultitenantConstants.SUPER_TENANT_DOMAIN_NAME, e); } try { privateKey = tenantKSM.getDefaultPrivateKey(); } catch (Exception e) { //getDefaultPrivateKey() method throws a generic Exception handleException( "Error retrieving default private key of " + MultitenantConstants.SUPER_TENANT_DOMAIN_NAME, e); } } publicKey = entityCertificate.getPublicKey(); }
From source file:org.wso2.carbon.hostobjects.sso.internal.util.SSOAgentCarbonX509Credential.java
protected void readCarbonX509Credentials(int tenantId, String tenantDomain) throws SSOHostObjectException { KeyStoreManager tenantKSM = KeyStoreManager.getInstance(tenantId); if (!tenantDomain.equals(MultitenantConstants.SUPER_TENANT_DOMAIN_NAME)) { // derive key store name String ksName = tenantDomain.trim().replace(".", "-"); // derive JKS name String jksName = ksName + ".jks"; KeyStore keyStore = null; try {/*from w ww . j a va 2s. co m*/ keyStore = tenantKSM.getKeyStore(jksName); } catch (Exception e) { // getKeyStore() method throws a generic Exception handleException("Error occurred while retrieving key store of tenant " + tenantDomain, e); return; } try { entityCertificate = (X509Certificate) keyStore.getCertificate(tenantDomain); } catch (KeyStoreException e) { handleException("Error occurred while retrieving public certificate with alias " + tenantDomain + " of tenant " + tenantDomain, e); } privateKey = (PrivateKey) tenantKSM.getPrivateKey(jksName, tenantDomain); } else { try { entityCertificate = tenantKSM.getDefaultPrimaryCertificate(); } catch (Exception e) { // getDefaultPrimaryCertificate() method throws a generic Exception handleException("Error retrieving default primary certificate of " + MultitenantConstants.SUPER_TENANT_DOMAIN_NAME, e); } try { privateKey = tenantKSM.getDefaultPrivateKey(); } catch (Exception e) { //getDefaultPrivateKey() method throws a generic Exception handleException( "Error retrieving default private key of " + MultitenantConstants.SUPER_TENANT_DOMAIN_NAME, e); } } publicKey = entityCertificate.getPublicKey(); }