I dont know 0xAA55 get in byte array (size 2) - java

I developing TCP Server Program but I stucked this Server's Protocol
the header is fixed by 0xAA55, header size is 2 Byte
this is the problem I dont know fill in 0xAA55 to byte array
byte[] tmp = new byte[2];
tmp = 0xAA55;
this is not work..

You could wrap tmp with a ByteBuffer and then use ByteBuffer.putShort(short) like
byte[] tmp = new byte[2];
ByteBuffer bb = ByteBuffer.wrap(tmp);
bb.putShort((short) 0xAA55);
System.out.println(Arrays.toString(tmp));

Related

Convert String to byte[] array

I want to convert a String to a byte array but the array must have 256 positions, I mean, like this:
public byte[] temporal1 = new byte[256];
public byte[] temporal2 = new byte[256];
So, when I do:
String send = "SEND_MESSAGE";
String sendAck = "SEND_MESSAGE_ACK";
temporal1 = send.getBytes();
temporal2 = sendAck.getBytes();
I get this error: "./th.java:24: error: <identifier> expected". I know that if I do public byte[] temporal1 = send.getBytes();it works, but I need the array with that size to compare it with other byte array byte to byte.
can you please show the exact Exception or Error which is occurring in the console. because it works completely fine with me.
byte b1[] = new byte[256];
String s = "hello there";
b1 = s.getBytes();
System.out.println(b1);
To have the byte array temporal1 padded upto 256 bytes, you might do:
public byte[] temporal1 = new byte[256];
String send = "SEND_MESSAGE";
byte[] sendB = send.getBytes(send, StandardCharsets.UTF_8);
System.arraycopy(sendB, 0, temporal1, 0, Math.max(256, sendB.length));
If you want a C like terminating 0 byte, sendB may only provide 255 bytes: Math.max(255, sendB.length).
Better:
String send = "SEND_MESSAGE";
byte[] sendB = send.getBytes(send, StandardCharsets.UTF_8);
byte[] temporal1 = Arrays.copyOf(sendB, 256); // Pads or truncates.
temportal1[255] = (byte) 0; // Maybe
To get a byte[] from String with defined size:
public static byte[] toBytes(String data, int length) {
byte[] result = new byte[length];
System.arraycopy(data.getBytes(), 0, result, length - data.length(), data.length());
return result;
}
Ex:
byte[] sample = toBytes("SEND_MESSAGE", 256);
sample will be of size 256.

How to make a byte array with first eight bytes as current timestamp?

I am making a byte array with predefined size as shown below:
private byte[] newPayload() {
byte[] payload = new byte[100];
Arrays.fill(payload, (byte) 1);
return payload;
}
Now I want to add 8 bytes of current timestamp in the same byte array in front of it.
long time = System.currentTimeMillis();
So first eight bytes will be current timestamp and remaining 92 bytes will be same what I am doing right now.
You can use ByteBuffer to convert long to byte[]. Also you can use System.arraycopy to copy this byte[] to the mail array. Please refer the below code.
ByteBuffer buffer = ByteBuffer.allocate(Long.SIZE / Byte.SIZE);
buffer.putLong(time);
byte[] timeBytes = buffer.array();
System.arraycopy(timeBytes, 0, payload, 0, timeBytes.length);

send tdata frame to a socket

byte[] demande=new byte[2];
Let's suppose that demande is a data frame which will be send to a socket.
What should be byte[0] and byte[1] if I want send 200. I try to write byte[0]=1 and byte[1]=-56 ( 1*256 - 56)=200 but it don't work. How can I do?
I assume that the number 200 is a decimal value.
As 200 is less than 255 it will fit into one byte because the hexadecimal value of 200 is 0xC8.
So in your case you have two options. Which one is correct depends on the protocol you are using.
Either
byte[] demande = { 0x00, 0xC8 }; // little endian
or
byte[] demande = { 0xC8, 0x00 }; // big endian
Or if you prefer
byte[] demande = new byte[2];
demande[0] = 0x00;
demande[1] = 0xC8;
(little endian)
You can use the ByteBuffer class to create a byte array. If you wanted to convert the integer 200 to a byte array:
ByteBuffer b = ByteBuffer.allocate(2);
b.putInt(0x000000c8);
byte[] result = b.array();

Java client server chat pads strings with squares when converting to byte[]

I'm building a chat client and server as part of a class project and running into one problem I can't seem to fix. Text has to be passed in the form of fixed size byte[] (either 32 or 64 bytes) depending on the particular case.
When I change the strings to byte[] with the .getBytes() method it pads out the length of the string with empty squares. This is fine during transit and receipt but at some point I need to change the string to it's original format (currently done with new String(byte[]) and delete the empty squares.
I can't seem to find a good way to do this. Any suggestions?
Relevant code bits client side:
byte[] bigDataByte = new byte[64];
sendData[2] = (bigDataByte = message.getBytes())
for (int i = 0; i < sendData.length; i++){
if (sendData[i] != null){
DatagramPacket sendPacket = new DatagramPacket(sendData[i], sendData[i].length, IPAddress, clientPort);
clientSocket.send(sendPacket);
}
}
Relevant code bits server side:
String name = new String(getBytes(32));
private static byte[] getBytes(int size) throws IOException {
byte[] dataByte = new byte[size];
DatagramPacket dataPacket = new DatagramPacket(dataByte, dataByte.length);
servSocket.receive(dataPacket);
return dataPacket.getData();
}
Not sure, but the issue might be that you are not specifying the charset.
Try using the
constructor: String(byte[] bytes, String charsetName)
and the method: getBytes(String charsetName).
e.g.
byte[] bytes = str.getBytes("UTF-8");
and
String str = new String(bytes, "UTF-8");
The default ones use the platform's default charset, which could lead to a mismatch.

Read byte[] from server

I am trying to read byte[] that is being send from a client to a server.
This is my client code...
din = new DataInputStream(socket.getInputStream());
dout = new DataOutputStream(socket.getOutputStream());
Cipher cipher = Cipher.getInstance("RSA");
// encrypt the aeskey using the public key
cipher.init(Cipher.ENCRYPT_MODE, pk);
byte[] cipherText = cipher.doFinal(aesKey.getEncoded());
dout.write(cipherText);
And this is my server code...
DataInputStream dis = new DataInputStream(socket.getInputStream());
DataOutputStream dos = new DataOutputStream(socket.getOutputStream());
String chiper = dis.readUTF();
System.out.println(chiper);
However, the dis.readUTF(); line fails with an exception...
java.io.EOFException at java.io.DataInputStream.readFully(DataInputStream.java:197)
at java.io.DataInputStream.readUTF(DataInputStream.java:609)
at java.io.DataInputStream.readUTF(DataInputStream.java:564)
at gameserver.ClientHandler.run(GameServer.java:65)
Could someone please help me understand why this doesn't work.
For starters, if you write a sequence of (encrypted!) bytes at one end, and trying to read a UTF-formatted string at the other end...you're going to have a bad time.
I'd suggest that on the client side you should do something like
dout.writeInt(cipherText.length);
dout.write(cipherText);
and then on the server side you should do something like
int byteLength = dis.readInt(); // now I know how many bytes to read
byte[] theBytes = new byte[byteLength];
dis.readFully(theBytes);
DataIputStream.readUTF() is for data that you have written with DataOutputStream.writeUTF()`. You haven't written UTF so you can't read it.
This is binary data so you shouldn't be thinking about UTF or strings at all. Write the length of the array with writeInt(), then the array with write(). At the other end, read the length with readInt(), allocate a byte[] buffer that big and then read the ciphertext into it with readFully().
Yo have to get the message with the read method and get the number of characters of the real messages and then convert this to a string
int bytesRead = 0;
byte[] messageByte = new byte[1000];
bytesRead = dis.read(messageByte);
String chiper = new String(messageByte, 0, bytesRead);
System.out.println(chiper);
on client side, you should convert the byte[] array to String and use
dout.writeUTF() to send the converted String.

Categories