Java Code Examples for java.security.KeyStore.getDefaultType()

The following are Jave code examples for showing how to use getDefaultType() of the java.security.KeyStore class. You can vote up the examples you like. Your votes will be used in our system to get more good examples.
+ Save this method
Example 1
Project: azeroth   File: RSA.java   View Source Code Vote up 6 votes
/**
 * 从KeyStore获取公钥
 * @param location
 * @param alias
 * @param storeType
 * @param storePass
 * @param keyPass
 * @return
 */
public static PublicKey loadPublicKeyFromKeyStore(String location, String alias, String storeType, String storePass, String keyPass) {
    try {
        storeType = null == storeType ? KeyStore.getDefaultType() : storeType;
        keyPass = keyPass == null ? storePass : keyPass;
        KeyStore keyStore = KeyStore.getInstance(storeType);
        InputStream is = new FileInputStream(location);
        keyStore.load(is, storePass.toCharArray());

        RSAPrivateCrtKey key = (RSAPrivateCrtKey) keyStore.getKey(alias, keyPass.toCharArray());
        RSAPublicKeySpec spec = new RSAPublicKeySpec(key.getModulus(),
                key.getPublicExponent());
        PublicKey publicKey = KeyFactory.getInstance(KEY_ALGORITHM).generatePublic(spec);
        return publicKey;
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}
 
Example 2
Project: BlogBookApp   File: MyWebService.java   View Source Code Vote up 6 votes
private SSLSocketFactory addCertificate(InputStream inputStream) throws CertificateException, NoSuchAlgorithmException, IOException, KeyStoreException, KeyManagementException {
    // loading CAs from an InputStream
    CertificateFactory cf = CertificateFactory.getInstance("X.509");
    Certificate ca;
    try {
        ca = cf.generateCertificate(inputStream);
    } finally {
        inputStream.close();
    }

    // creating a KeyStore containing our trusted CAs
    String keyStoreType = KeyStore.getDefaultType();
    KeyStore keyStore = KeyStore.getInstance(keyStoreType);
    keyStore.load(null, null);
    keyStore.setCertificateEntry("ca", ca);

    // creating a TrustManager that trusts the CAs in our KeyStore
    String tmfAlgorithm = TrustManagerFactory.getDefaultAlgorithm();
    TrustManagerFactory tmf = TrustManagerFactory.getInstance(tmfAlgorithm);
    tmf.init(keyStore);

    // creating an SSLSocketFactory that uses our TrustManager
    SSLContext sslContext = SSLContext.getInstance("TLS");
    sslContext.init(null, tmf.getTrustManagers(), null);

    return sslContext.getSocketFactory();
}
 
Example 3
Project: springboot-shiro-cas-mybatis   File: FileTrustStoreSslSocketFactory.java   View Source Code Vote up 5 votes
/**
 * Instantiates a new trusted proxy authentication trust store ssl socket factory.
 * Defaults to {@code TLSv1} and {@link SSLConnectionSocketFactory#BROWSER_COMPATIBLE_HOSTNAME_VERIFIER}
 * for the supported protocols and hostname verification.
 * @param trustStoreFile the trust store file
 * @param trustStorePassword the trust store password
 */
@Autowired
public FileTrustStoreSslSocketFactory(
        @Value("${http.client.truststore.file:classpath:truststore.jks}")
        final File trustStoreFile,
        @Value("${http.client.truststore.psw:changeit}")
        final String trustStorePassword) {
    this(trustStoreFile, trustStorePassword, KeyStore.getDefaultType());
}
 
Example 4
Project: nc-android-webrtcpeer   File: DefaultSocketService.java   View Source Code Vote up 5 votes
public void setTrustedCertificate(InputStream inputFile) {
    try {
        CertificateFactory cf = CertificateFactory.getInstance("X.509");
        InputStream caInput = new BufferedInputStream(inputFile);
        Certificate ca = cf.generateCertificate(caInput);

        // Create a KeyStore containing our trusted CAs
        String keyStoreType = KeyStore.getDefaultType();
        keyStore = KeyStore.getInstance(keyStoreType);
        keyStore.load(null, null);
        keyStore.setCertificateEntry("ca", ca);
    } catch (Exception e) {
        e.printStackTrace();
    }
}
 
Example 5
Project: LightSIP   File: DefaultSecurityManagerProvider.java   View Source Code Vote up 5 votes
public void init(Properties properties)
        throws GeneralSecurityException, IOException {
    // required, could use default keyStore, but it is better practice to explicitly specify
    final String keyStoreFilename = properties.getProperty("javax.net.ssl.keyStore");
    // required
    final String keyStorePassword = properties.getProperty("javax.net.ssl.keyStorePassword");
    // optional, uses default if not specified 
    String keyStoreType = properties.getProperty("javax.net.ssl.keyStoreType");
    if (keyStoreType == null) {
        keyStoreType = KeyStore.getDefaultType();
        logger.logWarning("Using default keystore type " + keyStoreType);
    }
    if (keyStoreFilename == null || keyStorePassword == null) {
        logger.logWarning("TLS server settings will be inactive - TLS key store will use JVM defaults"
                + " keyStoreType=" +  keyStoreType
                + " javax.net.ssl.keyStore=" + keyStoreFilename
                + " javax.net.ssl.keyStorePassword=" + (keyStorePassword == null? null: "***"));
    }

    // required, could use default trustStore, but it is better practice to explicitly specify
    final String trustStoreFilename = properties.getProperty("javax.net.ssl.trustStore");
    // optional, if not specified using keyStorePassword
    String trustStorePassword = properties.getProperty("javax.net.ssl.trustStorePassword");
    if(trustStorePassword == null) {
    	logger.logInfo("javax.net.ssl.trustStorePassword is null, using the password passed through javax.net.ssl.keyStorePassword");
    	trustStorePassword = keyStorePassword;
    }
    // optional, uses default if not specified 
    String trustStoreType = properties.getProperty("javax.net.ssl.trustStoreType");
    if (trustStoreType == null) {
        trustStoreType = KeyStore.getDefaultType();
        logger.logWarning("Using default truststore type " + trustStoreType);
    }
    if (trustStoreFilename == null || trustStorePassword == null) {
        logger.logWarning("TLS trust settings will be inactive - TLS trust store will use JVM defaults."
                + " trustStoreType=" +  trustStoreType
                + " javax.net.ssl.trustStore=" +  trustStoreFilename
                + " javax.net.ssl.trustStorePassword=" + (trustStorePassword == null? null: "***"));
    }

    String algorithm = Security.getProperty("ssl.KeyManagerFactory.algorithm");
    if (algorithm == null) {
        algorithm = "SunX509";
    }
    if (logger.isLoggingEnabled(LogWriter.TRACE_DEBUG)) {
        logger.logDebug("SecurityManagerProvider " + this.getClass().getCanonicalName() + " will use algorithm " + algorithm);
    }
    
    keyManagerFactory = KeyManagerFactory.getInstance(algorithm);
    if(keyStoreFilename != null) {
    	final KeyStore ks = KeyStore.getInstance(keyStoreType);
    	ks.load(new FileInputStream(new File(keyStoreFilename)), keyStorePassword.toCharArray());
    	
    	keyManagerFactory.init(ks, keyStorePassword.toCharArray());
    } else {
    	keyManagerFactory.init(null, null);
    }

    trustManagerFactory = TrustManagerFactory.getInstance(algorithm);
    if(trustStoreFilename != null) {
    	final KeyStore ts = KeyStore.getInstance(trustStoreType);
    	ts.load(new FileInputStream(new File(trustStoreFilename)), trustStorePassword.toCharArray());
    	
    	trustManagerFactory.init((KeyStore) ts);
    } else {
    	trustManagerFactory.init((KeyStore)null);
    }
    if (logger.isLoggingEnabled(LogWriter.TRACE_DEBUG)) {
    	logger.logDebug("TLS settings OK. SecurityManagerProvider " + this.getClass().getCanonicalName() + " initialized.");
    }
}
 
Example 6
Project: okhttpNDS   File: HttpsHelper.java   View Source Code Vote up 5 votes
public static SSLSocketFactory getDefaultSocketFactory(InputStream inputStream) {
    try {
        CertificateFactory cf = CertificateFactory.getInstance("X.509");
        Certificate ca;
        try {
            ca = cf.generateCertificate(inputStream);
        } finally {
            inputStream.close();
        }

        String keyStoreType = KeyStore.getDefaultType();
        KeyStore keyStore = KeyStore.getInstance(keyStoreType);
        keyStore.load(null);
        keyStore.setCertificateEntry("ca", ca);

        String tmfAlgorithm = TrustManagerFactory.getDefaultAlgorithm();
        TrustManagerFactory tmf = TrustManagerFactory.getInstance(tmfAlgorithm);
        tmf.init(keyStore);

        // Install the all-trusting trust manager
        final SSLContext sslContext = SSLContext.getInstance("TLS");
        sslContext.init(null, tmf.getTrustManagers(), new java.security.SecureRandom());
        // Create an ssl socket factory with our all-trusting manager
        return sslContext.getSocketFactory();
    } catch (Exception e) {
        Log.e(TAG, Log.getStackTraceString(e));
    }

    return null;
}
 
Example 7
Project: karate   File: JerseyHttpClient.java   View Source Code Vote up 5 votes
@Override
public void configure(HttpConfig config, ScriptContext context) {
    ClientConfig cc = new ClientConfig();
    // support request body for DELETE (non-standard)
    cc.property(ClientProperties.SUPPRESS_HTTP_COMPLIANCE_VALIDATION, true);
    if (!config.isFollowRedirects()) {
        cc.property(ClientProperties.FOLLOW_REDIRECTS, false);
    }
    ClientBuilder clientBuilder = ClientBuilder.newBuilder()
            .withConfig(cc)
            .register(new LoggingInterceptor(context)) // must be first
            .register(MultiPartFeature.class);
    if (config.isSslEnabled()) {
        SSLContext sslContext;
        if (config.getSslTrustStore() != null) {
            String trustStoreFile = config.getSslTrustStore();                
            String password = config.getSslTrustStorePassword();
            char[] passwordChars = password == null ? null : password.toCharArray();
            String algorithm = config.getSslAlgorithm();
            String type = config.getSslTrustStoreType();
            if (type == null) {
                type = KeyStore.getDefaultType();
            }
            try {
                KeyStore trustStore = KeyStore.getInstance(type);
                InputStream is = FileUtils.getFileStream(trustStoreFile, context);
                trustStore.load(is, passwordChars);
                context.logger.debug("trust store key count: {}", trustStore.size());
                sslContext = SslConfigurator.newInstance()
                        .securityProtocol(algorithm) // will default to TLS if null
                        .trustStore(trustStore)
                        // .keyStore(trustStore)
                        .createSSLContext();
            } catch (Exception e) {
                context.logger.error("ssl config failed: {}", e.getMessage());
                throw new RuntimeException(e);
            }                
        } else {
            sslContext = HttpUtils.getSslContext(config.getSslAlgorithm());
        }
        HttpsURLConnection.setDefaultSSLSocketFactory(sslContext.getSocketFactory());
        clientBuilder.sslContext(sslContext);
        clientBuilder.hostnameVerifier((host, session) -> true);
    }
    client = clientBuilder.build();
    client.property(ClientProperties.CONNECT_TIMEOUT, config.getConnectTimeout());
    client.property(ClientProperties.READ_TIMEOUT, config.getReadTimeout());
    if (config.getProxyUri() != null) {
        client.property(ClientProperties.PROXY_URI, config.getProxyUri());
        if (config.getProxyUsername() != null && config.getProxyPassword() != null) {
            client.property(ClientProperties.PROXY_USERNAME, config.getProxyUsername());
            client.property(ClientProperties.PROXY_PASSWORD, config.getProxyPassword());
        }
    }
}
 
Example 8
Project: cas-server-4.2.1   File: FileTrustStoreSslSocketFactory.java   View Source Code Vote up 5 votes
/**
 * Instantiates a new trusted proxy authentication trust store ssl socket factory.
 * Defaults to {@code TLSv1} and {@link SSLConnectionSocketFactory#BROWSER_COMPATIBLE_HOSTNAME_VERIFIER}
 * for the supported protocols and hostname verification.
 * @param trustStoreFile the trust store file
 * @param trustStorePassword the trust store password
 */
@Autowired
public FileTrustStoreSslSocketFactory(
        @Value("${http.client.truststore.file:classpath:truststore.jks}")
        final File trustStoreFile,
        @Value("${http.client.truststore.psw:changeit}")
        final String trustStorePassword) {
    this(trustStoreFile, trustStorePassword, KeyStore.getDefaultType());
}
 
Example 9
Project: cyberduck   File: CertificateStoreX509KeyManager.java   View Source Code Vote up 5 votes
private synchronized KeyStore getKeystore() throws IOException {
    String type = null;
    try {
        if(null == _keystore) {
            // Get the key manager factory for the default algorithm.
            final Preferences preferences = PreferencesFactory.get();
            type = preferences.getProperty("connection.ssl.keystore.type");
            if(log.isInfoEnabled()) {
                log.info(String.format("Load default store of type %s", type));
            }
            if(null == type) {
                type = KeyStore.getDefaultType();
            }
            final String provider = preferences.getProperty("connection.ssl.keystore.provider");
            if(StringUtils.isBlank(provider)) {
                _keystore = KeyStore.getInstance(type);
            }
            else {
                _keystore = KeyStore.getInstance(type, provider);
            }
            // Load default key store
            _keystore.load(null, null);
        }
    }
    catch(Exception e) {
        try {
            log.error(String.format("Could not load default store of type %s", type), e);
            if(log.isInfoEnabled()) {
                log.info("Load default store of default type");
            }
            _keystore = KeyStore.getInstance(KeyStore.getDefaultType());
            _keystore.load(null, null);
        }
        catch(NoSuchAlgorithmException | KeyStoreException | CertificateException ex) {
            log.error(String.format("Initialization of key store failed. %s", e.getMessage()));
            throw new IOException(e);
        }
    }
    return _keystore;
}
 
Example 10
Project: javaide   File: ZipSigner.java   View Source Code Vote up 5 votes
public void signZip(URL keystoreURL,
                    String keystoreType,
                    char[] keystorePw,
                    String certAlias,
                    char[] certPw,
                    String signatureAlgorithm,
                    String inputZipFilename,
                    String outputZipFilename)
        throws ClassNotFoundException, IllegalAccessException, InstantiationException,
        IOException, GeneralSecurityException {
    InputStream keystoreStream = null;


    try {
        KeyStore keystore = null;
        if (keystoreType == null) keystoreType = KeyStore.getDefaultType();
        keystore = KeyStore.getInstance(keystoreType);

        keystoreStream = keystoreURL.openStream();
        keystore.load(keystoreStream, keystorePw);
        Certificate cert = keystore.getCertificate(certAlias);
        X509Certificate publicKey = (X509Certificate) cert;
        Key key = keystore.getKey(certAlias, certPw);
        PrivateKey privateKey = (PrivateKey) key;

        setKeys("custom", publicKey, privateKey, signatureAlgorithm, null);

        signZip(inputZipFilename, outputZipFilename);
    } finally {
        if (keystoreStream != null) keystoreStream.close();
    }
}
 
Example 11
Project: azeroth   File: RSA.java   View Source Code Vote up 5 votes
/**
 * 从KeyStore获取私钥
 * @param location
 * @param alias
 * @param storeType
 * @param storePass
 * @param keyPass
 * @return
 */
public static PrivateKey loadPrivateKeyFromKeyStore(String location, String alias, String storeType, String storePass, String keyPass) {
    try {
        storeType = null == storeType ? KeyStore.getDefaultType() : storeType;
        keyPass = keyPass == null ? storePass : keyPass;
        KeyStore keyStore = KeyStore.getInstance(storeType);
        InputStream is = new FileInputStream(location);
        keyStore.load(is, storePass.toCharArray());
        // 由密钥库获取密钥的两种方式
        return (PrivateKey) keyStore.getKey(alias, keyPass.toCharArray());
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}
 
Example 12
Project: in-store-api-java-sdk   File: NetworkUtilities.java   View Source Code Vote up 5 votes
public static OkHttpClient.Builder getClient(SatispayContext satispayContext) {
    OkHttpClient.Builder okHttpClientBuilder;
    okHttpClientBuilder = new OkHttpClient.Builder();

    // ==> the SSL context is build only in environments different from PROD / STAGING, where the server cert is self signed
    String serverCert = satispayContext.getServerCert();
    if (serverCert != null) {
        try {
            String keyStoreType = KeyStore.getDefaultType();
            KeyStore keyStore;
            keyStore = KeyStore.getInstance(keyStoreType);
            keyStore.load(null, null);
            keyStore.setCertificateEntry("ca", CryptoUtils.certificateX509(serverCert));

            String trustManagerDefaultAlgorithm = TrustManagerFactory.getDefaultAlgorithm();
            TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance(trustManagerDefaultAlgorithm);
            trustManagerFactory.init(keyStore);

            SSLContext sslContext = SSLContext.getInstance("SSL");
            sslContext.init(null, trustManagerFactory.getTrustManagers(), null);
            SSLSocketFactory sslSocketFactory = sslContext.getSocketFactory();
            okHttpClientBuilder.sslSocketFactory(sslSocketFactory);
        } catch (Exception e) {
            ProtoLogger.error("!!! Error generating TLS context !!!");
        }
    }
    okHttpClientBuilder.connectTimeout(10, TimeUnit.SECONDS);
    okHttpClientBuilder.writeTimeout(10, TimeUnit.SECONDS);
    okHttpClientBuilder.readTimeout(30, TimeUnit.SECONDS);
    return okHttpClientBuilder;
}
 
Example 13
Project: react-native-android-library-humaniq-api   File: SelfSigningClientBuilder.java   View Source Code Vote up 5 votes
public static OkHttpClient createClient(Context context) {

        OkHttpClient client = null;

        CertificateFactory cf = null;
        InputStream cert = null;
        Certificate ca = null;
        SSLContext sslContext = null;
        try {
            cf = CertificateFactory.getInstance("X.509");
            cert = context.getResources().openRawResource(R.raw.public_key); // Place your 'my_cert.crt' file in `res/raw`

            ca = cf.generateCertificate(cert);
            cert.close();
            
            String keyStoreType = KeyStore.getDefaultType();
            KeyStore keyStore = KeyStore.getInstance(keyStoreType);
            keyStore.load(null, null);
            keyStore.setCertificateEntry("ca", ca);

            String tmfAlgorithm = TrustManagerFactory.getDefaultAlgorithm();
            TrustManagerFactory tmf = TrustManagerFactory.getInstance(tmfAlgorithm);
            tmf.init(keyStore);

            sslContext = SSLContext.getInstance("TLS");
            sslContext.init(null, tmf.getTrustManagers(), null);

            client = new OkHttpClient.Builder()
                    .sslSocketFactory(sslContext.getSocketFactory())
                .addInterceptor(new JwtTokenInterceptor())
                    .build();

        } catch (KeyStoreException | CertificateException | NoSuchAlgorithmException | IOException | KeyManagementException e) {
            e.printStackTrace();
        }


        return client;
    }
 
Example 14
Project: android-util2   File: HttpsHelper.java   View Source Code Vote up 5 votes
/**
     * create ssl socket factory. by target crt file.
     * @param context the context.
     * @param assetsFilePath the crt file path in assets.
     * @return an instance of SSLSocketFactory.
     */
    public static SSLSocketFactory createSSLSocketFactory(Context context, String assetsFilePath) {
        SSLContext sslContext = null;
        try {
            CertificateFactory certificateFactory = CertificateFactory.getInstance("X.509");
            InputStream certificates = new BufferedInputStream(context.getAssets().open(assetsFilePath));
            Certificate ca;
            try {
                ca = certificateFactory.generateCertificate(certificates);
                System.out.println("ca=" + ((X509Certificate) ca).getSubjectDN());
            } finally {
                certificates.close();
            }

            // Create a KeyStore containing our trusted CAs
            String keyStoreType = KeyStore.getDefaultType();
            KeyStore keyStore = KeyStore.getInstance(keyStoreType);
            keyStore.load(null, null);
            keyStore.setCertificateEntry("ca", ca);

            // Create a TrustManager that trusts the CAs in our KeyStore
            String tmfAlgorithm = TrustManagerFactory.getDefaultAlgorithm();
            TrustManagerFactory tmf = TrustManagerFactory.getInstance(tmfAlgorithm);
            tmf.init(keyStore);

            // Create an SSLContext that uses our TrustManager
            sslContext = SSLContext.getInstance("TLSv1", "AndroidOpenSSL");
//            sslContext = SSLContext.getInstance("TLS");
            sslContext.init(null, tmf.getTrustManagers(), null);

        } catch (Exception e) {
            e.printStackTrace();
        }

        return sslContext != null ? sslContext.getSocketFactory() : null;
    }
 
Example 15
Project: monarch   File: SocketCreator.java   View Source Code Vote up 4 votes
private TrustManager[] getTrustManagers()
    throws KeyStoreException, NoSuchAlgorithmException, CertificateException, IOException {
  TrustManager[] trustManagers = null;
  GfeConsoleReader consoleReader = GfeConsoleReaderFactory.getDefaultConsoleReader();

  String trustStoreType = sslConfig.getTruststoreType();
  if (StringUtils.isEmpty(trustStoreType)) {
    // read from console, default on empty
    if (consoleReader.isSupported()) {
      trustStoreType = consoleReader
          .readLine("Please enter the trustStoreType (javax.net.ssl.trustStoreType) : ");
    } else {
      trustStoreType = KeyStore.getDefaultType();
    }
  }

  KeyStore ts = KeyStore.getInstance(trustStoreType);
  String trustStorePath = sslConfig.getTruststore();
  if (StringUtils.isEmpty(trustStorePath)) {
    if (consoleReader.isSupported()) {
      trustStorePath = consoleReader
          .readLine("Please enter the trustStore location (javax.net.ssl.trustStore) : ");
    }
  }
  FileInputStream fis = new FileInputStream(trustStorePath);
  String passwordString = sslConfig.getTruststorePassword();
  char[] password = null;
  if (passwordString != null) {
    if (passwordString.trim().equals("")) {
      if (!StringUtils.isEmpty(passwordString)) {
        String toDecrypt = "encrypted(" + passwordString + ")";
        passwordString = PasswordUtil.decrypt(toDecrypt);
        password = passwordString.toCharArray();
      }
      // read from the console
      if (StringUtils.isEmpty(passwordString) && consoleReader.isSupported()) {
        password = consoleReader.readPassword(
            "Please enter password for trustStore (javax.net.ssl.trustStorePassword) : ");
      }
    } else {
      password = passwordString.toCharArray();
    }
  }
  ts.load(fis, password);

  // default algorithm can be changed by setting property "ssl.TrustManagerFactory.algorithm" in
  // security properties
  TrustManagerFactory tmf =
      TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
  tmf.init(ts);
  trustManagers = tmf.getTrustManagers();
  // follow the security tip in java doc
  if (password != null) {
    java.util.Arrays.fill(password, ' ');
  }

  return trustManagers;
}
 
Example 16
Project: monarch   File: SocketCreator.java   View Source Code Vote up 4 votes
private KeyManager[] getKeyManagers() throws KeyStoreException, IOException,
    NoSuchAlgorithmException, CertificateException, UnrecoverableKeyException {
  GfeConsoleReader consoleReader = GfeConsoleReaderFactory.getDefaultConsoleReader();

  KeyManager[] keyManagers = null;
  String keyStoreType = sslConfig.getKeystoreType();
  if (StringUtils.isEmpty(keyStoreType)) {
    // read from console, default on empty
    if (consoleReader.isSupported()) {
      keyStoreType =
          consoleReader.readLine("Please enter the keyStoreType (javax.net.ssl.keyStoreType) : ");
    } else {
      keyStoreType = KeyStore.getDefaultType();
    }
  }
  KeyStore keyStore = KeyStore.getInstance(keyStoreType);
  String keyStoreFilePath = sslConfig.getKeystore();
  if (StringUtils.isEmpty(keyStoreFilePath)) {
    if (consoleReader.isSupported()) {
      keyStoreFilePath = consoleReader
          .readLine("Please enter the keyStore location (javax.net.ssl.keyStore) : ");
    } else {
      keyStoreFilePath =
          System.getProperty("user.home") + System.getProperty("file.separator") + ".keystore";
    }
  }

  FileInputStream fileInputStream = new FileInputStream(keyStoreFilePath);
  String passwordString = sslConfig.getKeystorePassword();
  char[] password = null;
  if (passwordString != null) {
    if (passwordString.trim().equals("")) {
      String encryptedPass = System.getenv("javax.net.ssl.keyStorePassword");
      if (!StringUtils.isEmpty(encryptedPass)) {
        String toDecrypt = "encrypted(" + encryptedPass + ")";
        passwordString = PasswordUtil.decrypt(toDecrypt);
        password = passwordString.toCharArray();
      }
      // read from the console
      if (StringUtils.isEmpty(passwordString) && consoleReader != null) {
        password = consoleReader.readPassword(
            "Please enter password for keyStore (javax.net.ssl.keyStorePassword) : ");
      }
    } else {
      password = passwordString.toCharArray();
    }
  }
  keyStore.load(fileInputStream, password);
  // default algorithm can be changed by setting property "ssl.KeyManagerFactory.algorithm" in
  // security properties
  KeyManagerFactory keyManagerFactory =
      KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
  keyManagerFactory.init(keyStore, password);
  keyManagers = keyManagerFactory.getKeyManagers();
  // follow the security tip in java doc
  if (password != null) {
    java.util.Arrays.fill(password, ' ');
  }

  KeyManager[] extendedKeyManagers = new KeyManager[keyManagers.length];

  for (int i = 0; i < keyManagers.length; i++)

  {
    extendedKeyManagers[i] = new ExtendedAliasKeyManager(keyManagers[i], sslConfig.getAlias());
  }

  return extendedKeyManagers;
}
 
Example 17
Project: kafka-0.11.0.0-src-with-comment   File: SslFactory.java   View Source Code Vote up 4 votes
private SecurityStore(String type, String path, Password password) {
    this.type = type == null ? KeyStore.getDefaultType() : type;
    this.path = path;
    this.password = password;
}
 
Example 18
Project: pac4j-plus   File: SAML2ClientConfiguration.java   View Source Code Vote up 4 votes
private void createKeystore() {
    try {
        Security.addProvider(new BouncyCastleProvider());

        if (CommonHelper.isBlank(this.keyStoreAlias)) {
            this.keyStoreAlias = getClass().getSimpleName();
            LOGGER.warn("Using keystore alias {}", this.keyStoreAlias);
        }

        if (CommonHelper.isBlank(this.keyStoreType)) {
            this.keyStoreType = KeyStore.getDefaultType();
            LOGGER.warn("Using keystore type {}", this.keyStoreType);
        }

        final KeyStore ks = KeyStore.getInstance(this.keyStoreType);
        final char[] password = this.keystorePassword.toCharArray();
        ks.load(null, password);

        final KeyPairGenerator kpg = KeyPairGenerator.getInstance("RSA");
        kpg.initialize(2048);
        final KeyPair kp = kpg.genKeyPair();

        final X509V3CertificateGenerator cert = new X509V3CertificateGenerator();
        cert.setSerialNumber(BigInteger.valueOf(1));
        final String dn = InetAddress.getLocalHost().getHostName();
        cert.setSubjectDN(new X509Principal("CN=" + dn));
        cert.setIssuerDN(new X509Principal("CN=" + dn));
        cert.setPublicKey(kp.getPublic());
        cert.setNotBefore(new Date());

        final Calendar c = Calendar.getInstance();
        c.setTime(new Date());
        c.add(Calendar.YEAR, 1);
        cert.setNotAfter(c.getTime());

        cert.setSignatureAlgorithm("SHA1WithRSA");
        final PrivateKey signingKey = kp.getPrivate();
        final X509Certificate certificate = cert.generate(signingKey, "BC");

        ks.setKeyEntry(this.keyStoreAlias, signingKey, password, new Certificate[]{certificate});

        try (FileOutputStream fos = new FileOutputStream(this.keystoreResource.getFile().getCanonicalPath())) {
            ks.store(fos, password);
            fos.flush();
        }

        LOGGER.info("Created keystore {} with key alias {} ",
                keystoreResource.getFile().getCanonicalPath(),
                ks.aliases().nextElement());

        this.keyStore = ks;
    } catch (final Exception e) {
        throw new SAMLException("Could not create keystore", e);
    }
}
 
Example 19
Project: springboot-shiro-cas-mybatis   File: FileTrustStoreSslSocketFactory.java   View Source Code Vote up 2 votes
/**
 * Instantiates a new trusted proxy authentication trust store ssl socket factory.
 * Defaults to <code>TLSv1</code> and {@link SSLConnectionSocketFactory#BROWSER_COMPATIBLE_HOSTNAME_VERIFIER}
 * for the supported protocols and hostname verification.
 * @param trustStoreFile the trust store file
 * @param trustStorePassword the trust store password
 */
public FileTrustStoreSslSocketFactory(final File trustStoreFile, final String trustStorePassword) {
    this(trustStoreFile, trustStorePassword, KeyStore.getDefaultType());
}
 
Example 20
Project: cas-5.1.0   File: FileTrustStoreSslSocketFactory.java   View Source Code Vote up 2 votes
/**
 * Instantiates a new trusted proxy authentication trust store ssl socket factory.
 * Defaults to {@code TLSv1} and {@link SSLConnectionSocketFactory#BROWSER_COMPATIBLE_HOSTNAME_VERIFIER}
 * for the supported protocols and hostname verification.
 *
 * @param trustStoreFile     the trust store file
 * @param trustStorePassword the trust store password
 */
public FileTrustStoreSslSocketFactory(final Resource trustStoreFile, final String trustStorePassword) {
    this(trustStoreFile, trustStorePassword, KeyStore.getDefaultType());
}