简体   繁体   中英

Java Textbox - converting byte to String

I have a java application where you enter a String into a textbox, hit encrypt, and it will show the encrypted String in a seperate textbox. I will be using AES encyption for this. The problem is that I cannot get the crypted text to show as it is in byte but the textbox wont show byte (only takes String). Below is an exert from my code.

 public static byte[] encrypt(String plainText, String encryptionKey) throws Exception {
Cipher cipher = Cipher.getInstance("AES/CBC/NoPadding", "SunJCE");
SecretKeySpec key = new SecretKeySpec(encryptionKey.getBytes("UTF-8"), "AES");
cipher.init(Cipher.ENCRYPT_MODE, key,new IvParameterSpec(IV.getBytes("UTF-8")));
return cipher.doFinal(plainText.getBytes("UTF-8"));
}

private class HandleThat implements ActionListener{
 public void actionPerformed(ActionEvent eve){
 JTextField jtf; //user will enter string here
 JTextField jtf1; //this will show the encrypted text
 plaintext = jtf.getText();
 String error = "Error, you must provide some text"; 
        if(eve.getActionCommand().equals("Encrypt")){
            if(!jtf.getText().equals("")){
             try{   
             byte[] cipher = encrypt(plaintext, encryptionKey);
             for (int i=0; i<cipher.length; i++)

             jtf1.setText(cipher[i]); //here is where I get my error
            } catch (Exception e) {
            e.printStackTrace();}
        }else{
                label.setText(error);
        }
        }

Error - "method setText in class JTextComponent cannot be applied to given types; required: String found: byte reason: actual argument byte cannot be converted to String by method invocation conversion"

How can I change cipher from byte to String?

If you want to pretty-print the array of byte values use:

Arrays.toString(cipher)

If you want the cipher to be interpreted as a String , use:

new String(cipher)

A typical format to show bytes and byte arrays is hexadecimal display. For example, many ciphering applications show the keys in hexadecimal format.

You can use the method shown in this SO answer to convert byte[] to String in hexadecimal format.

This isn't built-in to the API because generally cipher-text contains non-printable characters. You may want to encode the encrypted text as Base-64 , especially if the user plans to do something with it (like send it in an email). This will ensure that all characters are printable.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM