List of usage examples for java.util Properties remove
@Override public synchronized Object remove(Object key)
From source file:tv.phantombot.PhantomBot.java
public static void main(String[] args) throws IOException { // Move user files. moveUserConfig();//from w w w . jav a2s. com /* List of properties that must exist. */ String requiredProperties[] = new String[] { "oauth", "channel", "owner", "user" }; String requiredPropertiesErrorMessage = ""; if (Float.valueOf(System.getProperty("java.specification.version")) < (float) 1.8 || Float.valueOf(System.getProperty("java.specification.version")) >= (float) 1.9) { System.out.println("Detected Java " + System.getProperty("java.version") + ". " + "PhantomBot requires Java 8. Java 9 and above will NOT work."); System.exit(1); } /* Properties configuration */ Properties startProperties = new Properties(); /* Indicates that the botlogin.txt file should be overwritten/created. */ Boolean changed = false; /* Print the user dir */ com.gmt2001.Console.out.println("The working directory is: " + System.getProperty("user.dir")); com.gmt2001.Console.out.println("Detected Java " + System.getProperty("java.version") + " running on " + System.getProperty("os.name") + " " + System.getProperty("os.version") + " (" + System.getProperty("os.arch") + ")"); /* If prompted, now that the version has been reported, exit. */ if (args.length > 0) { if (args[0].equals("--version") || args[0].equals("-v")) { com.gmt2001.Console.out.println("PhantomBot Version: " + RepoVersion.getPhantomBotVersion() + " (" + RepoVersion.getRepoVersion() + ")"); System.exit(1); } } /* Load up the bot info from the bot login file */ try { if (new File("./config/botlogin.txt").exists()) { FileInputStream inputStream = new FileInputStream("./config/botlogin.txt"); startProperties.load(inputStream); inputStream.close(); } else { /* Fill in the Properties object with some default values. Note that some values are left * unset to be caught in the upcoming logic to enforce settings. */ startProperties.setProperty("baseport", "25000"); startProperties.setProperty("usehttps", "false"); startProperties.setProperty("webenable", "true"); startProperties.setProperty("msglimit30", "19.0"); startProperties.setProperty("musicenable", "true"); startProperties.setProperty("whisperlimit60", "60.0"); } } catch (IOException ex) { com.gmt2001.Console.err.printStackTrace(ex); } catch (Exception ex) { com.gmt2001.Console.err.printStackTrace(ex); } /* Load up the bot info from the environment */ for (Entry<String, String> v : System.getenv().entrySet()) { String Prefix = "PHANTOMBOT_"; String Key = v.getKey().toUpperCase(); String Value = v.getValue(); if (Key.startsWith(Prefix) && Prefix.length() < Key.length()) { Key = Key.substring(Prefix.length()).toLowerCase(); startProperties.setProperty(Key, Value); } } /* Check to enable debug mode */ if (startProperties.getProperty("debugon", "false").equals("true")) { com.gmt2001.Console.out.println("Debug Mode Enabled"); PhantomBot.enableDebugging = true; } /* Check to enable debug to File */ if (startProperties.getProperty("debuglog", "false").equals("true")) { com.gmt2001.Console.out.println("Debug Log Only Mode Enabled"); PhantomBot.enableDebugging = true; PhantomBot.enableDebuggingLogOnly = true; } /* Check to enable Script Reloading */ if (startProperties.getProperty("reloadscripts", "false").equals("true")) { com.gmt2001.Console.out.println("Enabling Script Reloading"); PhantomBot.reloadScripts = true; } /* Check to enable Rhino Debugger */ if (startProperties.getProperty("rhinodebugger", "false").equals("true")) { com.gmt2001.Console.out.println("Rhino Debugger will be launched if system supports it."); PhantomBot.enableRhinoDebugger = true; } /* Check to see if there's a webOauth set */ if (startProperties.getProperty("webauth") == null) { startProperties.setProperty("webauth", generateWebAuth()); com.gmt2001.Console.debug.println("New webauth key has been generated for ./config/botlogin.txt"); changed = true; } /* Check to see if there's a webOAuthRO set */ if (startProperties.getProperty("webauthro") == null) { startProperties.setProperty("webauthro", generateWebAuth()); com.gmt2001.Console.debug .println("New webauth read-only key has been generated for ./config/botlogin.txt"); changed = true; } /* Check to see if there's a panelUsername set */ if (startProperties.getProperty("paneluser") == null) { com.gmt2001.Console.debug.println( "No Panel Username, using default value of 'panel' for Control Panel and YouTube Player"); startProperties.setProperty("paneluser", "panel"); changed = true; } /* Check to see if there's a panelPassword set */ if (startProperties.getProperty("panelpassword") == null) { com.gmt2001.Console.debug.println( "No Panel Password, using default value of 'panel' for Control Panel and YouTube Player"); startProperties.setProperty("panelpassword", "panel"); changed = true; } /* Check to see if there's a youtubeOAuth set */ if (startProperties.getProperty("ytauth") == null) { startProperties.setProperty("ytauth", generateWebAuth()); com.gmt2001.Console.debug .println("New YouTube websocket key has been generated for ./config/botlogin.txt"); changed = true; } /* Check to see if there's a youtubeOAuthThro set */ if (startProperties.getProperty("ytauthro") == null) { startProperties.setProperty("ytauthro", generateWebAuth()); com.gmt2001.Console.debug .println("New YouTube read-only websocket key has been generated for ./config/botlogin.txt"); changed = true; } /* Make a new botlogin with the botName, oauth or channel is not found */ if (startProperties.getProperty("user") == null || startProperties.getProperty("oauth") == null || startProperties.getProperty("channel") == null) { try { com.gmt2001.Console.out.print("\r\n"); com.gmt2001.Console.out.print("Welcome to the PhantomBot setup process!\r\n"); com.gmt2001.Console.out.print( "If you have any issues please report them on our forum, Tweet at us, or join our Discord!\r\n"); com.gmt2001.Console.out.print("Forum: https://community.phantombot.tv/\r\n"); com.gmt2001.Console.out.print("Documentation: https://docs.phantombot.tv/\r\n"); com.gmt2001.Console.out.print("Twitter: https://twitter.com/PhantomBot/\r\n"); com.gmt2001.Console.out.print("Discord: https://discord.gg/rkPqDuK/\r\n"); com.gmt2001.Console.out.print("Support PhantomBot on Patreon: https://phantombot.tv/support/\r\n"); com.gmt2001.Console.out.print("\r\n"); final String os = System.getProperty("os.name").toLowerCase(); // Detect Windows, MacOS, Linux or any other operating system. if (os.startsWith("win")) { com.gmt2001.Console.out .print("PhantomBot has detected that your device is running Windows.\r\n"); com.gmt2001.Console.out.print( "Here's the setup guide for Windows: https://community.phantombot.tv/t/windows-setup-guide/"); } else if (os.startsWith("mac")) { com.gmt2001.Console.out.print("PhantomBot has detected that your device is running macOS.\r\n"); com.gmt2001.Console.out.print( "Here's the setup guide for macOS: https://community.phantombot.tv/t/macos-setup-guide/"); } else { com.gmt2001.Console.out.print("PhantomBot has detected that your device is running Linux.\r\n"); com.gmt2001.Console.out.print( "Here's the setup guide for Ubuntu: https://community.phantombot.tv/t/ubuntu-16-04-lts-setup-guide/\r\n"); com.gmt2001.Console.out.print( "Here's the setup guide for CentOS: https://community.phantombot.tv/t/centos-7-setup-guide/"); } com.gmt2001.Console.out.print("\r\n\r\n\r\n"); // Bot name. do { com.gmt2001.Console.out.print("1. Please enter the bot's Twitch username: "); startProperties.setProperty("user", System.console().readLine().trim().toLowerCase()); } while (startProperties.getProperty("user", "").length() <= 0); // Twitch oauth. do { com.gmt2001.Console.out.print("\r\n"); com.gmt2001.Console.out .print("2. You will now need a OAuth token for the bot to be able to chat.\r\n"); com.gmt2001.Console.out.print( "Please note, this OAuth token needs to be generated while you're logged in into the bot's Twitch account.\r\n"); com.gmt2001.Console.out.print( "If you're not logged in as the bot, please go to https://twitch.tv/ and login as the bot.\r\n"); com.gmt2001.Console.out .print("Get the bot's OAuth token here: https://twitchapps.com/tmi/\r\n"); com.gmt2001.Console.out.print("Please enter the bot's OAuth token: "); startProperties.setProperty("oauth", System.console().readLine().trim()); } while (startProperties.getProperty("oauth", "").length() <= 0); // api oauth. do { com.gmt2001.Console.out.print("\r\n"); com.gmt2001.Console.out.print( "3. You will now need your channel OAuth token for the bot to be able to change your title and game.\r\n"); com.gmt2001.Console.out.print( "Please note, this OAuth token needs to be generated while you're logged in into your caster account.\r\n"); com.gmt2001.Console.out.print( "If you're not logged in as the caster, please go to https://twitch.tv/ and login as the caster.\r\n"); com.gmt2001.Console.out .print("Get the your OAuth token here: https://phantombot.tv/oauth/\r\n"); com.gmt2001.Console.out.print("Please enter your OAuth token: "); startProperties.setProperty("apioauth", System.console().readLine().trim()); } while (startProperties.getProperty("apioauth", "").length() <= 0); // Channel name. do { com.gmt2001.Console.out.print("\r\n"); com.gmt2001.Console.out .print("4. Please enter the name of the Twitch channel the bot should join: "); startProperties.setProperty("channel", System.console().readLine().trim()); } while (startProperties.getProperty("channel", "").length() <= 0); // Panel username. do { com.gmt2001.Console.out.print("\r\n"); com.gmt2001.Console.out.print("5. Please enter a custom username for the web panel: "); startProperties.setProperty("paneluser", System.console().readLine().trim()); } while (startProperties.getProperty("paneluser", "").length() <= 0); // Panel password. do { com.gmt2001.Console.out.print("\r\n"); com.gmt2001.Console.out.print("6. Please enter a custom password for the web panel: "); startProperties.setProperty("panelpassword", System.console().readLine().trim()); } while (startProperties.getProperty("panelpassword", "").length() <= 0); com.gmt2001.Console.out.print("\r\n"); com.gmt2001.Console.out.print("PhantomBot will launch in 10 seconds.\r\n"); com.gmt2001.Console.out.print( "If you're hosting the bot locally you can access the control panel here: http://localhost:25000/panel \r\n"); com.gmt2001.Console.out.print( "If you're running the bot on a server, make sure to open the following ports: \r\n"); com.gmt2001.Console.out.print( "25000, 25003, and 25004. You have to change 'localhost' to your server ip to access the panel. \r\n"); try { Thread.sleep(10000); } catch (InterruptedException ex) { com.gmt2001.Console.debug.println("Failed to sleep in setup: " + ex.getMessage()); } changed = true; newSetup = true; } catch (NullPointerException ex) { com.gmt2001.Console.err.printStackTrace(ex); com.gmt2001.Console.out.println("[ERROR] Failed to setup PhantomBot. Now exiting..."); System.exit(0); } } /* Make sure the oauth has been set correctly */ if (startProperties.getProperty("oauth") != null) { if (!startProperties.getProperty("oauth").startsWith("oauth") && !startProperties.getProperty("oauth").isEmpty()) { startProperties.setProperty("oauth", "oauth:" + startProperties.getProperty("oauth")); changed = true; } } /* Make sure the apiOAuth has been set correctly */ if (startProperties.getProperty("apioauth") != null) { if (!startProperties.getProperty("apioauth").startsWith("oauth") && !startProperties.getProperty("apioauth").isEmpty()) { startProperties.setProperty("apioauth", "oauth:" + startProperties.getProperty("apioauth")); changed = true; } } /* Make sure the channelName does not have a # */ if (startProperties.getProperty("channel").startsWith("#")) { startProperties.setProperty("channel", startProperties.getProperty("channel").substring(1)); changed = true; } else if (startProperties.getProperty("channel").contains(".tv")) { startProperties.setProperty("channel", startProperties.getProperty("channel") .substring(startProperties.getProperty("channel").indexOf(".tv/") + 4).replaceAll("/", "")); changed = true; } /* Check for the owner after the channel check is done. */ if (startProperties.getProperty("owner") == null) { if (startProperties.getProperty("channel") != null) { if (!startProperties.getProperty("channel").isEmpty()) { startProperties.setProperty("owner", startProperties.getProperty("channel")); changed = true; } } } /* Iterate the properties and delete entries for anything that does not have a * value. */ for (String propertyKey : startProperties.stringPropertyNames()) { if (startProperties.getProperty(propertyKey).isEmpty()) { changed = true; startProperties.remove(propertyKey); } } /* * Check for required settings. */ for (String requiredProperty : requiredProperties) { if (startProperties.getProperty(requiredProperty) == null) { requiredPropertiesErrorMessage += requiredProperty + " "; } } if (!requiredPropertiesErrorMessage.isEmpty()) { com.gmt2001.Console.err.println(); com.gmt2001.Console.err.println("Missing Required Properties: " + requiredPropertiesErrorMessage); com.gmt2001.Console.err.println("Exiting PhantomBot"); System.exit(0); } /* Check to see if anything changed */ if (changed) { Properties outputProperties = new Properties() { @Override public synchronized Enumeration<Object> keys() { return Collections.enumeration(new TreeSet<>(super.keySet())); } }; try { try (FileOutputStream outputStream = new FileOutputStream("./config/botlogin.txt")) { outputProperties.putAll(startProperties); outputProperties.store(outputStream, "PhantomBot Configuration File"); } } catch (IOException ex) { com.gmt2001.Console.err.printStackTrace(ex); } } /* Start PhantomBot */ PhantomBot.instance = new PhantomBot(startProperties); }
From source file:org.sakaiproject.lessonbuildertool.tool.beans.SimplePageBean.java
/** * Adds or removes the requirement to have site.upd in order to see a page * i.e. hide or unhide a page/*w w w . j a va 2 s.co m*/ * @param pageId * The Id of the Page * @param visible * @return true for success, false for failure * @throws IdUnusedException * , PermissionException */ private boolean pageVisibilityHelper(Site site, String pageId, boolean visible) throws IdUnusedException, PermissionException { SitePage page = site.getPage(pageId); List<ToolConfiguration> tools = page.getTools(); Iterator<ToolConfiguration> iterator = tools.iterator(); // If all the tools on a page require site.upd then only users with site.upd will see // the page in the site nav of Charon... not sure about the other Sakai portals floating // about while (iterator.hasNext()) { ToolConfiguration placement = iterator.next(); Properties roleConfig = placement.getPlacementConfig(); String roleList = roleConfig.getProperty("functions.require"); String visibility = roleConfig.getProperty("sakai-portal:visible"); boolean saveChanges = false; if (roleList == null) { roleList = ""; } if (!(roleList.indexOf(SITE_UPD) > -1) && !visible) { if (roleList.length() > 0) { roleList += ","; } roleList += SITE_UPD; saveChanges = true; } else if ((roleList.indexOf(SITE_UPD) > -1) && visible) { roleList = roleList.replaceAll("," + SITE_UPD, ""); roleList = roleList.replaceAll(SITE_UPD, ""); saveChanges = true; } if (saveChanges) { roleConfig.setProperty("functions.require", roleList); if (visible) roleConfig.remove("sakai-portal:visible"); else roleConfig.setProperty("sakai-portal:visible", "false"); placement.save(); siteService.save(site); } } return true; }
From source file:org.ejbca.ui.cli.ca.CaType.java
@Override public CommandResult execute(ParameterContainer parameters) { // Install BC provider CryptoProviderTools.installBCProviderIfNotAvailable(); String profileName = parameters.get(CERTIFICATE_PROFILE_KEY); final String superAdminCN = parameters.get(SUPERADMIN_CN_KEY); //Default is X509 final CaType type; if (parameters.get(TYPE_KEY) != null) { type = CaType.lookupCaType(parameters.get(TYPE_KEY)); if (type == null) { log.error("CA type of name " + parameters.get(TYPE_KEY) + " unknown. Available types: " + CaType.getTypeNames()); return CommandResult.FUNCTIONAL_FAILURE; }/* w w w.j ava2 s.co m*/ } else { type = CaType.X509; } final String explicitEcc = (parameters.get(EXPLICIT_ECC_KEY) != null ? Boolean.TRUE.toString() : Boolean.FALSE.toString()); final String extcachainName = parameters.get(EXTERNAL_CHAIN_KEY); final String caname = parameters.get(CA_NAME_KEY); final String dn = CertTools.stringToBCDNString(StringTools.strip(parameters.get(DN_KEY))); final String catokentype = parameters.get(TOKEN_TYPE_KEY); String catokenpassword = StringTools.passwordDecryption(parameters.get(TOKEN_PASSWORD_KEY), "ca.tokenpassword"); if (StringUtils.equals(catokenpassword, "prompt")) { getLogger().info("Enter CA token password: "); getLogger().info(""); catokenpassword = String.valueOf(System.console().readPassword()); } final String keyspec = parameters.get(KEY_SPEC_KEY); final String keytype = parameters.get(KEY_TYPE_KEY); final long validity = Long.parseLong(parameters.get(VALIDITY_KEY)); String policyId = parameters.get(POLICY_ID_KEY); final ArrayList<CertificatePolicy> policies = new ArrayList<CertificatePolicy>(1); if ((policyId != null) && (policyId.toLowerCase().trim().equals("null"))) { policyId = null; } else { String[] array = policyId.split(" "); for (int i = 0; i < array.length; i += 2) { String id = array[i + 0]; String cpsurl = ""; if (array.length > i + 1) { cpsurl = array[i + 1]; } policies.add(new CertificatePolicy(id, CertificatePolicy.id_qt_cps, cpsurl)); } } String signAlg = parameters.get(SIGNING_ALGORITHM_KEY); Properties cryptoTokenProperties = new Properties(); String caTokenPropertiesFile = parameters.get(CA_TOKEN_PROPERTIES_KEY); if (caTokenPropertiesFile != null && "soft".equals(catokentype)) { log.error("Can't define a CAToken properties file for a soft token."); return CommandResult.FUNCTIONAL_FAILURE; } else if (caTokenPropertiesFile != null) { if ((caTokenPropertiesFile != null) && (!caTokenPropertiesFile.equalsIgnoreCase("null"))) { File file = new File(caTokenPropertiesFile); if (!file.exists()) { log.error("CA Token propoerties file " + caTokenPropertiesFile + " does not exist."); return CommandResult.FUNCTIONAL_FAILURE; } else if (file.isDirectory()) { log.error("CA Token propoerties file " + caTokenPropertiesFile + " is a directory."); return CommandResult.FUNCTIONAL_FAILURE; } else { try { cryptoTokenProperties.load(new FileInputStream(caTokenPropertiesFile)); } catch (FileNotFoundException e) { //Can't happen throw new IllegalStateException( "Newly referenced file " + caTokenPropertiesFile + " was not found.", e); } catch (IOException e) { throw new IllegalStateException("Unknown exception was caught when reading input stream", e); } } } } int signedByCAId = CAInfo.SELFSIGNED; if (parameters.get(SIGNED_BY) != null) { if (StringUtils.equalsIgnoreCase("External", parameters.get(SIGNED_BY))) { signedByCAId = CAInfo.SIGNEDBYEXTERNALCA; if (extcachainName == null) { log.error("Signing by external CA requires parameter " + EXTERNAL_CHAIN_KEY); return CommandResult.FUNCTIONAL_FAILURE; } } else { signedByCAId = Integer.valueOf(parameters.get(SIGNED_BY)); } } // Check that the CA doesn't exist already getLogger().debug("Checking that CA doesn't exist: " + caname); if (getCAInfo(getAuthenticationToken(), caname) != null) { getLogger().error("Error: CA '" + caname + "' exists already"); return CommandResult.FUNCTIONAL_FAILURE; } // Get the profile ID from the name if we specified a certain profile name int certificateProfileId = CertificateProfileConstants.CERTPROFILE_FIXED_ROOTCA; if (profileName == null) { if (signedByCAId == CAInfo.SELFSIGNED) { profileName = "ROOTCA"; } else { profileName = "SUBCA"; certificateProfileId = CertificateProfileConstants.CERTPROFILE_FIXED_SUBCA; } } else { certificateProfileId = EjbRemoteHelper.INSTANCE.getRemoteSession(CertificateProfileSessionRemote.class) .getCertificateProfileId(profileName); if (certificateProfileId == 0) { getLogger().info("Error: Certificate profile with name '" + profileName + "' does not exist."); return CommandResult.FUNCTIONAL_FAILURE; } CertificateProfile certificateProfile = EjbRemoteHelper.INSTANCE .getRemoteSession(CertificateProfileSessionRemote.class).getCertificateProfile(profileName); if (certificateProfile.getType() != CertificateConstants.CERTTYPE_ROOTCA && certificateProfile.getType() != CertificateConstants.CERTTYPE_SUBCA) { getLogger().info("Error: Certificate profile " + profileName + " is not of type ROOTCA or SUBCA."); return CommandResult.FUNCTIONAL_FAILURE; } } if (KeyTools.isUsingExportableCryptography()) { getLogger().warn("WARNING!"); getLogger().warn("WARNING: Using exportable strength crypto!"); getLogger().warn("WARNING!"); getLogger().warn( "The Unlimited Strength Crypto policy files have not been installed. EJBCA may not function correctly using exportable crypto."); getLogger().warn( "Please install the Unlimited Strength Crypto policy files as documented in the Installation guide."); getLogger().warn("Sleeping 10 seconds..."); getLogger().warn(""); try { Thread.sleep(10000); } catch (InterruptedException e) { throw new IllegalStateException("Thread.sleep was interrupted for unknown reason.", e); } } getLogger().info("Initializing CA"); getLogger().info("Generating rootCA keystore:"); getLogger().info("CA Type:" + type.getTypeName()); getLogger().info("CA name: " + caname); getLogger().info("SuperAdmin CN: " + superAdminCN); getLogger().info("DN: " + dn); getLogger().info("CA token type: " + catokentype); getLogger().info("CA token password: " + (catokenpassword == null ? "null" : "hidden")); getLogger().info("Keytype: " + keytype); getLogger().info("Keyspec: " + keyspec); getLogger().info("Validity (days): " + validity); getLogger().info("Policy ID: " + policyId); getLogger().info("Signature alg: " + signAlg); getLogger().info("Certificate profile: " + profileName); getLogger().info("CA token properties: " + cryptoTokenProperties.toString()); if (StringUtils.equalsIgnoreCase(explicitEcc, "true")) { // Set if we should use explicit ECC parameters of not. On Java 6 this renders the created CA certificate not serializable getLogger().info("Explicit ECC public key parameters: " + explicitEcc); cryptoTokenProperties.setProperty(CryptoToken.EXPLICIT_ECC_PUBLICKEY_PARAMETERS, explicitEcc); } try { String signedByStr = "Signed by: "; if ((signedByCAId != CAInfo.SELFSIGNED) && (signedByCAId != CAInfo.SIGNEDBYEXTERNALCA)) { try { CAInfo cainfo = EjbRemoteHelper.INSTANCE.getRemoteSession(CaSessionRemote.class) .getCAInfo(getAuthenticationToken(), signedByCAId); signedByStr += cainfo.getName(); } catch (CADoesntExistsException e) { throw new IllegalArgumentException("CA with id " + signedByCAId + " does not exist."); } } else if (signedByCAId == CAInfo.SELFSIGNED) { signedByStr += "Self signed"; } else if (signedByCAId == CAInfo.SIGNEDBYEXTERNALCA) { signedByStr += "External CA"; } getLogger().info(signedByStr); if (superAdminCN != null) { try { initAuthorizationModule(getAuthenticationToken(), dn.hashCode(), superAdminCN); } catch (RoleExistsException e) { log.error("Tryin to initialize Authorization module (since " + SUPERADMIN_CN_KEY + " was set), but module is already initialized."); return CommandResult.FUNCTIONAL_FAILURE; } } // Transform our mixed properties into CA Token properties and cryptoTokenProperties final Properties caTokenProperties = new Properties(); final String defaultAlias = cryptoTokenProperties .getProperty(CATokenConstants.CAKEYPURPOSE_DEFAULT_STRING); if (defaultAlias != null) { caTokenProperties.setProperty(CATokenConstants.CAKEYPURPOSE_DEFAULT_STRING, defaultAlias); cryptoTokenProperties.remove(CATokenConstants.CAKEYPURPOSE_DEFAULT_STRING); } else { caTokenProperties.setProperty(CATokenConstants.CAKEYPURPOSE_DEFAULT_STRING, CAToken.SOFTPRIVATEDECKEYALIAS); } final String certSignAlias = cryptoTokenProperties .getProperty(CATokenConstants.CAKEYPURPOSE_CERTSIGN_STRING); if (certSignAlias != null) { caTokenProperties.setProperty(CATokenConstants.CAKEYPURPOSE_CERTSIGN_STRING, certSignAlias); cryptoTokenProperties.remove(CATokenConstants.CAKEYPURPOSE_CERTSIGN_STRING); } else { caTokenProperties.setProperty(CATokenConstants.CAKEYPURPOSE_CERTSIGN_STRING, CAToken.SOFTPRIVATESIGNKEYALIAS); } final String crlSignAlias = cryptoTokenProperties .getProperty(CATokenConstants.CAKEYPURPOSE_CRLSIGN_STRING); if (crlSignAlias != null) { caTokenProperties.setProperty(CATokenConstants.CAKEYPURPOSE_CRLSIGN_STRING, crlSignAlias); cryptoTokenProperties.remove(CATokenConstants.CAKEYPURPOSE_CRLSIGN_STRING); } else { final String certSignValue = caTokenProperties .getProperty(CATokenConstants.CAKEYPURPOSE_CERTSIGN_STRING); caTokenProperties.setProperty(CATokenConstants.CAKEYPURPOSE_CRLSIGN_STRING, certSignValue); } final String hardTokenEncAlias = cryptoTokenProperties .getProperty(CATokenConstants.CAKEYPURPOSE_HARDTOKENENCRYPT_STRING); if (hardTokenEncAlias != null) { caTokenProperties.setProperty(CATokenConstants.CAKEYPURPOSE_HARDTOKENENCRYPT_STRING, hardTokenEncAlias); cryptoTokenProperties.remove(CATokenConstants.CAKEYPURPOSE_HARDTOKENENCRYPT_STRING); } final String keyEncAlias = cryptoTokenProperties .getProperty(CATokenConstants.CAKEYPURPOSE_KEYENCRYPT_STRING); if (keyEncAlias != null) { caTokenProperties.setProperty(CATokenConstants.CAKEYPURPOSE_KEYENCRYPT_STRING, keyEncAlias); cryptoTokenProperties.remove(CATokenConstants.CAKEYPURPOSE_KEYENCRYPT_STRING); } final String testKeyAlias = cryptoTokenProperties .getProperty(CATokenConstants.CAKEYPURPOSE_TESTKEY_STRING); if (testKeyAlias != null) { caTokenProperties.setProperty(CATokenConstants.CAKEYPURPOSE_TESTKEY_STRING, testKeyAlias); cryptoTokenProperties.remove(CATokenConstants.CAKEYPURPOSE_TESTKEY_STRING); } // If authentication code is provided as "null", use the default token password for soft tokens (from cesecore.properties), and auto activation // If a user defined authentication code is provided, use this and do not enable auto activation for soft tokens final char[] authenticationCode; if (StringUtils.equalsIgnoreCase(catokenpassword, "null")) { authenticationCode = null; // auto activation is enabled by default when using the default soft token pwd, which is used by default } else { authenticationCode = catokenpassword.toCharArray(); } // We must do this in order to not set the default password when creating a new soft CA token // A bit tricky, but thats how it is as of EJBCA 5.0.x, 2012-05. final String className; if (StringUtils.equalsIgnoreCase(catokentype, "soft")) { className = SoftCryptoToken.class.getName(); if (authenticationCode != null) { getLogger().info("Non default password used for soft CA token, auto activation disabled."); cryptoTokenProperties.setProperty(SoftCryptoToken.NODEFAULTPWD, "true"); } } else { className = PKCS11CryptoToken.class.getName(); } // Create the CryptoToken final CryptoTokenManagementSessionRemote cryptoTokenManagementSession = EjbRemoteHelper.INSTANCE .getRemoteSession(CryptoTokenManagementSessionRemote.class); int cryptoTokenId; try { try { cryptoTokenId = cryptoTokenManagementSession.createCryptoToken(getAuthenticationToken(), caname, className, cryptoTokenProperties, null, authenticationCode); } catch (CryptoTokenNameInUseException e) { // If the name was already in use we simply add a timestamp to the name to make it unique final String postfix = "_" + new SimpleDateFormat("yyyyMMddHHmmss").format(new Date()); try { cryptoTokenId = cryptoTokenManagementSession.createCryptoToken(getAuthenticationToken(), caname + postfix, className, cryptoTokenProperties, null, authenticationCode); } catch (CryptoTokenNameInUseException e1) { //Shouldn't be able to happen. throw new IllegalStateException( "Crypto token name was in use, even though a unique name was just generated.", e); } } } catch (NoSuchSlotException e) { log.error("Slot as defined in the file " + caTokenPropertiesFile + " was not found: " + e.getMessage()); return CommandResult.FUNCTIONAL_FAILURE; } catch (CryptoTokenAuthenticationFailedException e) { log.error("Authentication to crypto token failed: " + e.getMessage()); return CommandResult.FUNCTIONAL_FAILURE; } // Create the CA Token final CAToken caToken = new CAToken(cryptoTokenId, caTokenProperties); caToken.setSignatureAlgorithm(signAlg); caToken.setEncryptionAlgorithm(AlgorithmConstants.SIGALG_SHA1_WITH_RSA); // Generate CA keys if it is a soft CryptoToken if ("soft".equals(catokentype)) { final String signKeyAlias = caToken.getAliasFromPurpose(CATokenConstants.CAKEYPURPOSE_CERTSIGN); final String signKeySpecification = "DSA".equals(keytype) ? "DSA" + keyspec : keyspec; try { cryptoTokenManagementSession.createKeyPair(getAuthenticationToken(), cryptoTokenId, signKeyAlias, signKeySpecification); } catch (InvalidAlgorithmParameterException e) { log.error(signKeySpecification + " was not a valid alias: " + e.getMessage()); return CommandResult.FUNCTIONAL_FAILURE; } catch (InvalidKeyException e) { log.error("Key generation for alias " + signKeyAlias + " failed." + e.getMessage()); return CommandResult.FUNCTIONAL_FAILURE; } final String defaultKeyAlias = caToken .getAliasFromPurpose(CATokenConstants.CAKEYPURPOSE_KEYENCRYPT); // Decryption key must be RSA final String defaultKeySpecification = "RSA".equals(keytype) ? keyspec : "2048"; try { cryptoTokenManagementSession.createKeyPair(getAuthenticationToken(), cryptoTokenId, defaultKeyAlias, defaultKeySpecification); } catch (InvalidAlgorithmParameterException e) { log.error(defaultKeySpecification + " was not a valid alias: " + e.getMessage()); return CommandResult.FUNCTIONAL_FAILURE; } catch (InvalidKeyException e) { log.error("Key generation for alias " + defaultKeyAlias + " failed: " + e.getMessage()); return CommandResult.FUNCTIONAL_FAILURE; } } // Create the CA Info CAInfo cainfo = null; switch (type) { case CVC: // Get keysequence from SERIALNUMBER in DN is it exists final String keysequence = CertTools.getPartFromDN(dn, "SN"); if (keysequence != null) { getLogger().info("CVC key sequence: " + keysequence); caToken.setKeySequence(keysequence); if (StringUtils.isNumeric(keysequence)) { getLogger().info("CVC key sequence format is numeric."); caToken.setKeySequenceFormat(StringTools.KEY_SEQUENCE_FORMAT_NUMERIC); } else { getLogger().info("CVC key sequence format is alphanumeric."); caToken.setKeySequenceFormat(StringTools.KEY_SEQUENCE_FORMAT_ALPHANUMERIC); } } cainfo = createCVCCAInfo(dn, caname, certificateProfileId, validity, signedByCAId, caToken); break; case X509: //Default, slip below. default: // Create and active OSCP CA Service. ArrayList<ExtendedCAServiceInfo> extendedcaservices = new ArrayList<ExtendedCAServiceInfo>(); String extendedServiceKeySpec = keyspec; if (keytype.equals(AlgorithmConstants.KEYALGORITHM_RSA)) { // Never use larger keys than 2048 bit RSA for OCSP signing int len = Integer.parseInt(extendedServiceKeySpec); if (len > 2048) { extendedServiceKeySpec = "2048"; } } extendedcaservices.add(new XKMSCAServiceInfo(ExtendedCAServiceInfo.STATUS_INACTIVE, "CN=XKMSCertificate, " + dn, "", extendedServiceKeySpec, keytype)); extendedcaservices.add(new CmsCAServiceInfo(ExtendedCAServiceInfo.STATUS_INACTIVE, "CN=CmsCertificate, " + dn, "", extendedServiceKeySpec, keytype)); extendedcaservices.add(new HardTokenEncryptCAServiceInfo(ExtendedCAServiceInfo.STATUS_ACTIVE)); extendedcaservices.add(new KeyRecoveryCAServiceInfo(ExtendedCAServiceInfo.STATUS_ACTIVE)); cainfo = createX509CaInfo(dn, caname, certificateProfileId, validity, signedByCAId, caToken, policies, extendedcaservices); break; } getLogger().info("Creating CA..."); // Make an error control before starting do do something else. List<Certificate> cachain = null; if (cainfo.getSignedBy() == CAInfo.SIGNEDBYEXTERNALCA) { try { cachain = CertTools.getCertsFromPEM(extcachainName); } catch (CertificateException e) { log.error("Certificate file " + extcachainName + " did not contain a correct certificate."); return CommandResult.FUNCTIONAL_FAILURE; } if (cachain == null || cachain.isEmpty()) { log.error( extcachainName + " does not seem to exist or contain any certificates in PEM format."); return CommandResult.FUNCTIONAL_FAILURE; } } try { EjbRemoteHelper.INSTANCE.getRemoteSession(CAAdminSessionRemote.class) .createCA(getAuthenticationToken(), cainfo); } catch (CAExistsException e) { log.error("CA " + caname + " already exists."); return CommandResult.FUNCTIONAL_FAILURE; } catch (InvalidAlgorithmException e) { log.error("Algirithm was not valid: " + e.getMessage()); return CommandResult.FUNCTIONAL_FAILURE; } try { if (StringUtils.equalsIgnoreCase(explicitEcc, "true")) { getLogger().info( "Not re-reading CAInfo, since explicit ECC parameters were used, which is not serializable on Java 6. Use Web GUI for further interactions."); } else { CAInfo newInfo; newInfo = EjbRemoteHelper.INSTANCE.getRemoteSession(CaSessionRemote.class) .getCAInfo(getAuthenticationToken(), caname); int caid = newInfo.getCAId(); getLogger().info("CAId for created CA: " + caid); } if (cainfo.getSignedBy() == CAInfo.SIGNEDBYEXTERNALCA) { getLogger().info("Creating a CA signed by an external CA, creating certificate request."); CAInfo info = EjbRemoteHelper.INSTANCE.getRemoteSession(CaSessionRemote.class) .getCAInfo(getAuthenticationToken(), caname); if (info.getStatus() != CAConstants.CA_WAITING_CERTIFICATE_RESPONSE) { log.error( "Creating a CA signed by an external CA should result in CA having status, CA_WAITING_CERTIFICATE_RESPONSE. Terminating process, please troubleshoot."); return CommandResult.FUNCTIONAL_FAILURE; } byte[] request; try { request = EjbRemoteHelper.INSTANCE.getRemoteSession(CAAdminSessionRemote.class).makeRequest( getAuthenticationToken(), info.getCAId(), cachain, info.getCAToken().getAliasFromPurpose(CATokenConstants.CAKEYPURPOSE_CERTSIGN)); } catch (CertPathValidatorException e) { log.error("Error creating certificate request for CA:" + e.getMessage()); return CommandResult.FUNCTIONAL_FAILURE; } final String filename = info.getName() + "_csr.der"; FileOutputStream fos = new FileOutputStream(filename); fos.write(request); fos.close(); getLogger().info( "Created CSR for CA, to be sent to external CA. Wrote CSR to file '" + filename + "'."); } else { getLogger().info("Created and published initial CRL."); } } catch (CADoesntExistsException e) { throw new IllegalStateException("Newly created CA does not exist.", e); } getLogger().info("CA initialized"); getLogger().info("Note that any open browser sessions must be restarted to interact with this CA."); } catch (AuthorizationDeniedException e) { log.error("Current CLI user not authorized to create CA: " + e.getMessage()); return CommandResult.AUTHORIZATION_FAILURE; } catch (CryptoTokenOfflineException e) { log.error("Crypto token was unavailable: " + e.getMessage()); return CommandResult.FUNCTIONAL_FAILURE; } catch (IOException e) { throw new IllegalStateException("Unknown IOException was caught.", e); } return CommandResult.SUCCESS; }