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() 

Source Link

Document

Encodes this String into a sequence of bytes using the platform's default charset, storing the result into a new byte array.

Usage

From source file:MainClass.java

public static void main(String[] args) {

    String phrase = new String("www.java2s.com API \n");
    File aFile = new File("test.txt");

    FileOutputStream file = null;
    try {// w  w w.j  av a  2  s.  co m
        file = new FileOutputStream(aFile, true);
    } catch (FileNotFoundException e) {
        e.printStackTrace(System.err);
    }
    FileChannel outChannel = file.getChannel();
    ByteBuffer buf = ByteBuffer.allocate(phrase.length());
    byte[] bytes = phrase.getBytes();
    buf.put(bytes);
    buf.flip();

    try {
        outChannel.write(buf);
        file.close();
    } catch (IOException e) {
        e.printStackTrace(System.err);
    }
}

From source file:com.threerings.getdown.tools.AppletParamSigner.java

public static void main(String[] args) {
    try {//from www . j a va 2 s. c  o m
        if (args.length != 7) {
            System.err
                    .println("AppletParamSigner keystore storepass alias keypass " + "appbase appname imgpath");
            System.exit(255);
        }

        String keystore = args[0];
        String storepass = args[1];
        String alias = args[2];
        String keypass = args[3];
        String appbase = args[4];
        String appname = args[5];
        String imgpath = args[6];
        String params = appbase + appname + imgpath;

        KeyStore store = KeyStore.getInstance("JKS");
        store.load(new BufferedInputStream(new FileInputStream(keystore)), storepass.toCharArray());
        PrivateKey key = (PrivateKey) store.getKey(alias, keypass.toCharArray());
        Signature sig = Signature.getInstance("SHA1withRSA");
        sig.initSign(key);
        sig.update(params.getBytes());
        String signed = new String(Base64.encodeBase64(sig.sign()));
        System.out.println("<param name=\"appbase\" value=\"" + appbase + "\" />");
        System.out.println("<param name=\"appname\" value=\"" + appname + "\" />");
        System.out.println("<param name=\"bgimage\" value=\"" + imgpath + "\" />");
        System.out.println("<param name=\"signature\" value=\"" + signed + "\" />");

    } catch (Exception e) {
        System.err.println("Failed to produce signature.");
        e.printStackTrace();
    }
}

From source file:Main.java

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

    String xml = "<metadata><codes class = 'class1'>" + "<code code='ABC'>" + "<detail x='blah blah'/>"
            + "</code>" + "</codes>" + "<codes class = 'class2'>" + "<code code = '123'>"
            + "<detail x='blah blah'/></code></codes></metadata>";

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

    XPath xPath = XPathFactory.newInstance().newXPath();
    XPathExpression expr = xPath.compile("//codes/code[@code ='ABC']");
    Object result = expr.evaluate(doc, XPathConstants.NODESET);

    NodeList nodes = (NodeList) result;
    System.out.println(nodes.getLength() > 0 ? "Yes" : "No");
    for (int i = 0; i < nodes.getLength(); i++) {
        System.out.println("nodes: " + nodes.item(i).getNodeValue());
    }/*from   w ww  .ja  v  a  2 s. c o  m*/
}

From source file:MainClass.java

public static void main(String[] args) throws Exception {
    Security.addProvider(new org.bouncycastle.jce.provider.BouncyCastleProvider());

    SecureRandom random = new SecureRandom();
    IvParameterSpec ivSpec = createCtrIvForAES();
    Key key = createKeyForAES(256, random);
    Cipher cipher = Cipher.getInstance("AES/CTR/NoPadding", "BC");
    String input = "12345678";
    Mac mac = Mac.getInstance("DES", "BC");
    byte[] macKeyBytes = new byte[] { 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08 };
    Key macKey = new SecretKeySpec(macKeyBytes, "DES");

    cipher.init(Cipher.ENCRYPT_MODE, key, ivSpec);

    byte[] cipherText = new byte[cipher.getOutputSize(input.length() + mac.getMacLength())];

    int ctLength = cipher.update(input.getBytes(), 0, input.length(), cipherText, 0);

    mac.init(macKey);/*from  ww  w.  j a  v a2s  . c om*/
    mac.update(input.getBytes());

    ctLength += cipher.doFinal(mac.doFinal(), 0, mac.getMacLength(), cipherText, ctLength);

    cipher.init(Cipher.DECRYPT_MODE, key, ivSpec);

    byte[] plainText = cipher.doFinal(cipherText, 0, ctLength);
    int messageLength = plainText.length - mac.getMacLength();

    mac.init(macKey);
    mac.update(plainText, 0, messageLength);

    byte[] messageHash = new byte[mac.getMacLength()];
    System.arraycopy(plainText, messageLength, messageHash, 0, messageHash.length);

    System.out.println("plain : " + new String(plainText) + " verified: "
            + MessageDigest.isEqual(mac.doFinal(), messageHash));

}

From source file:hh.learnj.test.license.test.rsacoder.RSACoder.java

/**
 * @param args//w  ww . j a va  2 s. c  o m
 * @throws Exception
 */
public static void main(String[] args) throws Exception {
    // ?
    // ?
    Map<String, Object> keyMap = RSACoder.initKey();
    // 
    byte[] publicKey = RSACoder.getPublicKey(keyMap);

    // ?
    byte[] privateKey = RSACoder.getPrivateKey(keyMap);
    System.out.println("/n" + Base64.encodeBase64String(publicKey));
    System.out.println("?/n" + Base64.encodeBase64String(privateKey));

    System.out.println(
            "================,?=============");
    String str = "RSA??";
    System.out.println("/n===========????==============");
    System.out.println(":" + str);
    // ?
    byte[] code1 = RSACoder.encryptByPrivateKey(str.getBytes(), privateKey);
    System.out.println("??" + Base64.encodeBase64String(code1));
    System.out.println("===========???==============");
    // ?
    byte[] decode1 = RSACoder.decryptByPublicKey(code1, publicKey);
    System.out.println("??" + new String(decode1) + "/n/n");

    System.out.println("===========????????==============/n/n");

    str = "????RSA";

    System.out.println(":" + str);

    // ?
    byte[] code2 = RSACoder.encryptByPublicKey(str.getBytes(), publicKey);
    System.out.println("===========?==============");
    System.out.println("??" + Base64.encodeBase64String(code2));

    System.out.println("=============??======================");
    System.out.println("===========??==============");

    // ??
    byte[] decode2 = RSACoder.decryptByPrivateKey(code2, privateKey);

    System.out.println("??" + new String(decode2));
}

From source file:edu.ku.brc.helpers.Encryption.java

/** I am leaving this here for documentation purposes
 * @param args input from the command line
 * @throws Exception some error/*from  ww w .jav  a2s.  co m*/
 */
public static void main(final String[] args) throws Exception {
    /*
     * If we're configured to use a third-party cryptography provider, where that provider is
     * not permanently installed, then we need to install it first.
     */
    if (EXTRA_PROVIDER != null) {
        Provider prov = (Provider) Class.forName(EXTRA_PROVIDER).newInstance();
        Security.addProvider(prov);
    }

    /*
     * The Encryption() function above uses a byte[] as input, so it's more general (it can Encryption
     * anything, not just a String), as well as using a char[] for the password, because it can
     * be overwritten once it's finished. Strings are immutable, so to purge them from RAM you
     * have to hope they get garbage collected and then the RAM gets reused. For char[]s you can
     * simply fill up the array with junk to erase the password from RAM. Anyway, use char[] if
     * you're concerned about security, but for a test case, a String works fine.
     */
    /* Our input text and password. */
    String input = "Hello World!"; //$NON-NLS-1$
    String password = "abcd"; //$NON-NLS-1$

    byte[] inputBytes = input.getBytes();
    char[] passwordChars = password.toCharArray();

    /* Encrypt the data. */
    byte[] ciphertext = encrypt(inputBytes, passwordChars);

    System.out.println("Ciphertext:"); //$NON-NLS-1$

    /*
     * This is just a little loop I made up which displays the encrypted data in hexadecimal, 30
     * bytes to a line. Obviously, the ciphertext won't necessarily be a recognizable String,
     * and it'll probably have control characters and such in it. We don't even want to convert
     * it to a String, let alone display it onscreen. If you need text, investigate some kind of
     * encoding at this point on top of the encryption, like Base64. It's not that hard to
     * implement and it'll give you text to carry from place to place. Just remember to *de*code
     * the text before calling decrypt().
     */
    int i;
    for (i = 0; i < ciphertext.length; i++) {
        String s = Integer.toHexString(ciphertext[i] & 0xFF);
        if (s.length() == 1)
            s = "0" + s; //$NON-NLS-1$
        System.out.print(s);
        if (i % 30 == 29)
            System.out.println();
    }
    if ((ciphertext.length - 1) % 30 != 29)
        System.out.println();

    String hexText = makeHEXStr(ciphertext);
    System.out.println("To:   [" + hexText + "]"); //$NON-NLS-1$ //$NON-NLS-2$
    System.out.println("From: [" + reverseHEXStr(hexText) + "]****"); //$NON-NLS-1$ //$NON-NLS-2$

    /*
     * Now, decrypt the data. Note that all we need is the password and the ciphertext.
     */
    byte[] output = decrypt(ciphertext, passwordChars);

    /* Transform the output into a string. */
    String sOutput = new String(output);

    /* Display it. */
    System.out.println("Plaintext:\n" + sOutput); //$NON-NLS-1$
}

From source file:com.kyne.webby.rtk.web.Connection.java

public static void main(String args[]) throws UnsupportedEncodingException {
    final String s = "2012-07-07 20:17:21 [INFO] <*Console> H%C3%A9%C3%A9";
    System.out.println(s);//w  ww  .  jav  a  2 s . co m
    System.out.println(new String(s.getBytes(), "UTF-8"));
    System.out.println(URLDecoder.decode(s, "UTF-8"));
}

From source file:MainClass.java

public static void main(String[] args) throws Exception {
    Security.addProvider(new BouncyCastleProvider());
    SecureRandom random = new SecureRandom();
    IvParameterSpec ivSpec = createCtrIvForAES(1, random);
    Key key = createKeyForAES(256, random);
    Cipher cipher = Cipher.getInstance("AES/CTR/NoPadding", "BC");
    String input = "www.java2s.com";
    Mac mac = Mac.getInstance("DES", "BC");
    byte[] macKeyBytes = "12345678".getBytes();
    Key macKey = new SecretKeySpec(macKeyBytes, "DES");
    System.out.println("input : " + input);

    // encryption step
    cipher.init(Cipher.ENCRYPT_MODE, key, ivSpec);
    byte[] cipherText = new byte[cipher.getOutputSize(input.length() + mac.getMacLength())];
    int ctLength = cipher.update(input.getBytes(), 0, input.length(), cipherText, 0);
    mac.init(macKey);/*from w w w.j  a va 2 s.  co m*/
    mac.update(input.getBytes());
    ctLength += cipher.doFinal(mac.doFinal(), 0, mac.getMacLength(), cipherText, ctLength);
    System.out.println("cipherText : " + new String(cipherText));

    // decryption step
    cipher.init(Cipher.DECRYPT_MODE, key, ivSpec);
    byte[] plainText = cipher.doFinal(cipherText, 0, ctLength);
    int messageLength = plainText.length - mac.getMacLength();

    mac.init(macKey);
    mac.update(plainText, 0, messageLength);

    byte[] messageHash = new byte[mac.getMacLength()];
    System.arraycopy(plainText, messageLength, messageHash, 0, messageHash.length);

    System.out.println("plain : " + new String(plainText) + " verified: "
            + MessageDigest.isEqual(mac.doFinal(), messageHash));
}

From source file:fr.inria.edelweiss.kgdqp.core.CentralizedInferrencingNoSpin.java

public static void main(String args[])
        throws ParseException, EngineException, InterruptedException, IOException, LoadException {

    List<String> endpoints = new ArrayList<String>();
    String queryPath = null;/*from  w w w  .jav  a 2 s  .  c o m*/
    boolean rulesSelection = false;
    File rulesDir = null;
    File ontDir = null;

    /////////////////
    Graph graph = Graph.create();
    QueryProcess exec = QueryProcess.create(graph);

    Options options = new Options();
    Option helpOpt = new Option("h", "help", false, "print this message");
    //        Option queryOpt = new Option("q", "query", true, "specify the sparql query file");
    //        Option endpointOpt = new Option("e", "endpoint", true, "a federated sparql endpoint URL");
    Option versionOpt = new Option("v", "version", false, "print the version information and exit");
    Option rulesOpt = new Option("r", "rulesDir", true, "directory containing the inference rules");
    Option ontOpt = new Option("o", "ontologiesDir", true,
            "directory containing the ontologies for rules selection");
    //        Option locOpt = new Option("c", "centralized", false, "performs centralized inferences");
    Option dataOpt = new Option("l", "load", true, "data file or directory to be loaded");
    //        Option selOpt = new Option("s", "rulesSelection", false, "if set to true, only the applicable rules are run");
    //        options.addOption(queryOpt);
    //        options.addOption(endpointOpt);
    options.addOption(helpOpt);
    options.addOption(versionOpt);
    options.addOption(rulesOpt);
    options.addOption(ontOpt);
    //        options.addOption(selOpt);
    //        options.addOption(locOpt);
    options.addOption(dataOpt);

    String header = "Corese/KGRAM rule engine experiment command line interface";
    String footer = "\nPlease report any issue to alban.gaignard@cnrs.fr, olivier.corby@inria.fr";

    CommandLineParser parser = new BasicParser();
    CommandLine cmd = parser.parse(options, args);
    if (cmd.hasOption("h")) {
        HelpFormatter formatter = new HelpFormatter();
        formatter.printHelp("kgdqp", header, options, footer, true);
        System.exit(0);
    }
    if (cmd.hasOption("o")) {
        rulesSelection = true;
        String ontDirPath = cmd.getOptionValue("o");
        ontDir = new File(ontDirPath);
        if (!ontDir.isDirectory()) {
            logger.warn(ontDirPath + " is not a valid directory path.");
            System.exit(0);
        }
    }
    if (!cmd.hasOption("r")) {
        logger.info("You must specify a path for inference rules directory !");
        System.exit(0);
    }

    if (cmd.hasOption("l")) {
        String[] dataPaths = cmd.getOptionValues("l");
        for (String path : dataPaths) {
            Load ld = Load.create(graph);
            ld.load(path);
            logger.info("Loaded " + path);
        }
    }

    if (cmd.hasOption("v")) {
        logger.info("version 3.0.4-SNAPSHOT");
        System.exit(0);
    }

    String rulesDirPath = cmd.getOptionValue("r");
    rulesDir = new File(rulesDirPath);
    if (!rulesDir.isDirectory()) {
        logger.warn(rulesDirPath + " is not a valid directory path.");
        System.exit(0);
    }

    // Local rules graph initialization
    Graph rulesG = Graph.create();
    Load ld = Load.create(rulesG);

    if (rulesSelection) {
        // Ontology loading
        if (ontDir.isDirectory()) {
            for (File o : ontDir.listFiles()) {
                logger.info("Loading " + o.getAbsolutePath());
                ld.load(o.getAbsolutePath());
            }
        }
    }

    // Rules loading
    if (rulesDir.isDirectory()) {
        for (File r : rulesDir.listFiles()) {
            if (r.getAbsolutePath().endsWith(".rq")) {
                logger.info("Loading " + r.getAbsolutePath());
                //                ld.load(r.getAbsolutePath());

                //                    byte[] encoded = Files.readAllBytes(Paths.get(r.getAbsolutePath()));
                //                    String construct = new String(encoded, "UTF-8"); //StandardCharsets.UTF_8);

                FileInputStream f = new FileInputStream(r);
                QueryLoad ql = QueryLoad.create();
                String construct = ql.read(f);
                f.close();

                SPINProcess sp = SPINProcess.create();
                String spinConstruct = sp.toSpin(construct);

                ld.load(new ByteArrayInputStream(spinConstruct.getBytes()), Load.TURTLE_FORMAT);
                logger.info("Rules graph size : " + rulesG.size());

            }
        }
    }

    // Rule engine initialization
    RuleEngine ruleEngine = RuleEngine.create(graph);
    ruleEngine.set(exec);
    ruleEngine.setOptimize(true);
    ruleEngine.setConstructResult(true);
    ruleEngine.setTrace(true);

    StopWatch sw = new StopWatch();
    logger.info("Federated graph size : " + graph.size());
    logger.info("Rules graph size : " + rulesG.size());

    // Rule selection
    logger.info("Rules selection");
    QueryProcess localKgram = QueryProcess.create(rulesG);
    ArrayList<String> applicableRules = new ArrayList<String>();
    sw.start();
    String rulesSelQuery = "";
    if (rulesSelection) {
        rulesSelQuery = pertinentRulesQuery;
    } else {
        rulesSelQuery = allRulesQuery;
    }
    Mappings maps = localKgram.query(rulesSelQuery);
    logger.info("Rules selected in " + sw.getTime() + " ms");
    logger.info("Applicable rules : " + maps.size());

    // Selected rule loading
    for (Mapping map : maps) {
        IDatatype dt = (IDatatype) map.getValue("?res");
        String rule = dt.getLabel();
        //loading rule in the rule engine
        //            logger.info("Adding rule : ");
        //            System.out.println("-------");
        //            System.out.println(rule);
        //            System.out.println("");
        //            if (! rule.toLowerCase().contains("sameas")) {
        applicableRules.add(rule);
        ruleEngine.addRule(rule);
        //            }
    }

    // Rules application on distributed sparql endpoints
    logger.info("Rules application (" + applicableRules.size() + " rules)");
    ExecutorService threadPool = Executors.newCachedThreadPool();
    RuleEngineThread ruleThread = new RuleEngineThread(ruleEngine);
    sw.reset();
    sw.start();

    //        ruleEngine.process();
    threadPool.execute(ruleThread);
    threadPool.shutdown();

    //monitoring loop
    while (!threadPool.isTerminated()) {
        //            System.out.println("******************************");
        //            System.out.println(Util.jsonDqpCost(QueryProcessDQP.queryCounter, QueryProcessDQP.queryVolumeCounter, QueryProcessDQP.sourceCounter, QueryProcessDQP.sourceVolumeCounter));
        //            System.out.println("Rule engine running for " + sw.getTime() + " ms");
        //            System.out.println("Federated graph size : " + graph.size());
        System.out.println(sw.getTime() + " , " + graph.size());
        Thread.sleep(5000);
    }

    logger.info("Federated graph size : " + graph.size());
    //        logger.info(Util.jsonDqpCost(QueryProcessDQP.queryCounter, QueryProcessDQP.queryVolumeCounter, QueryProcessDQP.sourceCounter, QueryProcessDQP.sourceVolumeCounter));

    //        TripleFormat f = TripleFormat.create(graph, true);
    //        f.write("/tmp/gAll.ttl");
}

From source file:com.github.pierods.ramltoapidocconverter.RAMLToApidocConverter.java

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

    OptionParser optionParser = new OptionParser("h");

    optionParser.accepts("raml").withRequiredArg();
    optionParser.accepts("apidoc").withRequiredArg();
    optionParser.accepts("version");
    optionParser.accepts("help");

    OptionSet optionSet = optionParser.parse(args);

    if (optionSet.has("help") || optionSet.has("h")) {
        System.out.println("Usage: -raml uri of raml " + "-apidoc name of apidoc file /n" + "or /"
                + "-raml uri of raml -version");
        System.exit(0);//  w  ww.j av  a  2  s.  co  m
    }

    if (!optionSet.has("raml")) {
        System.out.println("Missing raml option");
        System.exit(-1);
    }

    URI uri = new URI((String) optionSet.valueOf("raml"));

    if (uri.getScheme() == null) {
        System.out.println("Bad raml uri - should be file:// or http:// ");
        System.exit(-1);
    }

    RAMLToApidocConverter instance = new RAMLToApidocConverter();

    if (optionSet.has("version")) {
        System.out.print(instance.getVersion((String) optionSet.valueOf("raml")));
        return;
    }

    String data = instance.convert((String) optionSet.valueOf("raml"));
    if (optionSet.has("apidoc")) {
        Files.write(Paths.get((String) optionSet.valueOf("apidoc")), data.getBytes());
    } else {
        System.out.print(data);
    }

}