Example usage for java.security KeyPairGenerator initialize

List of usage examples for java.security KeyPairGenerator initialize

Introduction

In this page you can find the example usage for java.security KeyPairGenerator initialize.

Prototype

public void initialize(AlgorithmParameterSpec params) throws InvalidAlgorithmParameterException 

Source Link

Document

Initializes the key pair generator using the specified parameter set and the SecureRandom implementation of the highest-priority installed provider as the source of randomness.

Usage

From source file:org.forgerock.openidm.security.impl.SecurityResourceProvider.java

/**
 * Generates a CSR request.// ww w .  j a va 2s .c  om
 * 
 * @param alias
 * @param algorithm
 * @param signatureAlgorithm
 * @param keySize
 * @param params
 * @return
 * @throws Exception
 */
protected Pair<PKCS10CertificationRequest, PrivateKey> generateCSR(String alias, String algorithm,
        String signatureAlgorithm, int keySize, JsonValue params) throws Exception {

    // Construct the distinguished name
    StringBuilder sb = new StringBuilder();
    sb.append("CN=").append(params.get("CN").required().asString().replaceAll(",", "\\\\,"));
    sb.append(", OU=").append(params.get("OU").defaultTo("None").asString().replaceAll(",", "\\\\,"));
    sb.append(", O=").append(params.get("O").defaultTo("None").asString().replaceAll(",", "\\\\,"));
    sb.append(", L=").append(params.get("L").defaultTo("None").asString().replaceAll(",", "\\\\,"));
    sb.append(", ST=").append(params.get("ST").defaultTo("None").asString().replaceAll(",", "\\\\,"));
    sb.append(", C=").append(params.get("C").defaultTo("None").asString().replaceAll(",", "\\\\,"));

    // Create the principle subject name
    X509Principal subjectName = new X509Principal(sb.toString());

    //store.getStore().

    // Generate the key pair
    KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance(algorithm);
    keyPairGenerator.initialize(keySize);
    KeyPair keyPair = keyPairGenerator.generateKeyPair();
    PublicKey publicKey = keyPair.getPublic();
    PrivateKey privateKey = keyPair.getPrivate();

    // Generate the certificate request
    PKCS10CertificationRequest cr = new PKCS10CertificationRequest(signatureAlgorithm, subjectName, publicKey,
            null, privateKey);

    // Store the private key to use when the signed cert is return and updated
    logger.debug("Storing private key with alias {}", alias);
    storeKeyPair(alias, keyPair);

    return Pair.of(cr, privateKey);
}

From source file:org.tolven.gatekeeper.CertificateHelper.java

private X509CertificatePrivateKeyPair createX509CertificatePrivateKeyPair(String email, String commonName,
        String organizationUnitName, String organizationName, String stateOrProvince) {
    String privateKeyAlgorithm = USER_PRIVATE_KEY_ALGORITHM_PROP;
    KeyPairGenerator keyPairGenerator;
    try {/*from ww  w  . j av  a2s. c  o  m*/
        keyPairGenerator = KeyPairGenerator.getInstance(privateKeyAlgorithm);
    } catch (NoSuchAlgorithmException ex) {
        throw new RuntimeException("Could not get KeyPairGenerator for algorithm: " + privateKeyAlgorithm, ex);
    }
    int keySize = Integer.parseInt(USER_PRIVATE_KEY_LENGTH_PROP);
    keyPairGenerator.initialize(keySize);
    KeyPair keyPair = keyPairGenerator.generateKeyPair();
    X500Principal x500Principal = getX500Principal(email, commonName, organizationUnitName, organizationName,
            stateOrProvince);
    return createSelfSignedCertificate(x500Principal, keyPair.getPublic(), keyPair.getPrivate());
}

From source file:org.signserver.server.cryptotokens.KeystoreCryptoTokenTest.java

/**
 * Tests that a worker just set up with a key store containing a new
 * key-pair and is activated manually gets status ACTIVE.
 * @throws Exception/*from   w  w  w  .j  av a  2 s.  co m*/
 */
public void testActivateWithNewKeystore() throws Exception {
    LOG.info("testActivateWithNewKeystore");

    final boolean autoActivate = false;

    final int workerId = WORKER_CMS;
    try {
        setCMSSignerPropertiesCombined(workerId, autoActivate);

        // Create a key-pair and certificate in the keystore
        FileOutputStream out = null;
        try {
            KeyStore ks = KeyStore.getInstance("PKCS12", "BC");
            ks.load(null, null);

            // Generate key and issue certificate
            final KeyPairGenerator kpg = KeyPairGenerator.getInstance("RSA", "BC");
            kpg.initialize(1024);
            final KeyPair keyPair = kpg.generateKeyPair();
            X509Certificate[] chain = new X509Certificate[1];
            chain[0] = getSelfCertificate("CN=TestActivateWithNewKeystore" + ", C=SE",
                    (long) 30 * 24 * 60 * 60 * 365, keyPair);
            ks.setKeyEntry("newkey11", keyPair.getPrivate(), pin.toCharArray(), chain);

            out = new FileOutputStream(keystoreFile);
            ks.store(out, pin.toCharArray());
        } finally {
            IOUtils.closeQuietly(out);
        }

        workerSession.setWorkerProperty(workerId, "DEFAULTKEY", "newkey11");
        workerSession.reloadConfiguration(workerId);

        // Activate first so we can generate a key
        workerSession.activateSigner(workerId, pin);

        List<String> errors = workerSession.getStatus(workerId).getFatalErrors();
        assertTrue("Fatal errors: " + errors, workerSession.getStatus(workerId).getFatalErrors().isEmpty());

    } finally {
        FileUtils.deleteQuietly(keystoreFile);
        removeWorker(workerId);
    }
}

From source file:org.candlepin.sync.ExporterTest.java

private KeyPair createKeyPair() {
    KeyPair cpKeyPair = null;/*  w  w w  . j av  a 2 s. co  m*/

    try {
        KeyPairGenerator generator = KeyPairGenerator.getInstance("RSA");
        generator.initialize(2048);
        java.security.KeyPair newPair = generator.generateKeyPair();
        cpKeyPair = new KeyPair(newPair.getPrivate(), newPair.getPublic());
    } catch (NoSuchAlgorithmException e) {
        throw new RuntimeException(e);
    }

    return cpKeyPair;
}

From source file:org.signserver.server.cryptotokens.KeystoreCryptoTokenTest.java

/**
 * Test importing a new certificate chain to an existing keystore.
 * @throws Exception //w w  w . j a  va 2 s.c o m
 */
public void testImportCertificateChain() throws Exception {
    LOG.info("testImportCertificateChain");

    final boolean autoActivate = false;

    final int workerId = WORKER_CMS;
    try {
        setCMSSignerPropertiesCombined(workerId, autoActivate);

        // Generate key and issue certificate
        final KeyPairGenerator kpg = KeyPairGenerator.getInstance("RSA", "BC");
        kpg.initialize(1024);
        final KeyPair keyPair = kpg.generateKeyPair();

        // Create a key-pair and certificate in the keystore
        FileOutputStream out = null;
        try {
            KeyStore ks = KeyStore.getInstance("PKCS12", "BC");
            ks.load(null, null);

            final X509Certificate[] chain = new X509Certificate[1];
            chain[0] = getSelfCertificate("CN=Test", (long) 30 * 24 * 60 * 60 * 365, keyPair);
            ks.setKeyEntry("newkey11", keyPair.getPrivate(), pin.toCharArray(), chain);

            out = new FileOutputStream(keystoreFile);
            ks.store(out, pin.toCharArray());
        } finally {
            IOUtils.closeQuietly(out);
        }

        workerSession.setWorkerProperty(workerId, "DEFAULTKEY", "newkey11");
        workerSession.reloadConfiguration(workerId);

        // Activate first so we can generate a key
        workerSession.activateSigner(workerId, pin);

        List<String> errors = workerSession.getStatus(workerId).getFatalErrors();
        assertTrue("Fatal errors: " + errors, workerSession.getStatus(workerId).getFatalErrors().isEmpty());

        // generate a new certificate
        final X509Certificate newCert = getSelfCertificate("CN=TestNew", (long) 30 * 24 * 60 * 60 * 365,
                keyPair);

        workerSession.importCertificateChain(workerId, Arrays.asList(newCert.getEncoded()), "newkey11", null);

        final Certificate readCert = workerSession.getSignerCertificate(workerId);
        assertTrue("Matching certificates", Arrays.equals(newCert.getEncoded(), readCert.getEncoded()));
    } finally {
        FileUtils.deleteQuietly(keystoreFile);
        removeWorker(workerId);
    }
}

From source file:org.forgerock.openidm.security.impl.SecurityResourceProvider.java

/**
 * Generates a self signed certificate using the given properties.
 *
 * @param commonName the subject's common name
 * @param organization the subject's organization name
 * @param organizationUnit the subject's organization unit name
 * @param stateOrProvince the subject's state or province
 * @param country the subject's country code
 * @param locality the subject's locality
 * @param algorithm the algorithm to use
 * @param keySize the keysize to use//from   www  .  j  av a 2 s .  co  m
 * @param signatureAlgorithm the signature algorithm to use
 * @param validFrom when the certificate is valid from
 * @param validTo when the certificate is valid until
 * @return The generated certificate
 * @throws Exception
 */
protected Pair<X509Certificate, PrivateKey> generateCertificate(String commonName, String organization,
        String organizationUnit, String stateOrProvince, String country, String locality, String algorithm,
        int keySize, String signatureAlgorithm, String validFrom, String validTo) throws Exception {

    KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance(algorithm); // "RSA","BC"
    keyPairGenerator.initialize(keySize);
    KeyPair keyPair = keyPairGenerator.generateKeyPair();

    // Generate self-signed certificate
    X500NameBuilder builder = new X500NameBuilder(BCStyle.INSTANCE);
    builder.addRDN(BCStyle.C, country);
    builder.addRDN(BCStyle.ST, stateOrProvince);
    builder.addRDN(BCStyle.L, locality);
    builder.addRDN(BCStyle.OU, organizationUnit);
    builder.addRDN(BCStyle.O, organization);
    builder.addRDN(BCStyle.CN, commonName);

    Date notBefore = null;
    Date notAfter = null;
    if (validFrom == null) {
        notBefore = new Date(System.currentTimeMillis() - 1000L * 60 * 60 * 24 * 30);
    } else {
        DateTime notBeforeDateTime = DateUtil.getDateUtil().parseIfDate(validFrom);
        if (notBeforeDateTime == null) {
            throw new InternalServerErrorException("Invalid date format for 'validFrom' property");
        } else {
            notBefore = notBeforeDateTime.toDate();
        }
    }
    if (validTo == null) {
        Calendar date = Calendar.getInstance();
        date.setTime(new Date());
        date.add(Calendar.YEAR, 10);
        notAfter = date.getTime();
    } else {
        DateTime notAfterDateTime = DateUtil.getDateUtil().parseIfDate(validTo);
        if (notAfterDateTime == null) {
            throw new InternalServerErrorException("Invalid date format for 'validTo' property");
        } else {
            notAfter = notAfterDateTime.toDate();
        }
    }

    BigInteger serial = BigInteger.valueOf(System.currentTimeMillis());

    X509v3CertificateBuilder v3CertGen = new JcaX509v3CertificateBuilder(builder.build(), serial, notBefore,
            notAfter, builder.build(), keyPair.getPublic());

    ContentSigner sigGen = new JcaContentSignerBuilder(signatureAlgorithm).setProvider(BC)
            .build(keyPair.getPrivate());

    X509Certificate cert = new JcaX509CertificateConverter().setProvider(BC)
            .getCertificate(v3CertGen.build(sigGen));
    cert.checkValidity(new Date());
    cert.verify(cert.getPublicKey());

    return Pair.of(cert, keyPair.getPrivate());
}

From source file:org.mitre.openid.connect.client.AbstractOIDCAuthenticationFilter.java

@Override
public void afterPropertiesSet() {
    super.afterPropertiesSet();

    Assert.notNull(errorRedirectURI, "An Error Redirect URI must be supplied");

    KeyPairGenerator keyPairGenerator;

    try {//ww w  .j  a  v a  2 s .  co m
        keyPairGenerator = KeyPairGenerator.getInstance("RSA");
        keyPairGenerator.initialize(KEY_SIZE);
        KeyPair keyPair = keyPairGenerator.generateKeyPair();
        publicKey = keyPair.getPublic();
        privateKey = keyPair.getPrivate();

        signer = Signature.getInstance(SIGNING_ALGORITHM);
    } catch (GeneralSecurityException generalSecurityException) {
        // generalSecurityException.printStackTrace();
        throw new IllegalStateException(generalSecurityException);
    }

    // prepend the spec necessary SCOPE
    setScope((scope != null && !scope.isEmpty()) ? SCOPE + " " + scope : SCOPE);
}

From source file:org.loklak.data.DAO.java

/**
 * initialize the DAO//from   w w w  . j  ava 2  s  . c  om
 * @param configMap
 * @param dataPath the path to the data directory
 */
public static void init(Map<String, String> configMap, Path dataPath) throws Exception {

    log("initializing loklak DAO");

    config = configMap;
    conf_dir = new File("conf");
    bin_dir = new File("bin");
    html_dir = new File("html");

    // wake up susi
    File susiinitpath = new File(conf_dir, "susi");
    File sudiwatchpath = new File(new File("data"), "susi");
    susi = new SusiMind(susiinitpath, sudiwatchpath);
    String susi_boilerplate_name = "susi_cognition_boilerplate.json";
    File susi_boilerplate_file = new File(sudiwatchpath, susi_boilerplate_name);
    if (!susi_boilerplate_file.exists())
        Files.copy(new File(conf_dir, "susi/" + susi_boilerplate_name + ".example"), susi_boilerplate_file);

    // initialize public and private keys
    public_settings = new Settings(new File("data/settings/public.settings.json"));
    File private_file = new File("data/settings/private.settings.json");
    private_settings = new Settings(private_file);
    OS.protectPath(private_file.toPath());

    if (!private_settings.loadPrivateKey() || !public_settings.loadPublicKey()) {
        log("Can't load key pair. Creating new one");

        // create new key pair
        KeyPairGenerator keyGen;
        try {
            String algorithm = "RSA";
            keyGen = KeyPairGenerator.getInstance(algorithm);
            keyGen.initialize(2048);
            KeyPair keyPair = keyGen.genKeyPair();
            private_settings.setPrivateKey(keyPair.getPrivate(), algorithm);
            public_settings.setPublicKey(keyPair.getPublic(), algorithm);
        } catch (NoSuchAlgorithmException e) {
            throw e;
        }
        log("Key creation finished. Peer hash: " + public_settings.getPeerHashAlgorithm() + " "
                + public_settings.getPeerHash());
    } else {
        log("Key pair loaded from file. Peer hash: " + public_settings.getPeerHashAlgorithm() + " "
                + public_settings.getPeerHash());
    }

    File datadir = dataPath.toFile();
    // check if elasticsearch shall be accessed as external cluster
    String transport = configMap.get("elasticsearch_transport.enabled");
    if (transport != null && "true".equals(transport)) {
        String cluster_name = configMap.get("elasticsearch_transport.cluster.name");
        String transport_addresses_string = configMap.get("elasticsearch_transport.addresses");
        if (transport_addresses_string != null && transport_addresses_string.length() > 0) {
            String[] transport_addresses = transport_addresses_string.split(",");
            elasticsearch_client = new ElasticsearchClient(transport_addresses, cluster_name);
        }
    } else {
        // use all config attributes with a key starting with "elasticsearch." to set elasticsearch settings

        ESLoggerFactory.setDefaultFactory(new Slf4jESLoggerFactory());
        org.elasticsearch.common.settings.Settings.Builder settings = org.elasticsearch.common.settings.Settings
                .builder();
        for (Map.Entry<String, String> entry : config.entrySet()) {
            String key = entry.getKey();
            if (key.startsWith("elasticsearch."))
                settings.put(key.substring(14), entry.getValue());
        }
        // patch the home path
        settings.put("path.home", datadir.getAbsolutePath());
        settings.put("path.data", datadir.getAbsolutePath());
        settings.build();

        // start elasticsearch
        elasticsearch_client = new ElasticsearchClient(settings);
    }

    // open AAA storage
    Path settings_dir = dataPath.resolve("settings");
    settings_dir.toFile().mkdirs();
    Path authentication_path = settings_dir.resolve("authentication.json");
    authentication = new JsonTray(authentication_path.toFile(), 10000);
    OS.protectPath(authentication_path);
    Path authorization_path = settings_dir.resolve("authorization.json");
    authorization = new JsonTray(authorization_path.toFile(), 10000);
    OS.protectPath(authorization_path);
    Path passwordreset_path = settings_dir.resolve("passwordreset.json");
    passwordreset = new JsonTray(passwordreset_path.toFile(), 10000);
    OS.protectPath(passwordreset_path);
    Path accounting_path = settings_dir.resolve("accounting.json");
    accounting = new JsonTray(accounting_path.toFile(), 10000);
    OS.protectPath(accounting_path);
    Path login_keys_path = settings_dir.resolve("login-keys.json");
    login_keys = new JsonFile(login_keys_path.toFile());
    OS.protectPath(login_keys_path);

    Log.getLog().info("Initializing user roles");

    Path userRoles_path = settings_dir.resolve("userRoles.json");
    userRoles = new UserRoles(new JsonFile(userRoles_path.toFile()));
    OS.protectPath(userRoles_path);

    try {
        userRoles.loadUserRolesFromObject();
        Log.getLog().info("Loaded user roles from file");
    } catch (IllegalArgumentException e) {
        Log.getLog().info("Load default user roles");
        userRoles.loadDefaultUserRoles();
    }

    // open index
    Path index_dir = dataPath.resolve("index");
    if (index_dir.toFile().exists())
        OS.protectPath(index_dir); // no other permissions to this path

    // define the index factories
    messages = new MessageFactory(elasticsearch_client, IndexName.messages.name(), CACHE_MAXSIZE,
            EXIST_MAXSIZE);
    messages_hour = new MessageFactory(elasticsearch_client, IndexName.messages_hour.name(), CACHE_MAXSIZE,
            EXIST_MAXSIZE);
    messages_day = new MessageFactory(elasticsearch_client, IndexName.messages_day.name(), CACHE_MAXSIZE,
            EXIST_MAXSIZE);
    messages_week = new MessageFactory(elasticsearch_client, IndexName.messages_week.name(), CACHE_MAXSIZE,
            EXIST_MAXSIZE);
    users = new UserFactory(elasticsearch_client, IndexName.users.name(), CACHE_MAXSIZE, EXIST_MAXSIZE);
    accounts = new AccountFactory(elasticsearch_client, IndexName.accounts.name(), CACHE_MAXSIZE,
            EXIST_MAXSIZE);
    queries = new QueryFactory(elasticsearch_client, IndexName.queries.name(), CACHE_MAXSIZE, EXIST_MAXSIZE);
    importProfiles = new ImportProfileFactory(elasticsearch_client, IndexName.import_profiles.name(),
            CACHE_MAXSIZE, EXIST_MAXSIZE);

    // create indices and set mapping (that shows how 'elastic' elasticsearch is: it's always good to define data types)
    File mappingsDir = new File(new File(conf_dir, "elasticsearch"), "mappings");
    int shards = Integer.parseInt(configMap.get("elasticsearch.index.number_of_shards"));
    int replicas = Integer.parseInt(configMap.get("elasticsearch.index.number_of_replicas"));
    for (IndexName index : IndexName.values()) {
        log("initializing index '" + index.name() + "'...");
        try {
            elasticsearch_client.createIndexIfNotExists(index.name(), shards, replicas);
        } catch (Throwable e) {
            Log.getLog().warn(e);
        }
        try {
            elasticsearch_client.setMapping(index.name(), new File(mappingsDir, index.getSchemaFilename()));
        } catch (Throwable e) {
            Log.getLog().warn(e);
        }
    }
    // elasticsearch will probably take some time until it is started up. We do some other stuff meanwhile..

    // create and document the data dump dir
    assets = new File(datadir, "assets");
    external_data = new File(datadir, "external");
    dictionaries = new File(external_data, "dictionaries");
    dictionaries.mkdirs();

    // create message dump dir
    String message_dump_readme = "This directory contains dump files for messages which arrived the platform.\n"
            + "There are three subdirectories for dump files:\n"
            + "- own:      for messages received with this peer. There is one file for each month.\n"
            + "- import:   hand-over directory for message dumps to be imported. Drop dumps here and they are imported.\n"
            + "- imported: dump files which had been processed from the import directory are moved here.\n"
            + "You can import dump files from other peers by dropping them into the import directory.\n"
            + "Each dump file must start with the prefix '" + MESSAGE_DUMP_FILE_PREFIX
            + "' to be recognized.\n";
    message_dump_dir = dataPath.resolve("dump");
    message_dump = new JsonRepository(message_dump_dir.toFile(), MESSAGE_DUMP_FILE_PREFIX, message_dump_readme,
            JsonRepository.COMPRESSED_MODE, true, Runtime.getRuntime().availableProcessors());

    account_dump_dir = dataPath.resolve("accounts");
    account_dump_dir.toFile().mkdirs();
    OS.protectPath(account_dump_dir); // no other permissions to this path
    account_dump = new JsonRepository(account_dump_dir.toFile(), ACCOUNT_DUMP_FILE_PREFIX, null,
            JsonRepository.REWRITABLE_MODE, false, Runtime.getRuntime().availableProcessors());

    File user_dump_dir = new File(datadir, "accounts");
    user_dump_dir.mkdirs();
    user_dump = new JsonDataset(user_dump_dir, USER_DUMP_FILE_PREFIX,
            new JsonDataset.Column[] { new JsonDataset.Column("id_str", false),
                    new JsonDataset.Column("screen_name", true) },
            "retrieval_date", DateParser.PATTERN_ISO8601MILLIS, JsonRepository.REWRITABLE_MODE, false,
            Integer.MAX_VALUE);
    followers_dump = new JsonDataset(user_dump_dir, FOLLOWERS_DUMP_FILE_PREFIX,
            new JsonDataset.Column[] { new JsonDataset.Column("screen_name", true) }, "retrieval_date",
            DateParser.PATTERN_ISO8601MILLIS, JsonRepository.REWRITABLE_MODE, false, Integer.MAX_VALUE);
    following_dump = new JsonDataset(user_dump_dir, FOLLOWING_DUMP_FILE_PREFIX,
            new JsonDataset.Column[] { new JsonDataset.Column("screen_name", true) }, "retrieval_date",
            DateParser.PATTERN_ISO8601MILLIS, JsonRepository.REWRITABLE_MODE, false, Integer.MAX_VALUE);

    Path log_dump_dir = dataPath.resolve("log");
    log_dump_dir.toFile().mkdirs();
    OS.protectPath(log_dump_dir); // no other permissions to this path
    access = new AccessTracker(log_dump_dir.toFile(), ACCESS_DUMP_FILE_PREFIX, 60000, 3000);
    access.start(); // start monitor

    import_profile_dump_dir = dataPath.resolve("import-profiles");
    import_profile_dump = new JsonRepository(import_profile_dump_dir.toFile(), IMPORT_PROFILE_FILE_PREFIX, null,
            JsonRepository.COMPRESSED_MODE, false, Runtime.getRuntime().availableProcessors());

    // load schema folder
    conv_schema_dir = new File("conf/conversion");
    schema_dir = new File("conf/schema");

    // load dictionaries if they are embedded here
    // read the file allCountries.zip from http://download.geonames.org/export/dump/allCountries.zip
    //File allCountries = new File(dictionaries, "allCountries.zip");
    File cities1000 = new File(dictionaries, "cities1000.zip");
    if (!cities1000.exists()) {
        // download this file
        ClientConnection.download("http://download.geonames.org/export/dump/cities1000.zip", cities1000);
    }

    if (cities1000.exists()) {
        try {
            geoNames = new GeoNames(cities1000, new File(conf_dir, "iso3166.json"), 1);
        } catch (IOException e) {
            Log.getLog().warn(e.getMessage());
            cities1000.delete();
            geoNames = null;
        }
    }

    // finally wait for healthy status of elasticsearch shards
    ClusterHealthStatus required_status = ClusterHealthStatus
            .fromString(config.get("elasticsearch_requiredClusterHealthStatus"));
    boolean ok;
    do {
        log("Waiting for elasticsearch " + required_status.name() + " status");
        ok = elasticsearch_client.wait_ready(60000l, required_status);
    } while (!ok);
    /**
    do {
    log("Waiting for elasticsearch green status");
    health = elasticsearch_client.admin().cluster().prepareHealth().setWaitForGreenStatus().execute().actionGet();
    } while (health.isTimedOut());
    **/
    log("elasticsearch has started up!");

    // start the classifier
    new Thread() {
        public void run() {
            log("initializing the classifier...");
            try {
                Classifier.init(10000, 1000);
            } catch (Throwable e) {
                Log.getLog().warn(e);
            }
            log("classifier initialized!");
        }
    }.start();

    log("initializing queries...");
    File harvestingPath = new File(datadir, "queries");
    if (!harvestingPath.exists())
        harvestingPath.mkdirs();
    String[] list = harvestingPath.list();
    for (String queryfile : list) {
        if (queryfile.startsWith(".") || queryfile.endsWith("~"))
            continue;
        try {
            BufferedReader reader = new BufferedReader(
                    new InputStreamReader(new FileInputStream(new File(harvestingPath, queryfile))));
            String line;
            List<IndexEntry<QueryEntry>> bulkEntries = new ArrayList<>();
            while ((line = reader.readLine()) != null) {
                line = line.trim().toLowerCase();
                if (line.length() == 0)
                    continue;
                if (line.charAt(0) <= '9') {
                    // truncate statistic
                    int p = line.indexOf(' ');
                    if (p < 0)
                        continue;
                    line = line.substring(p + 1).trim();
                }
                // write line into query database
                if (!existQuery(line)) {
                    bulkEntries.add(new IndexEntry<QueryEntry>(line, SourceType.TWITTER,
                            new QueryEntry(line, 0, 60000, SourceType.TWITTER, false)));
                }
                if (bulkEntries.size() > 1000) {
                    queries.writeEntries(bulkEntries);
                    bulkEntries.clear();
                }
            }
            queries.writeEntries(bulkEntries);
            reader.close();
        } catch (IOException e) {
            Log.getLog().warn(e);
        }
    }
    log("queries initialized.");

    log("finished DAO initialization");
}

From source file:com.l2jfree.loginserver.manager.LoginManager.java

/**
 * Private constructor to avoid direct instantiation.
 * Initialize a key generator./*  www .ja  v a2 s  .  co  m*/
 */
private LoginManager() {
    try {
        _log.info("LoginManager: initializing.");

        _hackProtection = new FastMap<InetAddress, FailedLoginAttempt>();

        _keyPairs = new ScrambledKeyPair[10];

        _service = (AccountsServices) L2Registry.getBean("AccountsServices");

        _connections = new FastList<L2Client>();

        KeyPairGenerator keygen = null;

        try {
            keygen = KeyPairGenerator.getInstance("RSA");
            RSAKeyGenParameterSpec spec = new RSAKeyGenParameterSpec(1024, RSAKeyGenParameterSpec.F4);
            keygen.initialize(spec);
        } catch (GeneralSecurityException e) {
            _log.fatal("Error in RSA setup:", e);
            _log.info("Server shutting down now");
            System.exit(1);
            return;
        }

        //generate the initial set of keys
        for (int i = 0; i < 10; i++) {
            _keyPairs[i] = new ScrambledKeyPair(keygen.generateKeyPair());
        }
        _log.info("LoginManager: Cached 10 KeyPairs for RSA communication");

        testCipher((RSAPrivateKey) _keyPairs[0].getPair().getPrivate());

        // Store keys for blowfish communication
        generateBlowFishKeys();
    } catch (GeneralSecurityException e) {
        _log.fatal("FATAL: Failed initializing LoginManager. Reason: " + e.getMessage(), e);
        System.exit(1);
    }

}

From source file:org.tolven.config.model.CredentialManager.java

private X509CertificatePrivateKeyPair createSelfSignedCertificate(X500Principal subjectX500Principal)
        throws GeneralSecurityException {
    KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA");
    keyPairGenerator.initialize(1024);
    KeyPair keyPair = keyPairGenerator.generateKeyPair();
    X509Certificate certificate = signCertificate(subjectX500Principal, keyPair.getPublic(),
            subjectX500Principal, keyPair.getPrivate());
    return new X509CertificatePrivateKeyPair(certificate, keyPair.getPrivate());
}