1

Receving error that string cannot be convert to byte[]:

String decrypted = new String(cipher.doFinal(msgin));

This is the encryption method which is correct as i'm getting the message in encrypted form.

    try{
    String msgout = "";
    msgout = msg_text.getText().trim();
    aesKey = new SecretKeySpec(key.getBytes(), "AES");
        cipher = Cipher.getInstance("AES");
        cipher.init(Cipher.ENCRYPT_MODE, aesKey);
        encrypted = cipher.doFinal(msgout.getBytes());
    String msgout1;
        msgout1 = String.valueOf(encrypted);
    dout.writeUTF(msgout1);
    msg_area.setText(msg_area.getText().trim()+"\nYou:\t"+msgout);
    }catch(Exception e){

    }

This the display message which is decrypted

    String msgin = "";
     try{
       ss = new ServerSocket(1201);
       s = ss.accept();
       din = new DataInputStream(s.getInputStream());
       dout = new DataOutputStream(s.getOutputStream());
       while(!msgin.equals("exit")){
           msgin = din.readUTF();
           cipher.init(Cipher.DECRYPT_MODE, aesKey);               
          String decrypted = new String(cipher.doFinal(msgin));\\here am receving error that string cannot be convert to byte[]
        msg_area.setText(msg_area.getText().trim()+"\nClient:\t"+decrypted);

       }
    }catch(Exception e){

    }

Any solutions?

1

2 Answers 2

1

for String to byte[] you can use this code.

    byte[] msginbyte = msgin.getBytes();
    System.out.println(Arrays.toString(valuesDefault));

Use Arrays.toString to display our byte array.

    byte[] valuesAscii = letters.getBytes("US-ASCII");
    byte[] valuesAscii = letters.getBytes("UTF-8");

Specify US-ASCII, UTF-8,UTF-16 char set directly

Sign up to request clarification or add additional context in comments.

Comments

0

Use the String.getBytes() method to convert the String to a byte array before calling cipher.doFinal(msgin).

while(!msgin.equals("exit")){
    msgin = din.readUTF();
    cipher.init(Cipher.DECRYPT_MODE, aesKey);               
    String decrypted = new String(cipher.doFinal(msgin.getBytes()));
    msg_area.setText(msg_area.getText().trim()+"\nClient:\t"+decrypted);
}

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.