List of usage examples for java.security KeyPairGenerator genKeyPair
public final KeyPair genKeyPair()
From source file:org.apache.hadoop.yarn.server.resourcemanager.security.TestHopsworksRMAppSecurityActions.java
private PKCS10CertificationRequest generateCSR(String cn) throws Exception { KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA", "BC"); keyPairGenerator.initialize(1024);// w w w .j ava 2 s . c o m KeyPair keyPair = keyPairGenerator.genKeyPair(); X500NameBuilder x500NameBuilder = new X500NameBuilder(BCStyle.INSTANCE); x500NameBuilder.addRDN(BCStyle.CN, cn); x500NameBuilder.addRDN(BCStyle.O, O); x500NameBuilder.addRDN(BCStyle.OU, OU); X500Name x500Name = x500NameBuilder.build(); PKCS10CertificationRequestBuilder csrBuilder = new JcaPKCS10CertificationRequestBuilder(x500Name, keyPair.getPublic()); return csrBuilder .build(new JcaContentSignerBuilder("SHA256withRSA").setProvider("BC").build(keyPair.getPrivate())); }
From source file:org.loklak.api.aaa.PublicKeyRegistrationService.java
@Override public JSONObject serviceImpl(Query post, HttpServletResponse response, Authorization authorization, final JSONObjectWithDefault permissions) throws APIException { if (post.get("register", null) == null && !post.get("create", false) && !post.get("getParameters", false)) { throw new APIException(400, "Accepted parameters: 'register', 'create' or 'getParameters'"); }/*from w w w. j a v a 2s.c om*/ JSONObject result = new JSONObject(); // return algorithm parameters and users for whom we are allowed to register a key if (post.get("getParameters", false)) { result.put("self", permissions.getBoolean("self", false)); result.put("users", permissions.getJSONObject("users")); result.put("userRoles", permissions.getJSONObject("userRoles")); JSONObject algorithms = new JSONObject(); JSONObject rsa = new JSONObject(); JSONArray keySizes = new JSONArray(); for (int i : allowedKeySizesRSA) { keySizes.put(i); } rsa.put("sizes", keySizes); rsa.put("defaultSize", defaultKeySizeRSA); algorithms.put("RSA", rsa); result.put("algorithms", algorithms); JSONArray formats = new JSONArray(); for (String format : allowedFormats) { formats.put(format); } result.put("formats", formats); return result; } // for which id? String id; if (post.get("id", null) != null) id = post.get("id", null); else id = authorization.getIdentity().getName(); // check if we are allowed register a key if (!id.equals(authorization.getIdentity().getName())) { // if we don't want to register the key for the current user // create Authentication to check if the user id is a registered user ClientCredential credential = new ClientCredential(ClientCredential.Type.passwd_login, id); Authentication authentication = new Authentication(credential, DAO.authentication); if (authentication.getIdentity() == null) { // check if identity is valid authentication.delete(); throw new APIException(400, "Bad request"); // do not leak if user exists or not } // check if the current user is allowed to create a key for the user in question boolean allowed = false; // check if the user in question is in 'users' if (permissions.getJSONObject("users", null).has(id) && permissions.getJSONObjectWithDefault("users", null).getBoolean(id, false)) { allowed = true; } else { // check if the user role of the user in question is in 'userRoles' Authorization auth = new Authorization(authentication.getIdentity(), DAO.authorization, DAO.userRoles); for (String key : permissions.getJSONObject("userRoles").keySet()) { if (key.equals(auth.getUserRole().getName()) && permissions.getJSONObject("userRoles").getBoolean(key)) { allowed = true; } } } if (!allowed) throw new APIException(400, "Bad request"); // do not leak if user exists or not } else { // if we want to register a key for this user, bad are not allowed to (for example anonymous users) if (!permissions.getBoolean("self", false)) throw new APIException(403, "You are not allowed to register a public key"); } // set algorithm. later, we maybe want to support other algorithms as well String algorithm = "RSA"; if (post.get("algorithm", null) != null) { algorithm = post.get("algorithm", null); } if (post.get("create", false)) { // create a new key pair on the server if (algorithm.equals("RSA")) { int keySize = 2048; if (post.get("key-size", null) != null) { int finalKeyLength = post.get("key-size", 0); if (!IntStream.of(allowedKeySizesRSA).anyMatch(x -> x == finalKeyLength)) { throw new APIException(400, "Invalid key size."); } keySize = finalKeyLength; } KeyPairGenerator keyGen; KeyPair keyPair; try { keyGen = KeyPairGenerator.getInstance(algorithm); keyGen.initialize(keySize); keyPair = keyGen.genKeyPair(); } catch (NoSuchAlgorithmException e) { throw new APIException(500, "Server error"); } registerKey(authorization.getIdentity(), keyPair.getPublic()); String pubkey_pem = null, privkey_pem = null; try { StringWriter writer = new StringWriter(); PemWriter pemWriter = new PemWriter(writer); pemWriter.writeObject(new PemObject("PUBLIC KEY", keyPair.getPublic().getEncoded())); pemWriter.flush(); pemWriter.close(); pubkey_pem = writer.toString(); } catch (IOException e) { } try { StringWriter writer = new StringWriter(); PemWriter pemWriter = new PemWriter(writer); pemWriter.writeObject(new PemObject("PRIVATE KEY", keyPair.getPrivate().getEncoded())); pemWriter.flush(); pemWriter.close(); privkey_pem = writer.toString(); } catch (IOException e) { } result.put("publickey_DER_BASE64", Base64.getEncoder().encodeToString(keyPair.getPublic().getEncoded())); result.put("privatekey_DER_BASE64", Base64.getEncoder().encodeToString(keyPair.getPrivate().getEncoded())); result.put("publickey_PEM", pubkey_pem); result.put("privatekey_PEM", privkey_pem); result.put("keyhash", IO.getKeyHash(keyPair.getPublic())); try { result.put("keyhash_urlsave", URLEncoder.encode(IO.getKeyHash(keyPair.getPublic()), "UTF-8")); } catch (UnsupportedEncodingException e) { } result.put("key-size", keySize); result.put("message", "Successfully created and registered key. Make sure to copy the private key, it won't be saved on the server"); return result; } throw new APIException(400, "Unsupported algorithm"); } else if (post.get("register", null) != null) { if (algorithm.equals("RSA")) { String type = post.get("type", null); if (type == null) type = "DER"; RSAPublicKey pub; String encodedKey; try { encodedKey = URLDecoder.decode(post.get("register", null), "UTF-8"); } catch (Throwable e) { throw new APIException(500, "Server error"); } Log.getLog().info("Key (" + type + "): " + encodedKey); if (type.equals("DER")) { try { X509EncodedKeySpec keySpec = new X509EncodedKeySpec(Base64.getDecoder().decode(encodedKey)); pub = (RSAPublicKey) KeyFactory.getInstance(algorithm).generatePublic(keySpec); } catch (Throwable e) { throw new APIException(400, "Public key not readable (DER)"); } } else if (type.equals("PEM")) { try { PemReader pemReader = new PemReader(new StringReader(encodedKey)); PemObject pem = pemReader.readPemObject(); X509EncodedKeySpec keySpec = new X509EncodedKeySpec(pem.getContent()); pub = (RSAPublicKey) KeyFactory.getInstance(algorithm).generatePublic(keySpec); } catch (Exception e) { throw new APIException(400, "Public key not readable (PEM)"); } } else { throw new APIException(400, "Invalid value for 'type'."); } // check key size (not really perfect yet) int keySize; int bitLength = pub.getModulus().bitLength(); if (bitLength <= 512) { keySize = 512; } else if (bitLength <= 1024) { keySize = 1024; } else if (bitLength <= 2048) { keySize = 2048; } else if (bitLength <= 4096) { keySize = 4096; } else { keySize = 8192; } if (!IntStream.of(allowedKeySizesRSA).anyMatch(x -> x == keySize)) { throw new APIException(400, "Invalid key length."); } registerKey(authorization.getIdentity(), pub); String pubkey_pem = null; try { StringWriter writer = new StringWriter(); PemWriter pemWriter = new PemWriter(writer); pemWriter.writeObject(new PemObject("PUBLIC KEY", pub.getEncoded())); pemWriter.flush(); pemWriter.close(); pubkey_pem = writer.toString(); } catch (IOException e) { } result.put("publickey_DER_BASE64", Base64.getEncoder().encodeToString(pub.getEncoded())); result.put("publickey_PEM", pubkey_pem); result.put("keyhash", IO.getKeyHash(pub)); try { result.put("keyhash_urlsave", URLEncoder.encode(IO.getKeyHash(pub), "UTF-8")); } catch (UnsupportedEncodingException e) { } result.put("message", "Successfully registered key."); return result; } throw new APIException(400, "Unsupported algorithm"); } throw new APIException(400, "Invalid parameter"); }
From source file:ai.susi.server.api.aaa.PublicKeyRegistrationService.java
@Override public JSONObject serviceImpl(Query post, HttpServletResponse response, Authorization authorization, final JsonObjectWithDefault permissions) throws APIException { if (post.get("register", null) == null && !post.get("create", false) && !post.get("getParameters", false)) { throw new APIException(400, "Accepted parameters: 'register', 'create' or 'getParameters'"); }/* w w w.j a v a2s . co m*/ JSONObject result = new JSONObject(); // return algorithm parameters and users for whom we are allowed to register a key if (post.get("getParameters", false)) { result.put("self", permissions.getBoolean("self", false)); result.put("users", permissions.getJSONObject("users")); result.put("userRoles", permissions.getJSONObject("userRoles")); JSONObject algorithms = new JSONObject(); JSONObject rsa = new JSONObject(); JSONArray keySizes = new JSONArray(); for (int i : allowedKeySizesRSA) { keySizes.put(i); } rsa.put("sizes", keySizes); rsa.put("defaultSize", defaultKeySizeRSA); algorithms.put("RSA", rsa); result.put("algorithms", algorithms); JSONArray formats = new JSONArray(); for (String format : allowedFormats) { formats.put(format); } result.put("formats", formats); return result; } // for which id? String id; if (post.get("id", null) != null) id = post.get("id", null); else id = authorization.getIdentity().getName(); // check if we are allowed register a key if (!id.equals(authorization.getIdentity().getName())) { // if we don't want to register the key for the current user // create Authentication to check if the user id is a registered user ClientCredential credential = new ClientCredential(ClientCredential.Type.passwd_login, id); Authentication authentication = new Authentication(credential, DAO.authentication); if (authentication.getIdentity() == null) { // check if identity is valid authentication.delete(); throw new APIException(400, "Bad request"); // do not leak if user exists or not } // check if the current user is allowed to create a key for the user in question boolean allowed = false; // check if the user in question is in 'users' if (permissions.getJSONObject("users", null).has(id) && permissions.getJSONObjectWithDefault("users", null).getBoolean(id, false)) { allowed = true; } else { // check if the user role of the user in question is in 'userRoles' Authorization auth = new Authorization(authentication.getIdentity(), DAO.authorization, DAO.userRoles); for (String key : permissions.getJSONObject("userRoles").keySet()) { if (key.equals(auth.getUserRole().getName()) && permissions.getJSONObject("userRoles").getBoolean(key)) { allowed = true; } } } if (!allowed) throw new APIException(400, "Bad request"); // do not leak if user exists or not } else { // if we want to register a key for this user, bad are not allowed to (for example anonymous users) if (!permissions.getBoolean("self", false)) throw new APIException(403, "You are not allowed to register a public key"); } // set algorithm. later, we maybe want to support other algorithms as well String algorithm = "RSA"; if (post.get("algorithm", null) != null) { algorithm = post.get("algorithm", null); } if (post.get("create", false)) { // create a new key pair on the server if (algorithm.equals("RSA")) { int keySize = 2048; if (post.get("key-size", null) != null) { int finalKeyLength = post.get("key-size", 0); if (!IntStream.of(allowedKeySizesRSA).anyMatch(x -> x == finalKeyLength)) { throw new APIException(400, "Invalid key size."); } keySize = finalKeyLength; } KeyPairGenerator keyGen; KeyPair keyPair; try { keyGen = KeyPairGenerator.getInstance(algorithm); keyGen.initialize(keySize); keyPair = keyGen.genKeyPair(); } catch (NoSuchAlgorithmException e) { throw new APIException(500, "Server error"); } registerKey(authorization.getIdentity(), keyPair.getPublic()); String pubkey_pem = null, privkey_pem = null; try { StringWriter writer = new StringWriter(); PemWriter pemWriter = new PemWriter(writer); pemWriter.writeObject(new PemObject("PUBLIC KEY", keyPair.getPublic().getEncoded())); pemWriter.flush(); pemWriter.close(); pubkey_pem = writer.toString(); } catch (IOException e) { } try { StringWriter writer = new StringWriter(); PemWriter pemWriter = new PemWriter(writer); pemWriter.writeObject(new PemObject("PRIVATE KEY", keyPair.getPrivate().getEncoded())); pemWriter.flush(); pemWriter.close(); privkey_pem = writer.toString(); } catch (IOException e) { } result.put("publickey_DER_BASE64", Base64.getEncoder().encodeToString(keyPair.getPublic().getEncoded())); result.put("privatekey_DER_BASE64", Base64.getEncoder().encodeToString(keyPair.getPrivate().getEncoded())); result.put("publickey_PEM", pubkey_pem); result.put("privatekey_PEM", privkey_pem); result.put("keyhash", IO.getKeyHash(keyPair.getPublic())); try { result.put("keyhash_urlsave", URLEncoder.encode(IO.getKeyHash(keyPair.getPublic()), "UTF-8")); } catch (UnsupportedEncodingException e) { } result.put("key-size", keySize); result.put("message", "Successfully created and registered key. Make sure to copy the private key, it won't be saved on the server"); return result; } throw new APIException(400, "Unsupported algorithm"); } else if (post.get("register", null) != null) { if (algorithm.equals("RSA")) { String type = post.get("type", null); if (type == null) type = "DER"; RSAPublicKey pub; String encodedKey; try { encodedKey = URLDecoder.decode(post.get("register", null), "UTF-8"); } catch (Throwable e) { throw new APIException(500, "Server error"); } Log.getLog().info("Key (" + type + "): " + encodedKey); if (type.equals("DER")) { try { X509EncodedKeySpec keySpec = new X509EncodedKeySpec(Base64.getDecoder().decode(encodedKey)); pub = (RSAPublicKey) KeyFactory.getInstance(algorithm).generatePublic(keySpec); } catch (Throwable e) { throw new APIException(400, "Public key not readable (DER)"); } } else if (type.equals("PEM")) { try { PemReader pemReader = new PemReader(new StringReader(encodedKey)); PemObject pem = pemReader.readPemObject(); X509EncodedKeySpec keySpec = new X509EncodedKeySpec(pem.getContent()); pub = (RSAPublicKey) KeyFactory.getInstance(algorithm).generatePublic(keySpec); } catch (Exception e) { throw new APIException(400, "Public key not readable (PEM)"); } } else { throw new APIException(400, "Invalid value for 'type'."); } // check key size (not really perfect yet) int keySize; int bitLength = pub.getModulus().bitLength(); if (bitLength <= 512) { keySize = 512; } else if (bitLength <= 1024) { keySize = 1024; } else if (bitLength <= 2048) { keySize = 2048; } else if (bitLength <= 4096) { keySize = 4096; } else { keySize = 8192; } if (!IntStream.of(allowedKeySizesRSA).anyMatch(x -> x == keySize)) { throw new APIException(400, "Invalid key length."); } registerKey(authorization.getIdentity(), pub); String pubkey_pem = null; try { StringWriter writer = new StringWriter(); PemWriter pemWriter = new PemWriter(writer); pemWriter.writeObject(new PemObject("PUBLIC KEY", pub.getEncoded())); pemWriter.flush(); pemWriter.close(); pubkey_pem = writer.toString(); } catch (IOException e) { } result.put("publickey_DER_BASE64", Base64.getEncoder().encodeToString(pub.getEncoded())); result.put("publickey_PEM", pubkey_pem); result.put("keyhash", IO.getKeyHash(pub)); try { result.put("keyhash_urlsave", URLEncoder.encode(IO.getKeyHash(pub), "UTF-8")); } catch (UnsupportedEncodingException e) { } result.put("message", "Successfully registered key."); return result; } throw new APIException(400, "Unsupported algorithm"); } throw new APIException(400, "Invalid parameter"); }
From source file:org.loklak.data.DAO.java
/** * initialize the DAO// w w w . ja v a2 s . co m * @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:edu.uiuc.ncsa.myproxy.MyProxyLogon.java
/** * Retrieves credentials from the MyProxy server. *///from w ww . j ava 2s. c o m public void getCredentials() throws IOException, GeneralSecurityException { KeyPairGenerator keyGenerator = KeyPairGenerator.getInstance(keyAlg); keyGenerator.initialize(getKeySize()); this.keypair = keyGenerator.genKeyPair(); MyPKCS10CertRequest pkcs10 = CertUtil.createCertRequest(this.keypair, pkcs10SigAlgName, DN, pkcs10Provider); getCredentials(pkcs10.getEncoded()); }
From source file:com.poscoict.license.service.BoardService.java
public Map<String, Object> passwordPop(HttpSession session) throws Exception { logger.info("get passwordPopForm"); Map<String, Object> map = new HashMap<String, Object>(); KeyPairGenerator generator = KeyPairGenerator.getInstance("RSA"); generator.initialize(2048);/*from ww w . j a va2 s .c om*/ KeyPair keyPair = generator.genKeyPair(); KeyFactory keyFactory = KeyFactory.getInstance("RSA"); PublicKey publicKey = keyPair.getPublic(); PrivateKey privateKey = keyPair.getPrivate(); // ? ? ?? ? . session.setAttribute("__rsaPrivateKey__", privateKey); // ? JavaScript RSA ?? . RSAPublicKeySpec publicSpec = (RSAPublicKeySpec) keyFactory.getKeySpec(publicKey, RSAPublicKeySpec.class); map.put("publicKeyModulus", publicSpec.getModulus().toString(16)); map.put("publicKeyExponent", publicSpec.getPublicExponent().toString(16)); logger.info("return passwordPopForm"); return map; }
From source file:org.wso2.carbon.device.mgt.iot.agent.firealarm.enrollment.EnrollmentManager.java
/** * This method creates the Public-Private Key pair for the current client. * * @return the generated KeyPair object/*w ww.j a v a2 s . c o m*/ * @throws AgentCoreOperationException when the given Security Provider does not exist or the Algorithmn used to * generate the key pair is invalid. */ private KeyPair generateKeyPair() throws AgentCoreOperationException { // Generate our key pair KeyPairGenerator keyPairGenerator; try { keyPairGenerator = KeyPairGenerator.getInstance(KEY_PAIR_ALGORITHM, PROVIDER); keyPairGenerator.initialize(KEY_SIZE, new SecureRandom(SEED)); } catch (NoSuchAlgorithmException e) { String errorMsg = "Algorithm [" + KEY_PAIR_ALGORITHM + "] provided for KeyPairGenerator is invalid."; log.error(errorMsg); throw new AgentCoreOperationException(errorMsg, e); } catch (NoSuchProviderException e) { String errorMsg = "Provider [" + PROVIDER + "] provided for KeyPairGenerator does not exist."; log.error(errorMsg); throw new AgentCoreOperationException(errorMsg, e); } return keyPairGenerator.genKeyPair(); }
From source file:org.wso2.carbon.device.mgt.iot.virtualfirealarm.agent.advanced.enrollment.EnrollmentManager.java
/** * This method creates the Public-Private Key pair for the current client. * * @return the generated KeyPair object/*from w w w . j ava2 s . co m*/ * @throws AgentCoreOperationException when the given Security Provider does not exist or the Algorithmn used to * generate the key pair is invalid. */ private KeyPair generateKeyPair() throws AgentCoreOperationException { // Generate key pair KeyPairGenerator keyPairGenerator; try { keyPairGenerator = KeyPairGenerator.getInstance(KEY_PAIR_ALGORITHM, PROVIDER); keyPairGenerator.initialize(KEY_SIZE, new SecureRandom(SEED)); } catch (NoSuchAlgorithmException e) { String errorMsg = "Algorithm [" + KEY_PAIR_ALGORITHM + "] provided for KeyPairGenerator is invalid."; log.error(errorMsg); throw new AgentCoreOperationException(errorMsg, e); } catch (NoSuchProviderException e) { String errorMsg = "Provider [" + PROVIDER + "] provided for KeyPairGenerator does not exist."; log.error(errorMsg); throw new AgentCoreOperationException(errorMsg, e); } return keyPairGenerator.genKeyPair(); }
From source file:org.dasein.cloud.google.compute.server.ServerSupport.java
@Override public @Nonnull VirtualMachine launch(@Nonnull VMLaunchOptions withLaunchOptions) throws CloudException, InternalException { APITrace.begin(getProvider(), "launchVM"); // windows-cloud_windows-server-2012-r2-dc-v20150629 validateLaunchOptions(withLaunchOptions); // this will exception out on problem. try {/* www. ja va 2s. c o m*/ Compute gce = provider.getGoogleCompute(); GoogleMethod method = new GoogleMethod(provider); String hostName = getCapabilities().getVirtualMachineNamingConstraints() .convertToValidName(withLaunchOptions.getHostName(), Locale.US); Instance instance = new Instance(); instance.setName(hostName); instance.setDescription(withLaunchOptions.getDescription()); if (withLaunchOptions.getStandardProductId().contains("+")) { instance.setMachineType(getProduct(withLaunchOptions.getStandardProductId()).getDescription()); } else { instance.setMachineType(getProduct( withLaunchOptions.getStandardProductId() + "+" + withLaunchOptions.getDataCenterId()) .getDescription()); } MachineImage image = provider.getComputeServices().getImageSupport() .getImage(withLaunchOptions.getMachineImageId()); AttachedDisk rootVolume = new AttachedDisk(); rootVolume.setBoot(Boolean.TRUE); rootVolume.setType("PERSISTENT"); rootVolume.setMode("READ_WRITE"); AttachedDiskInitializeParams params = new AttachedDiskInitializeParams(); // do not use withLaunchOptions.getFriendlyName() it is non compliant!!! params.setDiskName(hostName); // Not Optimum solution, update in core should come next release to have this be part of MachineImage try { String[] parts = withLaunchOptions.getMachineImageId().split("_"); Image img = gce.images().get(parts[0], parts[1]).execute(); Long size = img.getDiskSizeGb(); String diskSizeGb = size.toString(); if (null == diskSizeGb) { diskSizeGb = img.getUnknownKeys().get("diskSizeGb").toString(); } Long MinimumDiskSizeGb = Long.valueOf(diskSizeGb).longValue(); params.setDiskSizeGb(MinimumDiskSizeGb); } catch (Exception e) { params.setDiskSizeGb(10L); } if ((image != null) && (image.getTag("contentLink") != null)) params.setSourceImage((String) image.getTag("contentLink")); else throw new CloudException("Problem getting the contentLink tag value from the image for " + withLaunchOptions.getMachineImageId()); rootVolume.setInitializeParams(params); List<AttachedDisk> attachedDisks = new ArrayList<AttachedDisk>(); attachedDisks.add(rootVolume); if (withLaunchOptions.getVolumes().length > 0) { for (VolumeAttachment volume : withLaunchOptions.getVolumes()) { AttachedDisk vol = new AttachedDisk(); vol.setBoot(Boolean.FALSE); vol.setType("PERSISTENT"); vol.setMode("READ_WRITE"); vol.setAutoDelete(Boolean.FALSE); vol.setKind("compute#attachedDisk"); if (null != volume.getExistingVolumeId()) { vol.setDeviceName(volume.getExistingVolumeId()); vol.setSource(provider.getComputeServices().getVolumeSupport() .getVolume(volume.getExistingVolumeId()).getMediaLink()); } else { VolumeCreateOptions volumeOptions = volume.getVolumeToCreate(); volumeOptions.setDataCenterId(withLaunchOptions.getDataCenterId()); String newDisk = provider.getComputeServices().getVolumeSupport() .createVolume(volume.getVolumeToCreate()); vol.setDeviceName(newDisk); vol.setSource( provider.getComputeServices().getVolumeSupport().getVolume(newDisk).getMediaLink()); } attachedDisks.add(vol); } } instance.setDisks(attachedDisks); AccessConfig nicConfig = new AccessConfig(); nicConfig.setName("External NAT"); nicConfig.setType("ONE_TO_ONE_NAT");//Currently the only type supported if (withLaunchOptions.getStaticIpIds().length > 0) { nicConfig.setNatIP(withLaunchOptions.getStaticIpIds()[0]); } List<AccessConfig> accessConfigs = new ArrayList<AccessConfig>(); accessConfigs.add(nicConfig); NetworkInterface nic = new NetworkInterface(); nic.setName("nic0"); if (null != withLaunchOptions.getVlanId()) { VLAN vlan = provider.getNetworkServices().getVlanSupport().getVlan(withLaunchOptions.getVlanId()); nic.setNetwork(vlan.getTag("contentLink")); } else { nic.setNetwork( provider.getNetworkServices().getVlanSupport().getVlan("default").getTag("contentLink")); } nic.setAccessConfigs(accessConfigs); List<NetworkInterface> nics = new ArrayList<NetworkInterface>(); nics.add(nic); instance.setNetworkInterfaces(nics); instance.setCanIpForward(Boolean.FALSE); Scheduling scheduling = new Scheduling(); scheduling.setAutomaticRestart(Boolean.TRUE); scheduling.setOnHostMaintenance("TERMINATE"); instance.setScheduling(scheduling); Map<String, String> keyValues = new HashMap<String, String>(); if (withLaunchOptions.getBootstrapUser() != null && withLaunchOptions.getBootstrapKey() != null && !withLaunchOptions.getBootstrapUser().equals("") && !withLaunchOptions.getBootstrapKey().equals("")) { keyValues.put("sshKeys", withLaunchOptions.getBootstrapUser() + ":" + withLaunchOptions.getBootstrapKey()); } if (!withLaunchOptions.getMetaData().isEmpty()) { for (Map.Entry<String, Object> entry : withLaunchOptions.getMetaData().entrySet()) { keyValues.put(entry.getKey(), (String) entry.getValue()); } } if (!keyValues.isEmpty()) { Metadata metadata = new Metadata(); ArrayList<Metadata.Items> items = new ArrayList<Metadata.Items>(); for (Map.Entry<String, String> entry : keyValues.entrySet()) { Metadata.Items item = new Metadata.Items(); item.set("key", entry.getKey()); if ((entry.getValue() == null) || (entry.getValue().isEmpty() == true) || (entry.getValue().equals(""))) item.set("value", ""); // GCE HATES nulls... else item.set("value", entry.getValue()); items.add(item); } // https://github.com/GoogleCloudPlatform/compute-image-packages/tree/master/google-startup-scripts if (null != withLaunchOptions.getUserData()) { Metadata.Items item = new Metadata.Items(); item.set("key", "startup-script"); item.set("value", withLaunchOptions.getUserData()); items.add(item); } metadata.setItems(items); instance.setMetadata(metadata); } Tags tags = new Tags(); ArrayList<String> tagItems = new ArrayList<String>(); tagItems.add(hostName); // Each tag must be 1-63 characters long, and comply with RFC1035 tags.setItems(tagItems); instance.setTags(tags); String vmId = ""; try { Operation job = gce.instances().insert(provider.getContext().getAccountNumber(), withLaunchOptions.getDataCenterId(), instance).execute(); vmId = method.getOperationTarget(provider.getContext(), job, GoogleOperationType.ZONE_OPERATION, "", withLaunchOptions.getDataCenterId(), false); } catch (IOException ex) { if (ex.getClass() == GoogleJsonResponseException.class) { GoogleJsonResponseException gjre = (GoogleJsonResponseException) ex; throw new GoogleException(CloudErrorType.GENERAL, gjre.getStatusCode(), gjre.getContent(), gjre.getDetails().getMessage()); } else throw new CloudException("An error occurred launching the instance: " + ex.getMessage()); } catch (Exception e) { if ((e.getMessage().contains("The resource")) && (e.getMessage().contains("disks")) && (e.getMessage().contains("already exists"))) { throw new CloudException( "A disk named '" + withLaunchOptions.getFriendlyName() + "' already exists."); } else { throw new CloudException(e); } } if (!vmId.equals("")) { VirtualMachine vm = getVirtualMachine(vmId); if (withLaunchOptions.getMachineImageId().toLowerCase().contains("windows")) { // Generate the public/private key pair for encryption and decryption. KeyPair keys = null; try { KeyPairGenerator keyGen = KeyPairGenerator.getInstance("RSA"); keyGen.initialize(2048); keys = keyGen.genKeyPair(); } catch (NoSuchAlgorithmException e) { throw new InternalException(e); } resetPassword(vmId, withLaunchOptions.getDataCenterId(), keys); int retryCount = 20; while (retryCount-- > 0) { SerialPortOutput output = null; try { output = gce.instances().getSerialPortOutput(provider.getContext().getAccountNumber(), withLaunchOptions.getDataCenterId(), vmId).setPort(4).execute(); } catch (IOException e) { throw new CloudException(e); } System.out.println(output); // Get the last line - this will be a JSON string corresponding to the most recent password reset attempt. String[] entries = output.getContents().split("\n"); String outputEntry = entries[entries.length - 1]; // Parse output using the json-simple library. JSONParser parser = new JSONParser(); try { org.json.simple.JSONObject passwordDict = (org.json.simple.JSONObject) parser .parse(outputEntry); vm.setRootUser(passwordDict.get("userName").toString()); vm.setRootPassword( decryptPassword(passwordDict.get("encryptedPassword").toString(), keys)); break; } catch (Exception e) { } // ignore exception, just means metadata not yet avail. try { Thread.sleep(10000); } catch (InterruptedException e) { } } } return vm; } else { throw new CloudException( "Could not find the instance: " + withLaunchOptions.getFriendlyName() + " after launch."); } } finally { APITrace.end(); } }
From source file:org.sakaiproject.lti13.LTI13Servlet.java
@Override public void init(ServletConfig config) throws ServletException { super.init(config); if (ltiService == null) { ltiService = (LTIService) ComponentManager.get("org.sakaiproject.lti.api.LTIService"); }/*from ww w . j av a 2s. co m*/ if (tokenKeyPair == null) { try { KeyPairGenerator keyGen = KeyPairGenerator.getInstance("RSA"); keyGen.initialize(2048); tokenKeyPair = keyGen.genKeyPair(); } catch (NoSuchAlgorithmException ex) { Logger.getLogger(LTI13Servlet.class.getName()).log(Level.SEVERE, "Unable to generate tokenKeyPair", ex); } } }