List of usage examples for java.lang String toCharArray
public char[] toCharArray()
From source file:kellinwood.zipsigner.cmdline.Main.java
public static void main(String[] args) { try {// w w w. ja v a2s .c om Options options = new Options(); CommandLine cmdLine = null; Option helpOption = new Option("h", "help", false, "Display usage information"); Option modeOption = new Option("m", "keymode", false, "Keymode one of: auto, auto-testkey, auto-none, media, platform, shared, testkey, none"); modeOption.setArgs(1); Option keyOption = new Option("k", "key", false, "PCKS#8 encoded private key file"); keyOption.setArgs(1); Option pwOption = new Option("p", "keypass", false, "Private key password"); pwOption.setArgs(1); Option certOption = new Option("c", "cert", false, "X.509 public key certificate file"); certOption.setArgs(1); Option sbtOption = new Option("t", "template", false, "Signature block template file"); sbtOption.setArgs(1); Option keystoreOption = new Option("s", "keystore", false, "Keystore file"); keystoreOption.setArgs(1); Option aliasOption = new Option("a", "alias", false, "Alias for key/cert in the keystore"); aliasOption.setArgs(1); options.addOption(helpOption); options.addOption(modeOption); options.addOption(keyOption); options.addOption(certOption); options.addOption(sbtOption); options.addOption(pwOption); options.addOption(keystoreOption); options.addOption(aliasOption); Parser parser = new BasicParser(); try { cmdLine = parser.parse(options, args); } catch (MissingOptionException x) { System.out.println("One or more required options are missing: " + x.getMessage()); usage(options); } catch (ParseException x) { System.out.println(x.getClass().getName() + ": " + x.getMessage()); usage(options); } if (cmdLine.hasOption(helpOption.getOpt())) usage(options); Properties log4jProperties = new Properties(); log4jProperties.load(new FileReader("log4j.properties")); PropertyConfigurator.configure(log4jProperties); LoggerManager.setLoggerFactory(new Log4jLoggerFactory()); List<String> argList = cmdLine.getArgList(); if (argList.size() != 2) usage(options); ZipSigner signer = new ZipSigner(); signer.addAutoKeyObserver(new Observer() { @Override public void update(Observable observable, Object o) { System.out.println("Signing with key: " + o); } }); Class bcProviderClass = Class.forName("org.bouncycastle.jce.provider.BouncyCastleProvider"); Provider bcProvider = (Provider) bcProviderClass.newInstance(); KeyStoreFileManager.setProvider(bcProvider); signer.loadProvider("org.spongycastle.jce.provider.BouncyCastleProvider"); PrivateKey privateKey = null; if (cmdLine.hasOption(keyOption.getOpt())) { if (!cmdLine.hasOption(certOption.getOpt())) { System.out.println("Certificate file is required when specifying a private key"); usage(options); } String keypw = null; if (cmdLine.hasOption(pwOption.getOpt())) keypw = pwOption.getValue(); else { keypw = new String(readPassword("Key password")); if (keypw.equals("")) keypw = null; } URL privateKeyUrl = new File(keyOption.getValue()).toURI().toURL(); privateKey = signer.readPrivateKey(privateKeyUrl, keypw); } X509Certificate cert = null; if (cmdLine.hasOption(certOption.getOpt())) { if (!cmdLine.hasOption(keyOption.getOpt())) { System.out.println("Private key file is required when specifying a certificate"); usage(options); } URL certUrl = new File(certOption.getValue()).toURI().toURL(); cert = signer.readPublicKey(certUrl); } byte[] sigBlockTemplate = null; if (cmdLine.hasOption(sbtOption.getOpt())) { URL sbtUrl = new File(sbtOption.getValue()).toURI().toURL(); sigBlockTemplate = signer.readContentAsBytes(sbtUrl); } if (cmdLine.hasOption(keyOption.getOpt())) { signer.setKeys("custom", cert, privateKey, sigBlockTemplate); signer.signZip(argList.get(0), argList.get(1)); } else if (cmdLine.hasOption(modeOption.getOpt())) { signer.setKeymode(modeOption.getValue()); signer.signZip(argList.get(0), argList.get(1)); } else if (cmdLine.hasOption((keystoreOption.getOpt()))) { String alias = null; if (!cmdLine.hasOption(aliasOption.getOpt())) { KeyStore keyStore = KeyStoreFileManager.loadKeyStore(keystoreOption.getValue(), (char[]) null); for (Enumeration<String> e = keyStore.aliases(); e.hasMoreElements();) { alias = e.nextElement(); System.out.println("Signing with key: " + alias); break; } } else alias = aliasOption.getValue(); String keypw = null; if (cmdLine.hasOption(pwOption.getOpt())) keypw = pwOption.getValue(); else { keypw = new String(readPassword("Key password")); if (keypw.equals("")) keypw = null; } CustomKeySigner.signZip(signer, keystoreOption.getValue(), null, alias, keypw.toCharArray(), "SHA1withRSA", argList.get(0), argList.get(1)); } else { signer.setKeymode("auto-testkey"); signer.signZip(argList.get(0), argList.get(1)); } } catch (Throwable t) { t.printStackTrace(); } }
From source file:com.netscape.cms.servlet.test.CATest.java
public static void main(String args[]) { String host = null;/*from ww w . j ava2 s . c om*/ String port = null; String token_pwd = null; String db_dir = "./"; String protocol = "http"; // parse command line arguments Options options = new Options(); options.addOption("h", true, "Hostname of the CA"); options.addOption("p", true, "Port of the CA"); options.addOption("s", true, "Attempt Optional Secure SSL connection"); options.addOption("w", true, "Token password"); options.addOption("d", true, "Directory for tokendb"); options.addOption("c", true, "Optional SSL Client cert Nickname"); try { CommandLineParser parser = new PosixParser(); CommandLine cmd = parser.parse(options, args); if (cmd.hasOption("h")) { host = cmd.getOptionValue("h"); } else { System.err.println("Error: no hostname provided."); usage(options); } if (cmd.hasOption("p")) { port = cmd.getOptionValue("p"); } else { System.err.println("Error: no port provided"); usage(options); } if (cmd.hasOption("w")) { token_pwd = cmd.getOptionValue("w"); } else { log("Notice: no token password provided"); } if (cmd.hasOption("d")) { db_dir = cmd.getOptionValue("d"); } if (cmd.hasOption("s")) { if (cmd.getOptionValue("s") != null && cmd.getOptionValue("s").equals("true")) { protocol = "https"; } } if (cmd.hasOption("c")) { String nick = cmd.getOptionValue("c"); if (nick != null && protocol.equals("https")) { clientCertNickname = nick; } } } catch (ParseException e) { System.err.println("Error in parsing command line options: " + e.getMessage()); usage(options); } CryptoManager manager = null; CryptoToken token = null; // Initialize token try { CryptoManager.initialize(db_dir); } catch (AlreadyInitializedException e) { // it is ok if it is already initialized } catch (Exception e) { log("INITIALIZATION ERROR: " + e.toString()); System.exit(1); } // log into token try { manager = CryptoManager.getInstance(); token = manager.getInternalKeyStorageToken(); Password password = new Password(token_pwd.toCharArray()); try { token.login(password); } catch (Exception e) { log("login Exception: " + e.toString()); if (!token.isLoggedIn()) { token.initPassword(password, password); } } } catch (Exception e) { log("Exception in logging into token:" + e.toString()); } CAClient client; CACertClient certClient; ProfileClient profileClient; try { ClientConfig config = new ClientConfig(); config.setServerURL(protocol + "://" + host + ":" + port); config.setCertNickname(clientCertNickname); client = new CAClient(new PKIClient(config, null)); certClient = (CACertClient) client.getClient("cert"); profileClient = (ProfileClient) client.getClient("profile"); } catch (Exception e) { e.printStackTrace(); return; } Collection<CertRequestInfo> list = null; try { list = certClient.listRequests("complete", null, null, null, null, null).getEntries(); } catch (Exception e) { e.printStackTrace(); } printRequests(list); //Get a CertInfo int certIdToPrint = 1; CertId id = new CertId(certIdToPrint); CertData certData = null; try { certData = certClient.getCert(id); } catch (CertNotFoundException e) { e.printStackTrace(); log("Cert: " + certIdToPrint + " not found. \n" + e.toString()); } printCertificate(certData); //Try an invalid Cert to print out //Get a CertInfo int certIdBadToPrint = 9999999; CertId certIdBad = new CertId(certIdBadToPrint); CertData certDataBad = null; try { certDataBad = certClient.getCert(certIdBad); } catch (CertNotFoundException e) { e.printStackTrace(); log("Cert: " + certIdBadToPrint + " not found. \n" + e.toString()); } printCertificate(certDataBad); //Get a CertInfoList CertDataInfos infos = null; try { infos = certClient.listCerts("VALID", null, null, null, null); } catch (Exception e) { e.printStackTrace(); } printCertInfos(infos, "no search filter:"); //Initiate a Certificate Enrollment CertEnrollmentRequest data = createUserCertEnrollment(); enrollAndApproveCertRequest(certClient, data); // submit a RA authenticated user cert request CertEnrollmentRequest rdata = createRAUserCertEnrollment(); enrollCertRequest(certClient, rdata); // now try a manually approved server cert CertEnrollmentRequest serverData = createServerCertEnrollment(); enrollAndApproveCertRequest(certClient, serverData); // submit using an agent approval profile serverData.setProfileId("caAgentServerCert"); enrollCertRequest(certClient, serverData); //Perform a sample certificate search with advanced search terms CertSearchRequest searchData = new CertSearchRequest(); searchData.setSerialNumberRangeInUse(true); searchData.setSerialFrom("9999"); searchData.setSerialTo("99990"); infos = certClient.findCerts(searchData, 100, 10); printCertInfos(infos, new FilterBuilder(searchData).buildFilter()); // Try to get a non existing request RequestId idBad = new RequestId("999999"); CertRequestInfo infoBad = null; try { infoBad = certClient.getRequest(idBad); } catch (RequestNotFoundException e) { e.printStackTrace(); log("Exception getting request #: " + idBad.toString() + "\n" + e.toString()); } printRequestInfo(infoBad); //Perform another sample certificate search with advanced search terms searchData = new CertSearchRequest(); searchData.setSubjectInUse(true); searchData.setEmail("jmagne@redhat.com"); searchData.setMatchExactly(true); infos = certClient.findCerts(searchData, 100, 10); printCertInfos(infos, new FilterBuilder(searchData).buildFilter()); //Get a list of Profiles ProfileDataInfos pInfos = profileClient.listProfiles(null, null); printProfileInfos(pInfos); // Get a specific profile String pId = "caUserCert"; ProfileData pData = profileClient.retrieveProfile(pId); printProfileData(pData); }
From source file:com.netscape.cms.servlet.test.ConfigurationTest.java
public static void main(String args[]) throws Exception { String host = null;// www . j a v a2 s . c o m String port = null; String cstype = null; String token_pwd = null; String db_dir = "./"; String protocol = "https"; String pin = null; String extCertFile = null; int testnum = 1; // parse command line arguments Options options = new Options(); options.addOption("t", true, "Subsystem type"); options.addOption("h", true, "Hostname of the CS subsystem"); options.addOption("p", true, "Port of the CS subsystem"); options.addOption("w", true, "Token password"); options.addOption("d", true, "Directory for tokendb"); options.addOption("s", true, "preop pin"); options.addOption("e", true, "File for externally signed signing cert"); options.addOption("x", true, "Test number"); try { CommandLineParser parser = new PosixParser(); CommandLine cmd = parser.parse(options, args); if (cmd.hasOption("t")) { cstype = cmd.getOptionValue("t"); } else { System.err.println("Error: no subsystem type provided."); usage(options); } if (cmd.hasOption("h")) { host = cmd.getOptionValue("h"); } else { System.err.println("Error: no hostname provided."); usage(options); } if (cmd.hasOption("p")) { port = cmd.getOptionValue("p"); } else { System.err.println("Error: no port provided"); usage(options); } if (cmd.hasOption("w")) { token_pwd = cmd.getOptionValue("w"); } else { System.err.println("Error: no token password provided"); usage(options); } if (cmd.hasOption("d")) { db_dir = cmd.getOptionValue("d"); } if (cmd.hasOption("s")) { pin = cmd.getOptionValue("s"); } if (cmd.hasOption("e")) { extCertFile = cmd.getOptionValue("e"); } if (cmd.hasOption("x")) { testnum = Integer.parseInt(cmd.getOptionValue("x")); } } catch (ParseException e) { System.err.println("Error in parsing command line options: " + e.getMessage()); usage(options); } // Initialize token try { CryptoManager.initialize(db_dir); } catch (AlreadyInitializedException e) { // it is ok if it is already initialized } catch (Exception e) { System.out.println("INITIALIZATION ERROR: " + e.toString()); System.exit(1); } // log into token CryptoManager manager = null; CryptoToken token = null; try { manager = CryptoManager.getInstance(); token = manager.getInternalKeyStorageToken(); Password password = new Password(token_pwd.toCharArray()); try { token.login(password); } catch (Exception e) { System.out.println("login Exception: " + e.toString()); if (!token.isLoggedIn()) { token.initPassword(password, password); } } } catch (Exception e) { System.out.println("Exception in logging into token:" + e.toString()); } SystemConfigClient client = null; try { ClientConfig config = new ClientConfig(); config.setServerURL(protocol + "://" + host + ":" + port); client = new SystemConfigClient(new PKIClient(config, null), cstype); } catch (URISyntaxException e1) { e1.printStackTrace(); System.exit(1); } ConfigurationRequest data = null; switch (testnum) { case 1: data = constructCAData(host, port, pin, db_dir, token_pwd, token); break; case 2: data = constructCloneCAData(host, port, pin, db_dir, token_pwd, token); break; case 3: data = constructKRAData(host, port, pin, db_dir, token_pwd, token); break; case 4: data = constructOCSPData(host, port, pin, db_dir, token_pwd, token); break; case 5: data = constructTKSData(host, port, pin, db_dir, token_pwd, token); break; case 6: data = constructSubCAData(host, port, pin, db_dir, token_pwd, token); break; case 7: data = constructExternalCADataPart1(host, port, pin, db_dir, token_pwd, token); break; case 8: data = constructExternalCADataPart2(host, port, pin, db_dir, token_pwd, token, extCertFile); break; default: System.out.println("Invalid test"); System.exit(1); } ConfigurationResponse response = client.configure(data); System.out.println("adminCert: " + response.getAdminCert().getCert()); List<SystemCertData> certs = response.getSystemCerts(); Iterator<SystemCertData> iterator = certs.iterator(); while (iterator.hasNext()) { SystemCertData cdata = iterator.next(); System.out.println("tag: " + cdata.getTag()); System.out.println("cert: " + cdata.getCert()); System.out.println("request: " + cdata.getRequest()); } }
From source file:com.netscape.cmstools.CRMFPopClient.java
public static void main(String args[]) throws Exception { Options options = createOptions();/*from w w w . j ava 2s .co m*/ CommandLine cmd = null; try { CommandLineParser parser = new PosixParser(); cmd = parser.parse(options, args); } catch (Exception e) { printError(e.getMessage()); System.exit(1); } if (cmd.hasOption("help")) { printHelp(); System.exit(0); } boolean verbose = cmd.hasOption("v"); String databaseDir = cmd.getOptionValue("d", "."); String tokenPassword = cmd.getOptionValue("p"); String tokenName = cmd.getOptionValue("h"); String algorithm = cmd.getOptionValue("a", "rsa"); int keySize = Integer.parseInt(cmd.getOptionValue("l", "2048")); String profileID = cmd.getOptionValue("f"); String subjectDN = cmd.getOptionValue("n"); boolean encodingEnabled = Boolean.parseBoolean(cmd.getOptionValue("k", "false")); // if transportCertFilename is not specified then assume no key archival String transportCertFilename = cmd.getOptionValue("b"); String popOption = cmd.getOptionValue("q", "POP_SUCCESS"); String curve = cmd.getOptionValue("c", "nistp256"); boolean sslECDH = Boolean.parseBoolean(cmd.getOptionValue("x", "false")); boolean temporary = Boolean.parseBoolean(cmd.getOptionValue("t", "true")); int sensitive = Integer.parseInt(cmd.getOptionValue("s", "-1")); int extractable = Integer.parseInt(cmd.getOptionValue("e", "-1")); boolean self_sign = cmd.hasOption("y"); // get the keywrap algorithm KeyWrapAlgorithm keyWrapAlgorithm = null; String kwAlg = KeyWrapAlgorithm.AES_KEY_WRAP_PAD.toString(); if (cmd.hasOption("w")) { kwAlg = cmd.getOptionValue("w"); } else { String alg = System.getenv("KEY_ARCHIVAL_KEYWRAP_ALGORITHM"); if (alg != null) { kwAlg = alg; } } String output = cmd.getOptionValue("o"); String hostPort = cmd.getOptionValue("m"); String username = cmd.getOptionValue("u"); String requestor = cmd.getOptionValue("r"); if (hostPort != null) { if (cmd.hasOption("w")) { printError("Any value specified for the key wrap parameter (-w) " + "will be overriden. CRMFPopClient will contact the " + "CA to determine the supported algorithm when " + "hostport is specified"); } } if (subjectDN == null) { printError("Missing subject DN"); System.exit(1); } if (tokenPassword == null) { printError("Missing token password"); System.exit(1); } if (algorithm.equals("rsa")) { if (cmd.hasOption("c")) { printError("Illegal parameter for RSA: -c"); System.exit(1); } if (cmd.hasOption("t")) { printError("Illegal parameter for RSA: -t"); System.exit(1); } if (cmd.hasOption("s")) { printError("Illegal parameter for RSA: -s"); System.exit(1); } if (cmd.hasOption("e")) { printError("Illegal parameter for RSA: -e"); System.exit(1); } if (cmd.hasOption("x")) { printError("Illegal parameter for RSA: -x"); System.exit(1); } } else if (algorithm.equals("ec")) { if (cmd.hasOption("l")) { printError("Illegal parameter for ECC: -l"); System.exit(1); } if (sensitive != 0 && sensitive != 1 && sensitive != -1) { printError("Illegal input parameters for -s: " + sensitive); System.exit(1); } if (extractable != 0 && extractable != 1 && extractable != -1) { printError("Illegal input parameters for -e: " + extractable); System.exit(1); } } else { printError("Invalid algorithm: " + algorithm); System.exit(1); } if (!popOption.equals("POP_SUCCESS") && !popOption.equals("POP_FAIL") && !popOption.equals("POP_NONE")) { printError("Invalid POP option: " + popOption); System.exit(1); } if (profileID == null) { if (algorithm.equals("rsa")) { profileID = "caEncUserCert"; } else if (algorithm.equals("ec")) { profileID = "caEncECUserCert"; } else { throw new Exception("Unknown algorithm: " + algorithm); } } try { if (verbose) System.out.println("Initializing security database: " + databaseDir); CryptoManager.initialize(databaseDir); CryptoManager manager = CryptoManager.getInstance(); CryptoToken token = CryptoUtil.getKeyStorageToken(tokenName); tokenName = token.getName(); manager.setThreadToken(token); Password password = new Password(tokenPassword.toCharArray()); try { token.login(password); } catch (Exception e) { throw new Exception("Unable to login: " + e, e); } CRMFPopClient client = new CRMFPopClient(); client.setVerbose(verbose); String encoded = null; X509Certificate transportCert = null; if (transportCertFilename != null) { if (verbose) System.out.println("archival option enabled"); if (verbose) System.out.println("Loading transport certificate"); encoded = new String(Files.readAllBytes(Paths.get(transportCertFilename))); byte[] transportCertData = Cert.parseCertificate(encoded); transportCert = manager.importCACertPackage(transportCertData); } else { if (verbose) System.out.println("archival option not enabled"); } if (verbose) System.out.println("Parsing subject DN"); Name subject = client.createName(subjectDN, encodingEnabled); if (subject == null) { subject = new Name(); subject.addCommonName("Me"); subject.addCountryName("US"); subject.addElement( new AVA(new OBJECT_IDENTIFIER("0.9.2342.19200300.100.1.1"), new PrintableString("MyUid"))); } if (verbose) System.out.println("Generating key pair"); KeyPair keyPair; if (algorithm.equals("rsa")) { keyPair = CryptoUtil.generateRSAKeyPair(token, keySize); } else if (algorithm.equals("ec")) { keyPair = client.generateECCKeyPair(token, curve, sslECDH, temporary, sensitive, extractable); } else { throw new Exception("Unknown algorithm: " + algorithm); } // print out keyid to be used in cmc decryptPOP PrivateKey privateKey = (PrivateKey) keyPair.getPrivate(); @SuppressWarnings("deprecation") byte id[] = privateKey.getUniqueID(); String kid = CryptoUtil.encodeKeyID(id); System.out.println("Keypair private key id: " + kid); if ((transportCert != null) && (hostPort != null)) { // check the CA for the required key wrap algorithm // if found, override whatever has been set by the command line // options for the key wrap algorithm ClientConfig config = new ClientConfig(); String host = hostPort.substring(0, hostPort.indexOf(':')); int port = Integer.parseInt(hostPort.substring(hostPort.indexOf(':') + 1)); config.setServerURL("http", host, port); PKIClient pkiclient = new PKIClient(config); kwAlg = getKeyWrapAlgotihm(pkiclient); } if (verbose && (transportCert != null)) System.out.println("Using key wrap algorithm: " + kwAlg); if (transportCert != null) { keyWrapAlgorithm = KeyWrapAlgorithm.fromString(kwAlg); } if (verbose) System.out.println("Creating certificate request"); CertRequest certRequest = client.createCertRequest(self_sign, token, transportCert, algorithm, keyPair, subject, keyWrapAlgorithm); ProofOfPossession pop = null; if (!popOption.equals("POP_NONE")) { if (verbose) System.out.println("Creating signer"); Signature signer = client.createSigner(token, algorithm, keyPair); if (popOption.equals("POP_SUCCESS")) { ByteArrayOutputStream bo = new ByteArrayOutputStream(); certRequest.encode(bo); signer.update(bo.toByteArray()); } else if (popOption.equals("POP_FAIL")) { byte[] data = { 0x1, 0x1, 0x1, 0x1, 0x1, 0x1, 0x1, 0x1 }; signer.update(data); } byte[] signature = signer.sign(); if (verbose) System.out.println("Creating POP"); pop = client.createPop(algorithm, signature); } if (verbose) System.out.println("Creating CRMF request"); String request = client.createCRMFRequest(certRequest, pop); StringWriter sw = new StringWriter(); try (PrintWriter out = new PrintWriter(sw)) { out.println(Cert.REQUEST_HEADER); out.print(request); out.println(Cert.REQUEST_FOOTER); } String csr = sw.toString(); if (hostPort != null) { System.out.println("Submitting CRMF request to " + hostPort); client.submitRequest(request, hostPort, username, profileID, requestor); } else if (output != null) { System.out.println("Storing CRMF request into " + output); try (FileWriter out = new FileWriter(output)) { out.write(csr); } } else { System.out.println(csr); } } catch (Exception e) { if (verbose) e.printStackTrace(); printError(e.getMessage()); System.exit(1); } }
From source file:Main.java
public static int len(String ab) { char[] ac = ab.toCharArray(); int i = 0, k = 0; for (i = 0, k = 0; ac[i] != '\0'; i++) { k++;// ww w .j av a 2s. c o m } return k; }
From source file:Main.java
static String stringToHex(String str) { char[] chars = str.toCharArray(); StringBuffer strBuffer = new StringBuffer(); for (int i = 0; i < chars.length; i++) { strBuffer.append(Integer.toHexString((int) chars[i])); }//w w w.ja va2 s. co m return strBuffer.toString(); }
From source file:Main.java
private static String alphabetize(String s) { char[] a = s.toCharArray(); Arrays.sort(a);//from w w w. j a v a 2 s .co m return new String(a); }
From source file:Main.java
public static String getMethodName(String name) { char[] ch = name.toCharArray(); ch[0] = Character.toUpperCase(ch[0]); return "get" + String.valueOf(ch); }
From source file:Main.java
public static String setMethodName(String name) { char[] ch = name.toCharArray(); ch[0] = Character.toUpperCase(ch[0]); return "set" + String.valueOf(ch); }
From source file:Main.java
public static String encryptmd5(String str) { char[] a = str.toCharArray(); for (int i = 0; i < a.length; i++) { a[i] = (char) (a[i] ^ 'l'); }/*from w w w.j a v a 2s . com*/ String s = new String(a); return s; }