List of usage examples for java.security KeyStore getDefaultType
public static final String getDefaultType()
From source file:com.cloudant.client.org.lightcouch.CouchDbClientAndroid.java
private SchemeRegistry createRegistry(CouchDbProperties properties) throws NoSuchAlgorithmException, KeyManagementException, KeyStoreException, CertificateException, IOException, UnrecoverableKeyException { SchemeRegistry registry = new SchemeRegistry(); if ("https".equals(properties.getProtocol())) { KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType()); trustStore.load(null, null);/*from w ww.j a v a 2s .c om*/ SSLSocketFactory sf = new MySSLSocketFactory(trustStore); sf.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER); registry.register(new Scheme(properties.getProtocol(), sf, properties.getPort())); } else { registry.register(new Scheme(properties.getProtocol(), PlainSocketFactory.getSocketFactory(), properties.getPort())); } return registry; }
From source file:org.wso2.carbon.webapp.authenticator.framework.authenticator.JWTAuthenticator.java
@Override public AuthenticationInfo authenticate(Request request, Response response) { String requestUri = request.getRequestURI(); SignedJWT jwsObject;// w w w . java 2s . c o m String username; String tenantDomain; int tenantId; String issuer; AuthenticationInfo authenticationInfo = new AuthenticationInfo(); if (requestUri == null || "".equals(requestUri)) { authenticationInfo.setStatus(Status.CONTINUE); } if (requestUri == null) { requestUri = ""; } StringTokenizer tokenizer = new StringTokenizer(requestUri, "/"); String context = tokenizer.hasMoreTokens() ? tokenizer.nextToken() : null; if (context == null || "".equals(context)) { authenticationInfo.setStatus(Status.CONTINUE); } try { String authorizationHeader = request.getHeader(JWT_ASSERTION_HEADER); jwsObject = SignedJWT.parse(authorizationHeader); username = jwsObject.getJWTClaimsSet().getStringClaim(SIGNED_JWT_AUTH_USERNAME); tenantDomain = MultitenantUtils.getTenantDomain(username); tenantId = Integer.parseInt(jwsObject.getJWTClaimsSet().getStringClaim(SIGNED_JWT_AUTH_TENANT_ID)); issuer = jwsObject.getJWTClaimsSet().getIssuer(); } catch (ParseException e) { log.error("Error occurred while parsing JWT header.", e); authenticationInfo.setMessage("Error occurred while parsing JWT header"); return authenticationInfo; } try { PrivilegedCarbonContext.startTenantFlow(); PrivilegedCarbonContext.getThreadLocalCarbonContext().setTenantDomain(tenantDomain); PrivilegedCarbonContext.getThreadLocalCarbonContext().setTenantId(tenantId); IssuerAlias issuerAlias = new IssuerAlias(issuer, tenantDomain); PublicKey publicKey = publicKeyHolder.get(issuerAlias); if (publicKey == null) { loadTenantRegistry(tenantId); KeyStoreManager keyStoreManager = KeyStoreManager.getInstance(tenantId); if (MultitenantConstants.SUPER_TENANT_DOMAIN_NAME.equals(tenantDomain)) { String alias = properties == null ? null : properties.getProperty(issuer); if (alias != null && !alias.isEmpty()) { ServerConfiguration serverConfig = CarbonUtils.getServerConfiguration(); KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType()); String trustStorePath = serverConfig.getFirstProperty(DEFAULT_TRUST_STORE_LOCATION); String trustStorePassword = serverConfig.getFirstProperty(DEFAULT_TRUST_STORE_PASSWORD); keyStore.load(new FileInputStream(trustStorePath), trustStorePassword.toCharArray()); java.security.cert.Certificate certificate = keyStore.getCertificate(alias); publicKey = certificate == null ? null : certificate.getPublicKey(); } else { authenticationInfo.setStatus(Status.FAILURE); return authenticationInfo; } } else { String ksName = tenantDomain.trim().replace('.', '-'); String jksName = ksName + ".jks"; publicKey = keyStoreManager.getKeyStore(jksName).getCertificate(tenantDomain).getPublicKey(); } if (publicKey != null) { issuerAlias = new IssuerAlias(tenantDomain); publicKeyHolder.put(issuerAlias, publicKey); } } //Get the filesystem keystore default primary certificate JWSVerifier verifier = null; if (publicKey != null) { verifier = new RSASSAVerifier((RSAPublicKey) publicKey); } if (verifier != null && jwsObject.verify(verifier)) { username = MultitenantUtils.getTenantAwareUsername(username); UserStoreManager userStore = AuthenticatorFrameworkDataHolder.getInstance().getRealmService() .getTenantUserRealm(tenantId).getUserStoreManager(); if (userStore.isExistingUser(username)) { authenticationInfo.setTenantId(tenantId); authenticationInfo.setUsername(username); authenticationInfo.setTenantDomain(tenantDomain); authenticationInfo.setStatus(Status.CONTINUE); } else { authenticationInfo.setStatus(Status.FAILURE); } } else { authenticationInfo.setStatus(Status.FAILURE); } } catch (UserStoreException e) { log.error("Error occurred while obtaining the user.", e); authenticationInfo.setStatus(Status.FAILURE); } catch (Exception e) { log.error("Error occurred while verifying the JWT header.", e); authenticationInfo.setStatus(Status.FAILURE); } finally { PrivilegedCarbonContext.endTenantFlow(); } return authenticationInfo; }
From source file:org.zaproxy.zap.extension.dynssl.SslCertificateUtils.java
/** * @param str// w w w . j ava 2 s .c o m * @return * @throws KeyStoreException * @throws IOException * @throws CertificateException * @throws NoSuchAlgorithmException */ public static final KeyStore string2Keystore(String str) throws KeyStoreException, NoSuchAlgorithmException, CertificateException, IOException { final byte[] bytes = Base64.decodeBase64(str); final ByteArrayInputStream bais = new ByteArrayInputStream(bytes); final KeyStore ks = KeyStore.getInstance(KeyStore.getDefaultType()); ks.load(bais, SslCertificateService.PASSPHRASE); bais.close(); return ks; }
From source file:org.gw2InfoViewer.factories.HttpsConnectionFactory.java
public static HttpClient getHttpsClientWithProxy(Certificate[] sslCertificate, String proxyAddress, int proxyPort) { DefaultHttpClient httpClient;/*w w w . ja v a2s . c o m*/ HttpHost proxy; httpClient = new DefaultHttpClient(); try { TrustManagerFactory tf = TrustManagerFactory.getInstance("X509"); KeyStore ks = KeyStore.getInstance(KeyStore.getDefaultType()); ks.load(null); for (int i = 0; i < sslCertificate.length; i++) { ks.setCertificateEntry("StartCom" + i, sslCertificate[i]); } tf.init(ks); TrustManager[] tm = tf.getTrustManagers(); SSLContext sslCon = SSLContext.getInstance("SSL"); sslCon.init(null, tm, new SecureRandom()); SSLSocketFactory socketFactory = new SSLSocketFactory(ks); Scheme sch = new Scheme("https", 443, socketFactory); proxy = new HttpHost(proxyAddress, proxyPort, "https"); httpClient.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, proxy); httpClient.getConnectionManager().getSchemeRegistry().register(sch); } catch (CertificateException | NoSuchAlgorithmException | KeyStoreException | IOException | KeyManagementException | UnrecoverableKeyException ex) { Logger.getLogger(HttpsConnectionFactory.class.getName()).log(Level.SEVERE, null, ex); } return httpClient; }
From source file:com.cws.esolutions.security.dao.certmgmt.impl.CertificateManagerImpl.java
/** * @see com.cws.esolutions.security.dao.certmgmt.interfaces.ICertificateManager#createCertificateRequest(List, String, int, int) *///from w w w. j a v a 2 s . co m public synchronized File createCertificateRequest(final List<String> subjectData, final String storePassword, final int validityPeriod, final int keySize) throws CertificateManagementException { final String methodName = ICertificateManager.CNAME + "#createCertificateRequest(final List<String> subjectData, final String storePassword, final int validityPeriod, final int keySize) throws CertificateManagementException"; if (DEBUG) { DEBUGGER.debug(methodName); DEBUGGER.debug("Value: {}", subjectData); DEBUGGER.debug("Value: {}", validityPeriod); DEBUGGER.debug("Value: {}", keySize); } final File rootDirectory = certConfig.getRootDirectory(); final String signatureAlgorithm = certConfig.getSignatureAlgorithm(); final String certificateAlgorithm = certConfig.getCertificateAlgorithm(); final File privateKeyDirectory = FileUtils .getFile(certConfig.getPrivateKeyDirectory() + "/" + subjectData.get(0)); final File publicKeyDirectory = FileUtils .getFile(certConfig.getPublicKeyDirectory() + "/" + subjectData.get(0)); final File csrDirectory = FileUtils.getFile(certConfig.getCsrDirectory() + "/" + subjectData.get(0)); final File storeDirectory = FileUtils.getFile(certConfig.getStoreDirectory() + "/" + subjectData.get(0)); final X500Name x500Name = new X500Name("CN=" + subjectData.get(0) + ",OU=" + subjectData.get(1) + ",O=" + subjectData.get(2) + ",L=" + subjectData.get(3) + ",ST=" + subjectData.get(4) + ",C=" + subjectData.get(5) + ",E=" + subjectData.get(6)); if (DEBUG) { DEBUGGER.debug("rootDirectory: {}", rootDirectory); DEBUGGER.debug("signatureAlgorithm: {}", signatureAlgorithm); DEBUGGER.debug("certificateAlgorithm: {}", certificateAlgorithm); DEBUGGER.debug("privateKeyDirectory: {}", privateKeyDirectory); DEBUGGER.debug("publicKeyDirectory: {}", publicKeyDirectory); DEBUGGER.debug("csrDirectory: {}", csrDirectory); DEBUGGER.debug("storeDirectory: {}", storeDirectory); DEBUGGER.debug("x500Name: {}", x500Name); } File csrFile = null; JcaPEMWriter csrPemWriter = null; JcaPEMWriter publicKeyWriter = null; JcaPEMWriter privateKeyWriter = null; FileOutputStream csrFileStream = null; FileOutputStream keyStoreStream = null; FileOutputStream publicKeyFileStream = null; FileOutputStream privateKeyFileStream = null; OutputStreamWriter csrFileStreamWriter = null; OutputStreamWriter privateKeyStreamWriter = null; OutputStreamWriter publicKeyStreamWriter = null; try { KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType()); keyStore.load(null, storePassword.toCharArray()); if (DEBUG) { DEBUGGER.debug("KeyStore: {}", keyStore); } SecureRandom random = new SecureRandom(); KeyPairGenerator keyGenerator = KeyPairGenerator.getInstance(certificateAlgorithm); keyGenerator.initialize(keySize, random); if (DEBUG) { DEBUGGER.debug("KeyGenerator: {}", keyGenerator); } KeyPair keyPair = keyGenerator.generateKeyPair(); if (DEBUG) { DEBUGGER.debug("KeyPair: {}", keyPair); } if (keyPair != null) { final Signature sig = Signature.getInstance(signatureAlgorithm); final PrivateKey privateKey = keyPair.getPrivate(); final PublicKey publicKey = keyPair.getPublic(); if (DEBUG) { DEBUGGER.debug("Signature: {}", sig); DEBUGGER.debug("PrivateKey: {}", privateKey); DEBUGGER.debug("PublicKey: {}", publicKey); } sig.initSign(privateKey, random); ContentSigner signGen = new JcaContentSignerBuilder(signatureAlgorithm).build(privateKey); if (DEBUG) { DEBUGGER.debug("ContentSigner: {}", signGen); } Calendar expiry = Calendar.getInstance(); expiry.add(Calendar.DAY_OF_YEAR, validityPeriod); if (DEBUG) { DEBUGGER.debug("Calendar: {}", expiry); } CertificateFactory certFactory = CertificateFactory.getInstance(certConfig.getCertificateType()); if (DEBUG) { DEBUGGER.debug("CertificateFactory: {}", certFactory); } X509Certificate[] issuerCert = new X509Certificate[] { (X509Certificate) certFactory .generateCertificate(new FileInputStream(certConfig.getIntermediateCertificateFile())) }; if (DEBUG) { DEBUGGER.debug("X509Certificate[]: {}", (Object) issuerCert); } keyStore.setCertificateEntry(certConfig.getRootCertificateName(), certFactory.generateCertificate( new FileInputStream(FileUtils.getFile(certConfig.getRootCertificateFile())))); keyStore.setCertificateEntry(certConfig.getIntermediateCertificateName(), certFactory.generateCertificate(new FileInputStream( FileUtils.getFile(certConfig.getIntermediateCertificateFile())))); PKCS10CertificationRequestBuilder builder = new JcaPKCS10CertificationRequestBuilder(x500Name, publicKey); if (DEBUG) { DEBUGGER.debug("PKCS10CertificationRequestBuilder: {}", builder); } PKCS10CertificationRequest csr = builder.build(signGen); if (DEBUG) { DEBUGGER.debug("PKCS10CertificationRequest: {}", csr); } // write private key File privateKeyFile = FileUtils.getFile(privateKeyDirectory + "/" + subjectData.get(0) + SecurityServiceConstants.PRIVATEKEY_FILE_EXT); if (DEBUG) { DEBUGGER.debug("privateKeyFile: {}", privateKeyFile); } if (!(privateKeyFile.createNewFile())) { throw new IOException("Failed to store private file"); } privateKeyFileStream = new FileOutputStream(privateKeyFile); privateKeyStreamWriter = new OutputStreamWriter(privateKeyFileStream); if (DEBUG) { DEBUGGER.debug("privateKeyFileStream: {}", privateKeyFileStream); DEBUGGER.debug("privateKeyStreamWriter: {}", privateKeyStreamWriter); } privateKeyWriter = new JcaPEMWriter(privateKeyStreamWriter); privateKeyWriter.writeObject(privateKey); privateKeyWriter.flush(); privateKeyStreamWriter.flush(); privateKeyFileStream.flush(); // write public key File publicKeyFile = FileUtils.getFile(publicKeyDirectory + "/" + subjectData.get(0) + SecurityServiceConstants.PUBLICKEY_FILE_EXT); if (DEBUG) { DEBUGGER.debug("publicKeyFile: {}", publicKeyFile); } if (!(publicKeyFile.createNewFile())) { throw new IOException("Failed to store public key file"); } publicKeyFileStream = new FileOutputStream(publicKeyFile); publicKeyStreamWriter = new OutputStreamWriter(publicKeyFileStream); if (DEBUG) { DEBUGGER.debug("publicKeyFileStream: {}", publicKeyFileStream); DEBUGGER.debug("publicKeyStreamWriter: {}", publicKeyStreamWriter); } publicKeyWriter = new JcaPEMWriter(publicKeyStreamWriter); publicKeyWriter.writeObject(publicKey); publicKeyWriter.flush(); publicKeyStreamWriter.flush(); publicKeyFileStream.flush(); // write csr csrFile = FileUtils .getFile(csrDirectory + "/" + subjectData.get(0) + SecurityServiceConstants.CSR_FILE_EXT); if (DEBUG) { DEBUGGER.debug("csrFile: {}", csrFile); } if (!(csrFile.createNewFile())) { throw new IOException("Failed to store CSR file"); } csrFileStream = new FileOutputStream(csrFile); csrFileStreamWriter = new OutputStreamWriter(csrFileStream); if (DEBUG) { DEBUGGER.debug("publicKeyFileStream: {}", publicKeyFileStream); DEBUGGER.debug("publicKeyStreamWriter: {}", publicKeyStreamWriter); } csrPemWriter = new JcaPEMWriter(csrFileStreamWriter); csrPemWriter.writeObject(csr); csrPemWriter.flush(); csrFileStreamWriter.flush(); csrFileStream.flush(); File keyStoreFile = FileUtils .getFile(storeDirectory + "/" + subjectData.get(0) + "." + KeyStore.getDefaultType()); if (DEBUG) { DEBUGGER.debug("keyStoreFile: {}", keyStoreFile); } keyStoreStream = FileUtils.openOutputStream(keyStoreFile); if (DEBUG) { DEBUGGER.debug("keyStoreStream: {}", keyStoreStream); } keyStore.setKeyEntry(subjectData.get(0), (Key) keyPair.getPrivate(), storePassword.toCharArray(), issuerCert); keyStore.store(keyStoreStream, storePassword.toCharArray()); keyStoreStream.flush(); if (DEBUG) { DEBUGGER.debug("KeyStore: {}", keyStore); } } else { throw new CertificateManagementException("Failed to generate keypair. Cannot continue."); } } catch (FileNotFoundException fnfx) { throw new CertificateManagementException(fnfx.getMessage(), fnfx); } catch (IOException iox) { throw new CertificateManagementException(iox.getMessage(), iox); } catch (NoSuchAlgorithmException nsax) { throw new CertificateManagementException(nsax.getMessage(), nsax); } catch (IllegalStateException isx) { throw new CertificateManagementException(isx.getMessage(), isx); } catch (InvalidKeyException ikx) { throw new CertificateManagementException(ikx.getMessage(), ikx); } catch (OperatorCreationException ocx) { throw new CertificateManagementException(ocx.getMessage(), ocx); } catch (KeyStoreException ksx) { throw new CertificateManagementException(ksx.getMessage(), ksx); } catch (CertificateException cx) { throw new CertificateManagementException(cx.getMessage(), cx); } finally { if (csrFileStreamWriter != null) { IOUtils.closeQuietly(csrFileStreamWriter); } if (csrFileStream != null) { IOUtils.closeQuietly(csrFileStream); } if (csrPemWriter != null) { IOUtils.closeQuietly(csrPemWriter); } if (publicKeyFileStream != null) { IOUtils.closeQuietly(publicKeyFileStream); } if (publicKeyStreamWriter != null) { IOUtils.closeQuietly(publicKeyStreamWriter); } if (publicKeyWriter != null) { IOUtils.closeQuietly(publicKeyWriter); } if (privateKeyFileStream != null) { IOUtils.closeQuietly(privateKeyFileStream); } if (privateKeyStreamWriter != null) { IOUtils.closeQuietly(privateKeyStreamWriter); } if (privateKeyWriter != null) { IOUtils.closeQuietly(privateKeyWriter); } if (keyStoreStream != null) { IOUtils.closeQuietly(keyStoreStream); } } return csrFile; }
From source file:nz.net.catalyst.MaharaDroid.upload.http.RestClient.java
private static SSLSocketFactory getSocketFactory(Boolean d) { // Enable debug mode to ignore all certificates if (DEBUG) {/*w w w.j av a 2 s .c o m*/ KeyStore trustStore; try { trustStore = KeyStore.getInstance(KeyStore.getDefaultType()); trustStore.load(null, null); SSLSocketFactory sf = new DebugSSLSocketFactory(trustStore); sf.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER); return sf; } catch (KeyStoreException e2) { // TODO Auto-generated catch block e2.printStackTrace(); } catch (NoSuchAlgorithmException e3) { // TODO Auto-generated catch block e3.printStackTrace(); } catch (CertificateException e3) { // TODO Auto-generated catch block e3.printStackTrace(); } catch (IOException e3) { // TODO Auto-generated catch block e3.printStackTrace(); } catch (KeyManagementException e2) { // TODO Auto-generated catch block e2.printStackTrace(); } catch (UnrecoverableKeyException e2) { // TODO Auto-generated catch block e2.printStackTrace(); } } return SSLSocketFactory.getSocketFactory(); }
From source file:org.gridgain.grid.tools.license.GridLicenseGeneratorV1.java
/** * Load private key from key store.//from w ww. j a v a2s.c o m * * @return Private key. * @throws GridException If key loading failed. */ private static PrivateKey getKey() throws GridException { KeyStore ks; try { ks = KeyStore.getInstance(KeyStore.getDefaultType()); } catch (Exception e) { throw new GridException("Failed to get key store instance.", e); } File ksFile = new File(U.getGridGainHome() + FS + "keystore", KEY_STORE); if (!ksFile.exists() || !ksFile.canRead()) throw new GridException("Key store file doesn't exist or is not readable: " + ksFile.getAbsolutePath()); InputStream in; try { in = new FileInputStream(ksFile); } catch (IOException e) { throw new GridException("Failed to open key store file: " + ksFile.getAbsolutePath(), e); } try { ks.load(in, KEY_STORE_PWD.toCharArray()); return (PrivateKey) ks.getKey(KEY_ALIAS, KEY_STORE_PWD.toCharArray()); } catch (Exception e) { throw new GridException("Failed to get private key from key store [keystore=" + KEY_STORE + ", alias=" + KEY_ALIAS + ']', e); } finally { U.close(in, null); } }
From source file:com.microsoft.exchange.impl.ExchangeWebServicesClient.java
/** * /* w ww . j a va 2s . c o m*/ * @param resource * @param password * @return */ protected static KeyStore getKeystoreFromResource(Resource resource, char[] password) { try { KeyStore k = KeyStore.getInstance(KeyStore.getDefaultType()); k.load(resource.getInputStream(), password); return k; } catch (KeyStoreException e) { throw new IllegalArgumentException("failed to load keystore from " + resource.getDescription(), e); } catch (CertificateException e) { throw new IllegalArgumentException("failed to load keystore from " + resource.getDescription(), e); } catch (IOException e) { throw new IllegalArgumentException("failed to load keystore from " + resource.getDescription(), e); } catch (NoSuchAlgorithmException e) { throw new IllegalArgumentException("failed to load keystore from " + resource.getDescription(), e); } }
From source file:io.hops.hopsworks.api.util.CustomSSLProtocolSocketFactory.java
private KeyStore createKeystore(final File keyStoreLocation, final String password) throws KeyStoreException, FileNotFoundException, IOException, NoSuchAlgorithmException, CertificateException { KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType()); try (FileInputStream fis = new FileInputStream(keyStoreLocation)) { keyStore.load(fis, password != null ? password.toCharArray() : null); }//from ww w . j a v a 2 s .com return keyStore; }
From source file:at.univie.sensorium.extinterfaces.HTTPSUploader.java
public HttpClient getNewHttpClient() { try {//from www. j a va2 s.c om KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType()); trustStore.load(null, null); SSLSocketFactory sf = new MySSLSocketFactory(trustStore); sf.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER); HttpParams params = new BasicHttpParams(); int timeout = 10 * 1000; HttpConnectionParams.setConnectionTimeout(params, timeout); HttpConnectionParams.setSoTimeout(params, timeout); HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1); HttpProtocolParams.setContentCharset(params, HTTP.UTF_8); SchemeRegistry registry = new SchemeRegistry(); registry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80)); registry.register(new Scheme("https", sf, 443)); ClientConnectionManager ccm = new ThreadSafeClientConnManager(params, registry); return new DefaultHttpClient(ccm, params); } catch (Exception e) { return new DefaultHttpClient(); } }