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?

Vadim Kotov
  • 8,084
  • 8
  • 48
  • 62

2 Answers2

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

Anshul Sharma
  • 3,432
  • 1
  • 12
  • 17
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);
}
xor
  • 60
  • 6