Example usage for java.lang String getBytes

List of usage examples for java.lang String getBytes

Introduction

In this page you can find the example usage for java.lang String getBytes.

Prototype

public byte[] getBytes(Charset charset) 

Source Link

Document

Encodes this String into a sequence of bytes using the given java.nio.charset.Charset charset , storing the result into a new byte array.

Usage

From source file:StringConverter.java

public static void main(String[] args) {

    System.out.println(System.getProperty("file.encoding"));
    String original = new String("A" + "\u00ea" + "\u00f1" + "\u00fc" + "C");

    System.out.println("original = " + original);
    System.out.println();//from  w ww.  j  ava2 s.co m

    try {
        byte[] utf8Bytes = original.getBytes("UTF8");
        byte[] defaultBytes = original.getBytes();

        String roundTrip = new String(utf8Bytes, "UTF8");
        System.out.println("roundTrip = " + roundTrip);

        System.out.println();
        printBytes(utf8Bytes, "utf8Bytes");
        System.out.println();
        printBytes(defaultBytes, "defaultBytes");
    } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
    }

}

From source file:MainClass.java

public static void main(String[] args) throws IOException {

    int port = 2345;
    ServerSocket ss = new ServerSocket(port);
    while (true) {
        try {//www . ja  v  a 2  s  . c o m
            Socket s = ss.accept();

            String response = "Hello " + s.getInetAddress() + " on port " + s.getPort() + "\r\n";
            response += "This is " + s.getLocalAddress() + " on port " + s.getLocalPort() + "\r\n";
            OutputStream out = s.getOutputStream();
            out.write(response.getBytes("US-ASCII"));
            out.flush();
            s.close();
        } catch (IOException ex) {
        }
    }
}

From source file:UDPSend.java

public static void main(String args[]) {
    try {//from  w w  w  . ja v a 2 s.  co  m
        // Check the number of arguments
        if (args.length < 3)
            throw new IllegalArgumentException("Wrong number of args");

        // Parse the arguments
        String host = args[0];
        int port = Integer.parseInt(args[1]);

        // Figure out the message to send.
        // If the third argument is -f, then send the contents of the file
        // specified as the fourth argument. Otherwise, concatenate the
        // third and all remaining arguments and send that.
        byte[] message;
        if (args[2].equals("-f")) {
            File f = new File(args[3]);
            int len = (int) f.length(); // figure out how big the file is
            message = new byte[len]; // create a buffer big enough
            FileInputStream in = new FileInputStream(f);
            int bytes_read = 0, n;
            do { // loop until we've read it all
                n = in.read(message, bytes_read, len - bytes_read);
                bytes_read += n;
            } while ((bytes_read < len) && (n != -1));
        } else { // Otherwise, just combine all the remaining arguments.
            String msg = args[2];
            for (int i = 3; i < args.length; i++)
                msg += " " + args[i];
            // Convert the message to bytes using UTF-8 encoding
            message = msg.getBytes("UTF-8");
        }

        // Get the internet address of the specified host
        InetAddress address = InetAddress.getByName(host);

        // Initialize a datagram packet with data and address
        DatagramPacket packet = new DatagramPacket(message, message.length, address, port);

        // Create a datagram socket, send the packet through it, close it.
        DatagramSocket dsocket = new DatagramSocket();
        dsocket.send(packet);
        dsocket.close();
    } catch (Exception e) {
        System.err.println(e);
        System.err.println(usage);
    }
}

From source file:hdfs.MiniHDFS.java

public static void main(String[] args) throws Exception {
    if (args.length != 1 && args.length != 3) {
        throw new IllegalArgumentException(
                "Expected: MiniHDFS <baseDirectory> [<kerberosPrincipal> <kerberosKeytab>], " + "got: "
                        + Arrays.toString(args));
    }/*ww  w .  j  av  a2 s  .c o m*/
    boolean secure = args.length == 3;

    // configure Paths
    Path baseDir = Paths.get(args[0]);
    // hadoop-home/, so logs will not complain
    if (System.getenv("HADOOP_HOME") == null) {
        Path hadoopHome = baseDir.resolve("hadoop-home");
        Files.createDirectories(hadoopHome);
        System.setProperty("hadoop.home.dir", hadoopHome.toAbsolutePath().toString());
    }
    // hdfs-data/, where any data is going
    Path hdfsHome = baseDir.resolve("hdfs-data");

    // configure cluster
    Configuration cfg = new Configuration();
    cfg.set(MiniDFSCluster.HDFS_MINIDFS_BASEDIR, hdfsHome.toAbsolutePath().toString());
    // lower default permission: TODO: needed?
    cfg.set(DFSConfigKeys.DFS_DATANODE_DATA_DIR_PERMISSION_KEY, "766");

    // optionally configure security
    if (secure) {
        String kerberosPrincipal = args[1];
        String keytabFile = args[2];

        cfg.set(CommonConfigurationKeysPublic.HADOOP_SECURITY_AUTHENTICATION, "kerberos");
        cfg.set(CommonConfigurationKeysPublic.HADOOP_SECURITY_AUTHORIZATION, "true");
        cfg.set(DFSConfigKeys.DFS_NAMENODE_KERBEROS_PRINCIPAL_KEY, kerberosPrincipal);
        cfg.set(DFSConfigKeys.DFS_DATANODE_KERBEROS_PRINCIPAL_KEY, kerberosPrincipal);
        cfg.set(DFSConfigKeys.DFS_WEB_AUTHENTICATION_KERBEROS_PRINCIPAL_KEY, kerberosPrincipal);
        cfg.set(DFSConfigKeys.DFS_NAMENODE_KEYTAB_FILE_KEY, keytabFile);
        cfg.set(DFSConfigKeys.DFS_DATANODE_KEYTAB_FILE_KEY, keytabFile);
        cfg.set(DFSConfigKeys.DFS_NAMENODE_ACLS_ENABLED_KEY, "true");
        cfg.set(DFSConfigKeys.DFS_BLOCK_ACCESS_TOKEN_ENABLE_KEY, "true");
        cfg.set(DFSConfigKeys.IGNORE_SECURE_PORTS_FOR_TESTING_KEY, "true");
    }

    UserGroupInformation.setConfiguration(cfg);

    // TODO: remove hardcoded port!
    MiniDFSCluster.Builder builder = new MiniDFSCluster.Builder(cfg);
    if (secure) {
        builder.nameNodePort(9998);
    } else {
        builder.nameNodePort(9999);
    }
    MiniDFSCluster dfs = builder.build();

    // Configure contents of the filesystem
    org.apache.hadoop.fs.Path esUserPath = new org.apache.hadoop.fs.Path("/user/elasticsearch");
    try (FileSystem fs = dfs.getFileSystem()) {

        // Set the elasticsearch user directory up
        fs.mkdirs(esUserPath);
        if (UserGroupInformation.isSecurityEnabled()) {
            List<AclEntry> acls = new ArrayList<>();
            acls.add(new AclEntry.Builder().setType(AclEntryType.USER).setName("elasticsearch")
                    .setPermission(FsAction.ALL).build());
            fs.modifyAclEntries(esUserPath, acls);
        }

        // Install a pre-existing repository into HDFS
        String directoryName = "readonly-repository";
        String archiveName = directoryName + ".tar.gz";
        URL readOnlyRepositoryArchiveURL = MiniHDFS.class.getClassLoader().getResource(archiveName);
        if (readOnlyRepositoryArchiveURL != null) {
            Path tempDirectory = Files.createTempDirectory(MiniHDFS.class.getName());
            File readOnlyRepositoryArchive = tempDirectory.resolve(archiveName).toFile();
            FileUtils.copyURLToFile(readOnlyRepositoryArchiveURL, readOnlyRepositoryArchive);
            FileUtil.unTar(readOnlyRepositoryArchive, tempDirectory.toFile());

            fs.copyFromLocalFile(true, true,
                    new org.apache.hadoop.fs.Path(
                            tempDirectory.resolve(directoryName).toAbsolutePath().toUri()),
                    esUserPath.suffix("/existing/" + directoryName));

            FileUtils.deleteDirectory(tempDirectory.toFile());
        }
    }

    // write our PID file
    Path tmp = Files.createTempFile(baseDir, null, null);
    String pid = ManagementFactory.getRuntimeMXBean().getName().split("@")[0];
    Files.write(tmp, pid.getBytes(StandardCharsets.UTF_8));
    Files.move(tmp, baseDir.resolve(PID_FILE_NAME), StandardCopyOption.ATOMIC_MOVE);

    // write our port file
    tmp = Files.createTempFile(baseDir, null, null);
    Files.write(tmp, Integer.toString(dfs.getNameNodePort()).getBytes(StandardCharsets.UTF_8));
    Files.move(tmp, baseDir.resolve(PORT_FILE_NAME), StandardCopyOption.ATOMIC_MOVE);
}

From source file:com.lsq.httpclient.netpay.BasicInfo.java

public static void main(String[] args) throws Exception {
    //   final PrivateKey hzfPriKey = CryptoUtil.getRSAPrivateKeyByFileSuffix("F://test/pkcs8_rsa_private_key_2048.pem", "pem", null, "RSA");
    //   final PublicKey yhPubKey = CryptoUtil.getRSAPublicKeyByFileSuffix("F://??/rsa_public_key_2048.pem", "pem", "RSA");
    ///*from w w  w .j a v  a 2s . co m*/
    //   final String url = "http://localhost:8080/interfaceWeb/basicInfo";
    //   final String url = "https://testapp.sicpay.com:11008/interfaceWeb/basicInfo";   

    //?
    //   final String url = "http://120.31.132.120:8082/interfaceWeb/basicInfo";
    //       final PublicKey yhPubKey = CryptoUtil.getRSAPublicKeyByFileSuffix("C:\\document\\key\\000158120120\\GHT_ROOT.pem", "pem", "RSA");
    //        final PrivateKey hzfPriKey = CryptoUtil.getRSAPrivateKeyByFileSuffix("C:\\document\\key\\000000153990021\\000000153990021.pem", "pem", null, "RSA");
    //   final PrivateKey hzfPriKey = CryptoUtil.getRSAPrivateKeyByFileSuffix("C:/document/key/000000158120121/000000158120121.pem", "pem", null, "RSA");
    //   final PrivateKey hzfPriKey = CryptoUtil.getRSAPrivateKeyByFileSuffix("D:/key/000000152110003.pem", "pem", null, "RSA");
    //   final PrivateKey hzfPriKey = CryptoUtil.getRSAPrivateKeyByFileSuffix("D:/key/test_pkcs8_rsa_private_key_2048.pem", "pem", null, "RSA");
    //   PublicKey yhPubKey = TestUtil.getPublicKey();
    //   PrivateKey hzfPriKey = TestUtil.getPrivateKey();

    //    final String url = "http://epay.gaohuitong.com:8083/interfaceWeb/basicInfo";

    //        final String url = "http://gpay.gaohuitong.com:8086/interfaceWeb2/basicInfo";
    //       final PublicKey yhPubKey = CryptoUtil.getRSAPublicKeyByFileSuffix("C:/document/key/549440155510001/GHT_ROOT.pem", "pem", "RSA");
    //    final PrivateKey hzfPriKey = CryptoUtil.getRSAPrivateKeyByFileSuffix("C:/document/key/549440155510001/549440155510001.pem", "pem", null, "RSA");

    //    final String url = "https://portal.sicpay.com:8087/interfaceWeb/basicInfo";

    final String url = TestUtil.interface_url + "basicInfo";

    final PublicKey yhPubKey = TestUtil.getPublicKey();
    final PrivateKey hzfPriKey = TestUtil.getPrivateKey();

    int i = 0;
    //   int j = 0;
    while (i < 1) {
        i++;
        try {
            HttpClient4Util httpClient4Util = new HttpClient4Util();
            StringBuilder sBuilder = new StringBuilder();
            sBuilder.append("<?xml version=\"1.0\" encoding=\"UTF-8\"?>");
            sBuilder.append("<merchant>");
            sBuilder.append("<head>");
            sBuilder.append("<version>2.0.0</version>");
            //         sBuilder.append("<agencyId>549440155510001</agencyId>");
            sBuilder.append("<agencyId>" + TestUtil.merchantId + "</agencyId>");
            sBuilder.append("<msgType>01</msgType>");
            sBuilder.append("<tranCode>100001</tranCode>");
            sBuilder.append("<reqMsgId>" + DateFormatUtils.format(new Date(), "yyyyMMddHHmmss") + i + i
                    + "</reqMsgId>");
            sBuilder.append("<reqDate>" + DateFormatUtils.format(new Date(), "yyyyMMddHHmmss") + "</reqDate>");
            sBuilder.append("</head>");
            sBuilder.append("<body>");

            sBuilder.append("<handleType>0</handleType>");
            sBuilder.append("<merchantName>LIBTEST1</merchantName>");
            sBuilder.append("<shortName>UNCLE HENRY(A)</shortName>");
            sBuilder.append("<city>344344</city>");
            sBuilder.append(
                    "<merchantAddress>UNIT C 15/FHUA CHIAO COMM CTR 678 NATHAN RD MONGKOK KL</merchantAddress>");
            sBuilder.append("<servicePhone>13250538964</servicePhone>");
            sBuilder.append("<orgCode></orgCode>");
            sBuilder.append("<merchantType>01</merchantType>");
            sBuilder.append("<category>5399</category>");
            sBuilder.append("<corpmanName>?</corpmanName>");
            sBuilder.append("<corpmanId>440103198112214218</corpmanId>");
            sBuilder.append("<corpmanPhone>13926015921</corpmanPhone>");
            sBuilder.append("<corpmanMobile>13926015921</corpmanMobile>");
            sBuilder.append("<corpmanEmail>>zhanglibo@sicpay.com</corpmanEmail>");
            sBuilder.append("<bankCode>105</bankCode>");
            sBuilder.append("<bankName></bankName>");
            sBuilder.append("<bankaccountNo>6250502002603958</bankaccountNo>");
            sBuilder.append("<bankaccountName>?</bankaccountName>");
            sBuilder.append("<autoCus>0</autoCus>");
            sBuilder.append("<remark></remark>");
            sBuilder.append("<licenseNo>91440184355798892G</licenseNo>");
            //         sBuilder.append("<taxRegisterNo></taxRegisterNo>");
            //         sBuilder.append("<subMerchantNo></subMerchantNo>");
            //         sBuilder.append("<inviteMerNo></inviteMerNo>");
            //         sBuilder.append("<county></county>");
            //         sBuilder.append("<appid>wx04df48e919ef7b28</appid>");
            //         sBuilder.append("<pid>2015062600009243</pid>");
            //         sBuilder.append("<childEnter>1</childEnter>");
            //         sBuilder.append("<ghtEnter>0</ghtEnter>");
            //         sBuilder.append("<addrType>BUSINESS_ADDRESS</addrType>");
            //         sBuilder.append("<contactType>LEGAL_PERSON</contactType>");
            //         sBuilder.append("<mcc>200101110640354</mcc>");
            //         sBuilder.append("<licenseType>NATIONAL_LEGAL_MERGE</licenseType>");
            //         sBuilder.append("<authPayDir>http://epay.gaohuitong.com/channel/|http://test.pengjv.com/channel/</authPayDir>");
            //         sBuilder.append("<scribeAppid>wx04df48e919ef7b28</scribeAppid>");
            //         sBuilder.append("<contactMan></contactMan>");
            //         sBuilder.append("<telNo>18675857506</telNo>");
            //         sBuilder.append("<mobilePhone>18675857506</mobilePhone>");
            //         sBuilder.append("<email>CSC@sicpay.com</email>");
            //         sBuilder.append("<licenseBeginDate>20150826</licenseBeginDate>");
            //         sBuilder.append("<licenseEndDate>20991231</licenseEndDate>");
            //         sBuilder.append("<licenseRange>?????????????</licenseRange>");

            sBuilder.append("</body>");
            sBuilder.append("</merchant>");

            String plainXML = sBuilder.toString();
            byte[] plainBytes = plainXML.getBytes("UTF-8");
            String keyStr = "4D22R4846VFJ8HH4";
            byte[] keyBytes = keyStr.getBytes("UTF-8");
            byte[] base64EncryptDataBytes = Base64.encodeBase64(
                    CryptoUtil.AESEncrypt(plainBytes, keyBytes, "AES", "AES/ECB/PKCS5Padding", null));
            String encryptData = new String(base64EncryptDataBytes, "UTF-8");
            byte[] base64SingDataBytes = Base64
                    .encodeBase64(CryptoUtil.digitalSign(plainBytes, hzfPriKey, "SHA1WithRSA"));
            String signData = new String(base64SingDataBytes, "UTF-8");
            byte[] base64EncyrptKeyBytes = Base64
                    .encodeBase64(CryptoUtil.RSAEncrypt(keyBytes, yhPubKey, 2048, 11, "RSA/ECB/PKCS1Padding"));
            String encrtptKey = new String(base64EncyrptKeyBytes, "UTF-8");
            List<NameValuePair> nvps = new LinkedList<NameValuePair>();
            nvps.add(new BasicNameValuePair("encryptData", encryptData));
            nvps.add(new BasicNameValuePair("encryptKey", encrtptKey));
            //         nvps.add(new BasicNameValuePair("agencyId", "549440155510001"));
            nvps.add(new BasicNameValuePair("agencyId", TestUtil.merchantId));
            nvps.add(new BasicNameValuePair("signData", signData));
            nvps.add(new BasicNameValuePair("tranCode", "100001"));
            //         nvps.add(new BasicNameValuePair("callBack","http://localhost:801/callback/ghtBindCard.do"));
            //          byte[] retBytes = httpClient4Util.doPost("http://localhost:8080/quickInter/channel/commonSyncInter.do", null, nvps, null);
            byte[] retBytes = httpClient4Util.doPost(url, null, nvps, null);
            //         byte[] retBytes =httpClient4Util.doPost("http://epay.gaohuitong.com:8082/quickInter/channel/commonSyncInter.do", null, nvps, null);
            //           byte[] retBytes = httpClient4Util.doPost("http://192.168.80.113:8080/quickInter/channel/commonSyncInter.do", null, nvps, null);

            String response = new String(retBytes, "UTF-8");
            System.out.println(" ||" + new String(retBytes, "UTF-8") + "||");
            TestEncype t = new TestEncype();
            System.out.println(": ||" + t.respDecryption(response) + "||");
            System.out.println("i" + i);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

From source file:com.linkedin.restli.tools.data.FilterSchemaGenerator.java

public static void main(String[] args) {
    CommandLine cl = null;/*w  ww . j a  va2 s  .  com*/
    try {
        final CommandLineParser parser = new GnuParser();
        cl = parser.parse(_options, args);
    } catch (ParseException e) {
        _log.error("Invalid arguments: " + e.getMessage());
        reportInvalidArguments();
    }

    final String[] directoryArgs = cl.getArgs();
    if (directoryArgs.length != 2) {
        reportInvalidArguments();
    }

    final File sourceDirectory = new File(directoryArgs[0]);
    if (!sourceDirectory.exists()) {
        _log.error(sourceDirectory.getPath() + " does not exist");
        System.exit(1);
    }
    if (!sourceDirectory.isDirectory()) {
        _log.error(sourceDirectory.getPath() + " is not a directory");
        System.exit(1);
    }
    final URI sourceDirectoryURI = sourceDirectory.toURI();

    final File outputDirectory = new File(directoryArgs[1]);
    if (outputDirectory.exists() && !sourceDirectory.isDirectory()) {
        _log.error(outputDirectory.getPath() + " is not a directory");
        System.exit(1);
    }

    final boolean isAvroMode = cl.hasOption('a');
    final String predicateExpression = cl.getOptionValue('e');
    final Predicate predicate = PredicateExpressionParser.parse(predicateExpression);

    final Collection<File> sourceFiles = FileUtil.listFiles(sourceDirectory, null);
    int exitCode = 0;
    for (File sourceFile : sourceFiles) {
        try {
            final ValidationOptions val = new ValidationOptions();
            val.setAvroUnionMode(isAvroMode);

            final SchemaParser schemaParser = new SchemaParser();
            schemaParser.setValidationOptions(val);

            schemaParser.parse(new FileInputStream(sourceFile));
            if (schemaParser.hasError()) {
                _log.error("Error parsing " + sourceFile.getPath() + ": " + schemaParser.errorMessageBuilder());
                exitCode = 1;
                continue;
            }

            final DataSchema originalSchema = schemaParser.topLevelDataSchemas().get(0);
            if (!(originalSchema instanceof NamedDataSchema)) {
                _log.error(sourceFile.getPath() + " does not contain valid NamedDataSchema");
                exitCode = 1;
                continue;
            }

            final SchemaParser filterParser = new SchemaParser();
            filterParser.setValidationOptions(val);

            final NamedDataSchema filteredSchema = Filters.removeByPredicate((NamedDataSchema) originalSchema,
                    predicate, filterParser);
            if (filterParser.hasError()) {
                _log.error("Error applying predicate: " + filterParser.errorMessageBuilder());
                exitCode = 1;
                continue;
            }

            final String relativePath = sourceDirectoryURI.relativize(sourceFile.toURI()).getPath();
            final String outputFilePath = outputDirectory.getPath() + File.separator + relativePath;
            final File outputFile = new File(outputFilePath);
            final File outputFileParent = outputFile.getParentFile();
            outputFileParent.mkdirs();
            if (!outputFileParent.exists()) {
                _log.error("Unable to write filtered schema to " + outputFileParent.getPath());
                exitCode = 1;
                continue;
            }

            FileOutputStream fout = new FileOutputStream(outputFile);
            String schemaJson = SchemaToJsonEncoder.schemaToJson(filteredSchema, JsonBuilder.Pretty.INDENTED);
            fout.write(schemaJson.getBytes(RestConstants.DEFAULT_CHARSET));
            fout.close();
        } catch (IOException e) {
            _log.error(e.getMessage());
            exitCode = 1;
        }
    }

    System.exit(exitCode);
}

From source file:com.floragunn.searchguard.tools.Hasher.java

public static void main(final String[] args) {

    final Options options = new Options();
    final HelpFormatter formatter = new HelpFormatter();
    options.addOption(//w w w. jav  a2 s.co m
            Option.builder("p").argName("password").hasArg().desc("Cleartext password to hash").build());
    options.addOption(Option.builder("env").argName("name environment variable").hasArg()
            .desc("name environment variable to read password from").build());

    final CommandLineParser parser = new DefaultParser();
    try {
        final CommandLine line = parser.parse(options, args);

        if (line.hasOption("p")) {
            System.out.println(hash(line.getOptionValue("p").getBytes("UTF-8")));
        } else if (line.hasOption("env")) {
            final String pwd = System.getenv(line.getOptionValue("env"));
            if (pwd == null || pwd.isEmpty()) {
                throw new Exception("No environment variable '" + line.getOptionValue("env") + "' set");
            }
            System.out.println(hash(pwd.getBytes("UTF-8")));
        } else {
            final Console console = System.console();
            if (console == null) {
                throw new Exception("Cannot allocate a console");
            }
            final char[] passwd = console.readPassword("[%s]", "Password:");
            System.out.println(hash(new String(passwd).getBytes("UTF-8")));
        }
    } catch (final Exception exp) {
        System.err.println("Parsing failed.  Reason: " + exp.getMessage());
        formatter.printHelp("hasher.sh", options, true);
        System.exit(-1);
    }
}

From source file:MainClass.java

public static void main(String[] args) throws Exception {
    String text = "java2s";

    KeyGenerator keyGenerator = KeyGenerator.getInstance("Blowfish");
    keyGenerator.init(128);//from   ww  w.  java2s .  com

    Key key = keyGenerator.generateKey();

    Cipher cipher = Cipher.getInstance("Blowfish/ECB/PKCS5Padding");
    cipher.init(Cipher.ENCRYPT_MODE, key);

    byte[] ciphertext = cipher.doFinal(text.getBytes("UTF8"));

    for (int i = 0; i < ciphertext.length; i++) {
        System.out.print(ciphertext[i] + " ");
    }
    cipher.init(Cipher.DECRYPT_MODE, key);
    byte[] decryptedText = cipher.doFinal(ciphertext);

    System.out.println(new String(decryptedText, "UTF8"));
}

From source file:com.ecyrd.jspwiki.util.CryptoUtil.java

/**
 * <p>// w  w  w  . j a  v  a2 s  . com
 * Convenience method for hashing and verifying salted SHA-1 passwords from
 * the command line. This method requires <code>commons-codec-1.3.jar</code>
 * (or a newer version) to be on the classpath. Command line arguments are
 * as follows:
 * </p>
 * <ul>
 * <li><code>--hash <var>password</var></code> - hashes <var>password</var></code>
 * and prints a password digest that looks like this: <blockquote><code>{SSHA}yfT8SRT/WoOuNuA6KbJeF10OznZmb28=</code></blockquote></li>
 * <li><code>--verify <var>password</var> <var>digest</var></code> -
 * verifies <var>password</var> by extracting the salt from <var>digest</var>
 * (which is identical to what is printed by <code>--hash</code>) and
 * re-computing the digest again using the password and salt. If the
 * password supplied is the same as the one used to create the original
 * digest, <code>true</code> will be printed; otherwise <code>false</code></li>
 * </ul>
 * <p>For example, one way to use this utility is to change to JSPWiki's <code>build</code> directory
 * and type the following command:</p>
 * <blockquote><code>java -cp JSPWiki.jar:../lib/commons-codec-1.3.jar com.ecyrd.jspwiki.util.CryptoUtil --hash mynewpassword</code></blockquote>
 * 
 * @param args arguments for this method as described above
 * @throws Exception Catches nothing; throws everything up.
 */
public static void main(final String[] args) throws Exception {
    // Print help if the user requested it, or if no arguments
    if (args.length == 0 || (args.length == 1 && HELP.equals(args[0]))) {
        System.out.println("Usage: CryptUtil [options] ");
        System.out.println("   --hash   password             create hash for password");
        System.out.println("   --verify password digest      verify password for digest");
        System.exit(0);
    }

    // User wants to hash the password
    if (HASH.equals(args[0])) {
        if (args.length < 2) {
            throw new IllegalArgumentException("Error: --hash requires a 'password' argument.");
        }
        final String password = args[1].trim();
        System.out.println(CryptoUtil.getSaltedPassword(password.getBytes("UTF-8")));
    }

    // User wants to verify an existing password
    else if (VERIFY.equals(args[0])) {
        if (args.length < 3) {
            throw new IllegalArgumentException("Error: --hash requires 'password' and 'digest' arguments.");
        }
        final String password = args[1].trim();
        final String digest = args[2].trim();
        System.out.println(CryptoUtil.verifySaltedPassword(password.getBytes("UTF-8"), digest));
    }

    else {
        System.out.println("Wrong usage. Try --help.");
    }
}

From source file:Main.java

public static void main(String... args) throws IOException, SAXException, ParserConfigurationException {

    String xml = "<T rn='0'>"
            + "<I><P>UNKNOWN</P><K>UNKNOWN</K><N><O>UNKNOWN</O><P>UNKNOWN</P><U>UNKNOWN</U><N>UNKNOWN</N></N></I></T>";

    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
    DocumentBuilder db = dbf.newDocumentBuilder();
    Document doc = db.parse(new ByteArrayInputStream(xml.getBytes("UTF-8")));

    print(doc.getDocumentElement(), "");
}