List of usage examples for java.security KeyPairGenerator getInstance
public static KeyPairGenerator getInstance(String algorithm) throws NoSuchAlgorithmException
From source file:org.nuxeo.ecm.platform.signature.core.pki.CertServiceImpl.java
@Override public KeyStore initializeUser(UserInfo userInfo, String suppliedPassword) throws CertException { char[] password = suppliedPassword.toCharArray(); KeyStore ks = null;//from w w w .j ava 2s . c o m String userName = userInfo.getUserFields().get(CNField.UserID); AliasWrapper keystoreAlias = new AliasWrapper(userName); try { ks = java.security.KeyStore.getInstance(KEYSTORE_TYPE); ks.load(null, password); KeyPairGenerator keyGen = KeyPairGenerator.getInstance(KEY_ALGORITHM); keyGen.initialize(KEY_SIZE); KeyPair keyPair = keyGen.genKeyPair(); java.security.cert.Certificate[] chain = { getRootCertificate() }; ks.setKeyEntry(keystoreAlias.getId(AliasType.KEY), keyPair.getPrivate(), password, chain); X509Certificate cert = getCertificate(keyPair, userInfo); ks.setCertificateEntry(keystoreAlias.getId(AliasType.CERT), cert); } catch (CertificateException e) { throw new CertException(e); } catch (IOException e) { throw new CertException(e); } catch (KeyStoreException e) { throw new CertException(e); } catch (NoSuchAlgorithmException e) { throw new CertException(e); } return ks; }
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 w w w . j a v a2s . c o m 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:net.nicholaswilliams.java.licensing.encryption.TestKeyFileUtilities.java
@Test public void testPublicKeyEncryption03() throws Throwable { PublicKey publicKey = KeyPairGenerator.getInstance(KeyFileUtilities.keyAlgorithm).generateKeyPair() .getPublic();/*w w w . j a va 2s. c om*/ byte[] publicKeyData = KeyFileUtilities.writeEncryptedPublicKey(publicKey, "myTestPassword01".toCharArray()); assertNotNull("The key data should not be null.", publicKeyData); assertTrue("The key data should have length.", publicKeyData.length > 0); PublicKey publicKey2 = KeyFileUtilities.readEncryptedPublicKey(publicKeyData, "myTestPassword01".toCharArray()); assertNotNull("The key should not be null.", publicKey2); assertFalse("The objects should not be the same.", publicKey == publicKey2); assertEquals("The keys should be the same.", publicKey, publicKey2); }
From source file:org.loklak.data.DAO.java
/** * initialize the DAO/*from w w w. j a va2 s . c o 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:test.unit.be.fedict.eid.idp.protocol.saml2.SAML2ArtifactProtocolServiceTest.java
private KeyPair generateKeyPair() throws Exception { KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA"); SecureRandom random = new SecureRandom(); keyPairGenerator.initialize(new RSAKeyGenParameterSpec(1024, RSAKeyGenParameterSpec.F4), random); return keyPairGenerator.generateKeyPair(); }
From source file:com.github.aynu.yukar.framework.util.SecurityHelper.java
/** * ?????//from w ww .j av a2 s. c om * <dl> * <dt>? * <dd>EC??????256?????? * </dl> * @return ?(???) */ public static KeyPair createSignKeyPair() { try { final KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("EC"); keyPairGenerator.initialize(256); return keyPairGenerator.generateKeyPair(); } catch (final NoSuchAlgorithmException e) { throw new RuntimeException(e); } }
From source file:org.keycloak.testsuite.client.OIDCJwksClientRegistrationTest.java
@Test public void testTwoClientsWithSameKid() throws Exception { // Create client with manually set "kid" OIDCClientRepresentation response = createClientWithManuallySetKid("a1"); // Create client2 OIDCClientRepresentation clientRep2 = createRep(); clientRep2.setGrantTypes(Collections.singletonList(OAuth2Constants.CLIENT_CREDENTIALS)); clientRep2.setTokenEndpointAuthMethod(OIDCLoginProtocol.PRIVATE_KEY_JWT); // Generate some random keys for client2 KeyPairGenerator generator = KeyPairGenerator.getInstance("RSA"); generator.initialize(2048);// w ww.j a v a 2s .c o m PublicKey client2PublicKey = generator.generateKeyPair().getPublic(); // Set client2 with manually set "kid" to be same like kid of client1 (but keys for both clients are different) JSONWebKeySet keySet = new JSONWebKeySet(); keySet.setKeys(new JWK[] { JWKBuilder.create().kid("a1").rs256(client2PublicKey) }); clientRep2.setJwks(keySet); clientRep2 = reg.oidc().create(clientRep2); // Authenticate client1 Map<String, String> generatedKeys = testingClient.testApp().oidcClientEndpoints().getKeysAsPem(); assertAuthenticateClientSuccess(generatedKeys, response, "a1"); // Assert item in publicKey cache for client1 String expectedCacheKey = PublicKeyStorageUtils.getClientModelCacheKey(REALM_NAME, response.getClientId()); Assert.assertTrue(testingClient.testing().cache(InfinispanConnectionProvider.KEYS_CACHE_NAME) .contains(expectedCacheKey)); // Assert it's not possible to authenticate as client2 with the same "kid" like client1 assertAuthenticateClientError(generatedKeys, clientRep2, "a1"); }
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'"); }/*from w w w. ja v a2 s. c o 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.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 . ja v a 2s . 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.nuxeo.ecm.directory.ldap.LDAPDirectoryTestCase.java
/** * Method to create a X509 certificate used to test the creation and the update of an entry in the ldap. * * @return A X509 certificate//from www .ja v a 2s. c o m * @throws CertificateException * @throws NoSuchAlgorithmException * @throws InvalidKeyException * @throws SignatureException * @throws IllegalStateException * @since 5.9.3 */ protected X509Certificate createCertificate(String dnNameStr) throws NoSuchAlgorithmException, CertificateException, InvalidKeyException, IllegalStateException, SignatureException { X509Certificate cert = null; // Parameters used to define the certificate // yesterday Date validityBeginDate = new Date(System.currentTimeMillis() - 24 * 60 * 60 * 1000); // in 2 years Date validityEndDate = new Date(System.currentTimeMillis() + 2 * 365 * 24 * 60 * 60 * 1000); // Generate the key pair KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA"); keyPairGenerator.initialize(1024, new SecureRandom()); KeyPair keyPair = keyPairGenerator.generateKeyPair(); // Define the content of the certificate X509V1CertificateGenerator certGen = new X509V1CertificateGenerator(); X500Principal dnName = new X500Principal(dnNameStr); certGen.setSerialNumber(BigInteger.valueOf(System.currentTimeMillis())); certGen.setSubjectDN(dnName); certGen.setIssuerDN(dnName); // use the same certGen.setNotBefore(validityBeginDate); certGen.setNotAfter(validityEndDate); certGen.setPublicKey(keyPair.getPublic()); certGen.setSignatureAlgorithm("SHA256WithRSA"); cert = certGen.generate(keyPair.getPrivate()); return cert; }