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:BrokerFrame.java

/**
 * @param args the command line arguments
 *///from   w  ww. ja v  a2s  . c  o m
public static void main(String args[]) throws Exception {
    /* Set the Nimbus look and feel */
    //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
    /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
     * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
     */
    try {
        for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
            if ("Nimbus".equals(info.getName())) {
                javax.swing.UIManager.setLookAndFeel(info.getClassName());
                break;
            }
        }
    } catch (ClassNotFoundException ex) {
        java.util.logging.Logger.getLogger(BrokerFrame.class.getName()).log(java.util.logging.Level.SEVERE,
                null, ex);
    } catch (InstantiationException ex) {
        java.util.logging.Logger.getLogger(BrokerFrame.class.getName()).log(java.util.logging.Level.SEVERE,
                null, ex);
    } catch (IllegalAccessException ex) {
        java.util.logging.Logger.getLogger(BrokerFrame.class.getName()).log(java.util.logging.Level.SEVERE,
                null, ex);
    } catch (javax.swing.UnsupportedLookAndFeelException ex) {
        java.util.logging.Logger.getLogger(BrokerFrame.class.getName()).log(java.util.logging.Level.SEVERE,
                null, ex);
    }
    //</editor-fold>

    String ola = new String();
    ola = "olajjhgjhhjkhjkhjhkjhjhgg";

    RSA rs = new RSA();
    rs.generateKeys();
    System.out.println((RSA.privKey).toString());
    byte[] signature = rs.encrypt(ola, RSA.privKey);
    String sig = new Base64().encodeAsString(signature);
    byte[] byt = new Base64().decode(sig);
    System.out.println(sig);
    try {
        rs.verifySignature(ola.getBytes(), signature);
    } catch (Exception e) {
        throw new Exception(e);
    }
    /* Create and display the form */
    java.awt.EventQueue.invokeLater(new Runnable() {
        public void run() {
            new BrokerFrame().setVisible(true);
        }
    });
}

From source file:MainClass.java

public static void main(String[] args) {
    String phrase = new String("text\n");
    String dirname = "C:/test"; // Directory name
    String filename = "byteData.txt";
    File aFile = new File(dirname, filename);
    // Create the file output stream
    FileOutputStream file = null;
    try {//from ww w.java2  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:Main.java

public static void main(String[] args) throws Exception {
    String xml = "<root>" + "<ctc:BasePrice>" + "<cgc:PriceAmount currencyID='EUR'>18.75</cgc:PriceAmount>"
            + "<cgc:BaseQuantity quantityUnitCode='EA'>1</cgc:BaseQuantity>" + "</ctc:BasePrice>"
            + "<ctc:BasePrice>" + "<cgc:PriceAmount currencyID='EUR'>18.25</cgc:PriceAmount>"
            + "<cgc:BaseQuantity quantityUnitCode='EA'>1</cgc:BaseQuantity>"
            + "<cgc:MinimumQuantity quantityUnitCode='EA'>3</cgc:MinimumQuantity>" + "</ctc:BasePrice>"
            + "</root>";

    InputStream xmlStream = new ByteArrayInputStream(xml.getBytes());
    DocumentBuilderFactory builderFactory = DocumentBuilderFactory.newInstance();
    DocumentBuilder builder = builderFactory.newDocumentBuilder();
    Document xmlDocument = builder.parse(xmlStream);
    XPath xPath = XPathFactory.newInstance().newXPath();
    String expression = "//*[local-name() = 'BasePrice' and not(descendant::*[local-name() = 'MinimumQuantity'])]/*[local-name()='PriceAmount']";
    NodeList nodeList = (NodeList) xPath.compile(expression).evaluate(xmlDocument, XPathConstants.NODESET);
    for (int i = 0; i < nodeList.getLength(); i++) {
        System.out.println(nodeList.item(i).getFirstChild().getNodeValue());
    }// w  w  w  .j  ava 2s  .com
}

From source file:com.cfs.util.AESCriptografia.java

public static void main(String[] args) {
    AESCriptografia aes = new AESCriptografia();
    String msg = "Teste4";
    String key = "8TScvUZRTmS8V6hd/cZt/A==";

    try {//from  ww  w. j a v a2  s .  co m
        System.out.println("                 AES - " + aes.testeCifrar(msg, key));
        String teste = "AES/ECB/PKCS5PADDING";
        Cipher cipher = Cipher.getInstance(teste);
        cipher.init(Cipher.ENCRYPT_MODE, aes.gerarChave(key));
        byte[] original = msg.getBytes();
        byte[] cifrada = cipher.doFinal(original);
        byte[] retorno = Base64.encodeBase64(cifrada);

        System.out.println(teste + " - " + new String(retorno));
    } catch (Exception e) {
        System.out.println(Utilities.getInstance().getLineNumber() + e.getLocalizedMessage());
    }
}

From source file:ee.ria.xroad.common.signature.BatchSignerIntegrationTest.java

/**
 * Main program entry point./*from  www. j a  v a2 s  .co  m*/
 * @param args command-line arguments
 * @throws Exception in case of any errors
 */
public static void main(String[] args) throws Exception {
    if (args.length == 0) {
        printUsage();

        return;
    }

    ActorSystem actorSystem = ActorSystem.create("Proxy", ConfigFactory.load().getConfig("proxy"));
    SignerClient.init(actorSystem);

    Thread.sleep(SIGNER_INIT_DELAY); // wait for signer client to connect

    BatchSigner.init(actorSystem);

    X509Certificate subjectCert = TestCertUtil.getConsumer().cert;
    X509Certificate issuerCert = TestCertUtil.getCaCert();
    X509Certificate signerCert = TestCertUtil.getOcspSigner().cert;
    PrivateKey signerKey = TestCertUtil.getOcspSigner().key;

    List<String> messages = new ArrayList<>();

    for (String arg : args) {
        messages.add(FileUtils.readFileToString(new File(arg)));
    }

    latch = new CountDownLatch(messages.size());

    Date thisUpdate = new DateTime().plusDays(1).toDate();
    final OCSPResp ocsp = OcspTestUtils.createOCSPResponse(subjectCert, issuerCert, signerCert, signerKey,
            CertificateStatus.GOOD, thisUpdate, null);

    for (final String message : messages) {
        new Thread(() -> {
            try {
                byte[] hash = hash(message);
                log.info("File: {}, hash: {}", message, hash);

                MessagePart hashPart = new MessagePart(MessageFileNames.MESSAGE, SHA512_ID,
                        calculateDigest(SHA512_ID, message.getBytes()), message.getBytes());

                List<MessagePart> hashes = Collections.singletonList(hashPart);

                SignatureBuilder builder = new SignatureBuilder();
                builder.addPart(hashPart);

                builder.setSigningCert(subjectCert);
                builder.addOcspResponses(Collections.singletonList(ocsp));

                log.info("### Calculating signature...");

                SignatureData signatureData = builder.build(
                        new SignerSigningKey(KEY_ID, CryptoUtils.CKM_RSA_PKCS_NAME), CryptoUtils.SHA512_ID);

                synchronized (sigIdx) {
                    log.info("### Created signature: {}", signatureData.getSignatureXml());

                    log.info("HashChainResult: {}", signatureData.getHashChainResult());
                    log.info("HashChain: {}", signatureData.getHashChain());

                    toFile("message-" + sigIdx + ".xml", message);

                    String sigFileName = signatureData.getHashChainResult() != null ? "batch-sig-" : "sig-";

                    toFile(sigFileName + sigIdx + ".xml", signatureData.getSignatureXml());

                    if (signatureData.getHashChainResult() != null) {
                        toFile("hash-chain-" + sigIdx + ".xml", signatureData.getHashChain());
                        toFile("hash-chain-result.xml", signatureData.getHashChainResult());
                    }

                    sigIdx++;
                }

                try {
                    verify(signatureData, hashes, message);

                    log.info("Verification successful (message hash: {})", hash);
                } catch (Exception e) {
                    log.error("Verification failed (message hash: {})", hash, e);
                }
            } catch (Exception e) {
                log.error("Error", e);
            } finally {
                latch.countDown();
            }
        }).start();
    }

    latch.await();
    actorSystem.shutdown();
}

From source file:com.miyue.util.Cryptos.java

public static void main(String[] args) throws Exception {
    String helloWorld = "skymobi-android-browser-statiscs-key";
    byte key[] = generateAesKey();
    File file = new File("/Users/feize/key");
    //      byte key[]=FileUtils.readFileToByteArray(file);
    FileUtils.writeByteArrayToFile(file, key);
    //[B@4139eeda
    System.out.println("key is:" + key);
    //      FileOutputStream fos = new FileOutputStream("/Users/feize/key"); 
    //      fos.write(key);
    byte encodeString[] = aesEncrypt(helloWorld.getBytes(), key);
    System.out.println("encodeString is:" + encodeString);
    String decodeString = aesDecrypt(encodeString, key);
    System.out.println("decodeString is:" + decodeString);
}

From source file:GetChannels.java

public static void main(String[] args) {
    System.out.println("Executing Get Channels");
    try {// w w w . j av a 2  s.c o  m
        URL marketoSoapEndPoint = new URL("CHANGEME" + "?WSDL");
        String marketoUserId = "CHANGEME";
        String marketoSecretKey = "CHANGEME";

        QName serviceName = new QName("http://www.marketo.com/mktows/", "MktMktowsApiService");
        MktMktowsApiService service = new MktMktowsApiService(marketoSoapEndPoint, serviceName);

        // Create Signature
        DateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssZ");
        String text = df.format(new Date());
        String requestTimestamp = text.substring(0, 22) + ":" + text.substring(22);
        String encryptString = requestTimestamp + marketoUserId;

        SecretKeySpec secretKey = new SecretKeySpec(marketoSecretKey.getBytes(), "HmacSHA1");
        Mac mac = Mac.getInstance("HmacSHA1");
        mac.init(secretKey);
        byte[] rawHmac = mac.doFinal(encryptString.getBytes());
        char[] hexChars = Hex.encodeHex(rawHmac);
        String signature = new String(hexChars);

        // Set Authentication Header
        AuthenticationHeader header = new AuthenticationHeader();
        header.setMktowsUserId(marketoUserId);
        header.setRequestTimestamp(requestTimestamp);
        header.setRequestSignature(signature);

        // Create Request
        ParamsGetChannels params = new ParamsGetChannels();
        Tag tags = new Tag();
        ArrayOfString tagArray = new ArrayOfString();
        tagArray.getStringItems().add("Webinar");
        tagArray.getStringItems().add("Blog");
        tagArray.getStringItems().add("Tradeshow");
        tags.setValues(tagArray);

        MktowsPort port = service.getMktowsApiSoapPort();
        SuccessGetChannels result = port.getChannels(params, header);

        JAXBContext context = JAXBContext.newInstance(SuccessGetLead.class);
        Marshaller m = context.createMarshaller();
        m.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
        m.marshal(result, System.out);
    } catch (Exception e) {
        e.printStackTrace();
    }
}

From source file:AuthenticationHeader.java

public static void main(String[] args) {

    try {// w w  w  . java  2s  . c  o m
        URL marketoSoapEndPoint = new URL("CHANGE ME" + "?WSDL");
        String marketoUserId = "CHANGE ME";
        String marketoSecretKey = "CHANGE ME";

        QName serviceName = new QName("http://www.marketo.com/mktows/", "MktMktowsApiService");
        MktMktowsApiService service = new MktMktowsApiService(marketoSoapEndPoint, serviceName);
        MktowsPort port = service.getMktowsApiSoapPort();

        // Create Signature
        DateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssZ");
        String text = df.format(new Date());
        String requestTimestamp = text.substring(0, 22) + ":" + text.substring(22);
        String encryptString = requestTimestamp + marketoUserId;

        SecretKeySpec secretKey = new SecretKeySpec(marketoSecretKey.getBytes(), "HmacSHA1");
        Mac mac = Mac.getInstance("HmacSHA1");
        mac.init(secretKey);
        byte[] rawHmac = mac.doFinal(encryptString.getBytes());
        char[] hexChars = Hex.encodeHex(rawHmac);
        String signature = new String(hexChars);

        // Set Authentication Header
        AuthenticationHeader header = new AuthenticationHeader();
        header.setMktowsUserId(marketoUserId);
        header.setRequestTimestamp(requestTimestamp);
        header.setRequestSignature(signature);

        JAXBContext context = JAXBContext.newInstance(AuthenticationHeader.class);
        Marshaller m = context.createMarshaller();
        m.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
        m.marshal(header, System.out);

    } catch (Exception e) {
        e.printStackTrace();
    }
}

From source file:ListMObjects.java

public static void main(String[] args) {
    System.out.println("Executing List MObjects");
    try {/* www .  j a v a 2 s. c o  m*/
        URL marketoSoapEndPoint = new URL("CHANGE ME" + "?WSDL");
        String marketoUserId = "CHANGE ME";
        String marketoSecretKey = "CHANGE ME";

        QName serviceName = new QName("http://www.marketo.com/mktows/", "MktMktowsApiService");
        MktMktowsApiService service = new MktMktowsApiService(marketoSoapEndPoint, serviceName);
        MktowsPort port = service.getMktowsApiSoapPort();

        // Create Signature
        DateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssZ");
        String text = df.format(new Date());
        String requestTimestamp = text.substring(0, 22) + ":" + text.substring(22);
        String encryptString = requestTimestamp + marketoUserId;

        SecretKeySpec secretKey = new SecretKeySpec(marketoSecretKey.getBytes(), "HmacSHA1");
        Mac mac = Mac.getInstance("HmacSHA1");
        mac.init(secretKey);
        byte[] rawHmac = mac.doFinal(encryptString.getBytes());
        char[] hexChars = Hex.encodeHex(rawHmac);
        String signature = new String(hexChars);

        // Set Authentication Header
        AuthenticationHeader header = new AuthenticationHeader();
        header.setMktowsUserId(marketoUserId);
        header.setRequestTimestamp(requestTimestamp);
        header.setRequestSignature(signature);

        // Create Request
        ParamsListMObjects request = new ParamsListMObjects();

        SuccessListMObjects result = port.listMObjects(request, header);
        JAXBContext context = JAXBContext.newInstance(SuccessListMObjects.class);
        Marshaller m = context.createMarshaller();
        m.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
        m.marshal(result, System.out);

    } catch (Exception e) {
        e.printStackTrace();
    }
}

From source file:com.adobe.aem.demomachine.Base64Encoder.java

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

    String value = null;

    // Command line options for this tool
    Options options = new Options();
    options.addOption("v", true, "Value");
    CommandLineParser parser = new BasicParser();
    try {//  w  w  w  . j a v  a  2 s  .  c o m
        CommandLine cmd = parser.parse(options, args);

        if (cmd.hasOption("v")) {
            value = cmd.getOptionValue("v");
        }

        if (value == null) {
            System.out.println("Command line parameters: -v value");
            System.exit(-1);
        }

    } catch (ParseException ex) {

        logger.error(ex.getMessage());

    }

    byte[] encodedBytes = Base64.encodeBase64(value.getBytes());
    System.out.println(new String(encodedBytes));

}