There is Vector and DataOutputStream. I need to write bytes from Vector (toArray returns Byte[]) to the stream, but it understands byte[] only. How to convert Byte[] to byte[] ?
You could use the toPrimitive method in the Apache Commons lang library ArrayUtils class?
byte[] toPrimitives(Byte[] oBytes)
{
byte[] bytes = new byte[oBytes.length];
for(int i = 0; i < oBytes.length; i++) {
bytes[i] = oBytes[i];
}
return bytes;
}
Inverse:
// byte[] to Byte[]
Byte[] toObjects(byte[] bytesPrim) {
Byte[] bytes = new Byte[bytesPrim.length];
int i = 0;
for (byte b : bytesPrim) bytes[i++] = b; // Autoboxing
return bytes;
}
freeone3000 contributed in this answer :)
A Vector<Byte> is about as inefficient structure as you could use to store bytes. I would serious consider using something more efficient line ByteArrayOutputStream which has a toByteArray() method. i.e. don't just convert the Vector but remove it from the code.
Related
I have wrote a simple snippet in which I try to convert (maybe) a byte array in char array e vice versa.
There are a lot of examples on the Net but this is for me the simplest way to do it.
I need to use array and not strings because its content is a password field to manage.
So I ask you, is this snippet correct?
private static char[] fromByteToCharArrayConverter(byte[] byteArray){
ByteBuffer buffer = ByteBuffer.wrap(byteArray);
clearArray(byteArray);
CharBuffer charBuffer = Charset.forName("UTF-8").decode(buffer);
char[] charArray = new char[charBuffer.remaining()];
charBuffer.get(charArray);
return charArray;
}
private static byte[] fromCharToByteArray(char[] charArray){
CharBuffer charBuffer = CharBuffer.wrap(charArray);
ByteBuffer byteBuffer = Charset.forName("UTF-8").encode(charBuffer);
byte[] byteArray = new byte[byteBuffer.remaining()];
byteBuffer.get(byteArray);
return byteArray;
}
Thanks
No, that won't work for (at least) the following reason:
ByteBuffer buffer = ByteBuffer.wrap(byteArray); // Wrap the array
clearArray(byteArray); // Clear the array -> ByteBuffer cleared too
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.
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.
I think i'm looking for some sort of basic file encryption but don't know where to start.
I'm looking for someone to tell me where to start looking or, even better, offer some code.
I've written a game that currently saves data to a general text file. This of course could be changed by anyone who wished to do so.
What i need is to create a file that can store integers and strings that is difficult if not impossible to be edited outside of the game.
In my searching i came across .dat files but they seemed more complicated that what i'm looking for.
All help is appreciated, Alex.
You can write your data to a ByteBuffer and then you can distort your data by a simple algorithm. For example, assume that the data you want to save is a String array, you can do this:
String[] data; // the data you want to save
int byteLength = 0;
byte[][] bytes = new byte[data.length][];
// Calculate the length of the content.
for(int i=0; i<data.length; i++) {
bytes[i] = data[i].getBytes();
byteLength += bytes[i].length;
byteLength += 4; // this is for an integer, which is for the length of the String
}
// Transfer the content to a ByteBuffer object
ByteBuffer buffer = ByteBuffer.allocate(byteLength);
for(int i=0; i<bytes.length; i++) {
// Put the length of the current byte array
buffer.putInt(bytes[i].length);
for(int j=0; j<bytes[i].length; j++) {
// Reverse the byte so that it can't be understood
buffer.put((byte)(~bytes[i][j]));
}
}
After writing all of your content to the ByteBuffer object, you can take the resulting byte array and write it down to a file.
FileOutputStream fos = new FileOutputStream("YourFileName.anyExtension");
fos.write(buffer.array());
fos.close();
While reading the file back, you should first read an integer, which is the length of the data you should read as byte array, then you should read this byte array.
FileInputStream fis = new FileInputStream("YourFileName.anyExtension");
DataInputStream dis = new DataInputStream(fis);
ArrayList<String> list = new ArrayList<String>();
byte[] bytes;
while(dis.available()) {
int length = dis.readInt();
bytes = new byte[length];
for(int i=0; i<length; i++) {
// Those bytes were reversed, right?
bytes[i] = (byte)(~dis.readByte());
}
// Convert byte array to String
String str = new String(bytes);
list.add(str);
}
Now you have an ArrayList of your String data.
Of course this is not the best, the safest, and the fastest algorithm. You can always find or create faster. But I think this is a good example of doing those kind of things.
If you are using Java you can just try and create a class that implements Serializable This way you can just create an object with all your meta info stored inside, serialize it, and when you wanna load it just deserialize it again.
Its not very safe though since you only need to know have the class it was made with, to deserialize it. But it is something to begin with.
Look into digital signatures, specifically HMACs. Those are pretty much exactly what you need, and the Java Crypto framework should make things fairly straightforward. Here's a potentially relevant SO entry: How to generate an HMAC in Java equivalent to a Python example?
You could pass your file writing stream thru a CipherOutputStream
Generate a random string, or number or anything. get its byte array, produce a key, and use it to encrypt your file.
byte password[] = (WHAT YOUR WANT. STRING, NUMBER, etc.).getBytes();
DESKeySpec desKeySpec;
try {
desKeySpec = new DESKeySpec(password);
SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");
SecretKey key = keyFactory.generateSecret(desKeySpec);
Cipher desCipher = Cipher.getInstance("DES/ECB/PKCS5Padding");
desCipher.init(Cipher.ENCRYPT_MODE, key);
// Create stream
FileOutputStream fos = new FileOutputStream("Your file here");
BufferedOutputStream bos = new BufferedOutputStream(fos);
CipherOutputStream cos = new CipherOutputStream(bos, desCipher);
}
Now you can write to the file using cos
Reading the file is done the same way using the SecretKey object
SecretKey key = loadKey(); // Deserialize your SecretKey object
try {
Cipher cipher = Cipher.getInstance("DES/ECB/PKCS5Padding");
cipher.init(Cipher.DECRYPT_MODE, key);
FileInputStream fis = new FileInputStream("Your file here");
BufferedInputStream bis = new BufferedInputStream(fis);
CipherInputStream cis = new CipherInputStream(bis, cipher);
now you can read using cis
The downside is you need to keep the SecretKey object (Serialize it or something) it wouldn't be a problem for any low level hacker to get the data (since the key is stored on the device) but it wouldn't allow just changing your data using a text editor.
I am using Javas UUID and need to convert a UUID to a byte Array. Strangely the UUID Class does not provide a "toBytes()" method.
I already found out about the two methods:
UUID.getMostSignificantBits()
and
UUID.getLeasSignificantBits()
But how to get this into a byte array? the result should be a byte[] with those tow values. I somehow need to do Bitshifting but, how?
update:
I found:
ByteBuffer byteBuffer = MappedByteBuffer.allocate(2);
byteBuffer.putLong(uuid.getMostSignificantBits());
byteBuffer.putLong(uuid.getLeastSignificantBits());
Is this approach corret?
Are there any other methods (for learning purposes)?
Thanks very much!!
Jens
You can use ByteBuffer
byte[] bytes = new byte[16];
ByteBuffer bb = ByteBuffer.wrap(bytes);
bb.order(ByteOrder.LITTLE_ENDIAN or ByteOrder.BIG_ENDIAN);
bb.putLong(UUID.getMostSignificantBits());
bb.putLong(UUID.getLeastSignificantBits());
// to reverse
bb.flip();
UUID uuid = new UUID(bb.getLong(), bb.getLong());
One option if you prefer "regular" IO to NIO:
ByteArrayOutputStream baos = new ByteArrayOutputStream();
DataOutputStream dos = new DataOutputStream(baos);
dos.write(uuid.getMostSignificantBits());
dos.write(uuid.getLeastSignificantBits());
dos.flush(); // May not be necessary
byte[] data = dos.toByteArray();
For anyone trying to use this in Java 1.7, I found the following to be necessary:
<!-- language: lang-java -->
ByteArrayOutputStream baos = new ByteArrayOutputStream();
DataOutputStream dos = new DataOutputStream(baos);
dos.writeLong(password.getMostSignificantBits());
dos.writeLong(password.getLeastSignificantBits());
dos.flush(); // May not be necessary
return baos.toByteArray();