I have the following values:
public static short TAG_VALUE1 = 0x2E09;
public static short TAG_VALUE2 = 0x2E0D;
And I want to create a byte[] from both values. As a byte array, I have to get the first byte and insert it into the array and then the second byte of each TAG. I tried to convert to string and then go back, but I think it has to be an easier way to do so.
How can I get this in a byte[] that looks like this?
2E 09 2E 0D
How about
byte[] foo = new byte[] {
(byte) (TAG_VALUE1>>8),
(byte) (TAG_VALUE1),
(byte) (TAG_VALUE2>>8),
(byte) (TAG_VALUE2),
};
See ByteBuffer and its many uses.
byte[] bytes = new byte[4];
ByteBuffer buf = ByteBuffer.wrap(bytes);
buf.putShort(TAG_VALUE1);
buf.putShort(TAG_VALUE2);
Related
I'm trying to read an unsigned long from byte stream (that has been generated by a C program). Since the number might be too big for a Java long I imagined the best way to do this would be to read the 8 bytes into a BigInteger (as below) but this doesn't work.
Would appreciate any help with a good way to do this.
ByteBuffer bb = ByteBuffer.wrap(new byte[8]).order(ByteOrder.nativeOrder());
bb.putLong(12345678910L);
byte[] bytes = new byte[8];
for(int i=0; i<8; i++){
bytes[i] = bb.get(i);
}
BigInteger bi = new BigInteger(bytes);// bi is not correct
Try taking out the order call:
ByteBuffer bb = ByteBuffer.wrap(new byte[8]);
bb.putLong(12345678910L);
I'm trying to write to a Brother label printer, even Brother supplies a SDK they do not have a newsroom for developers and the support are send to the regular printer support.
I have to send the following hex 1b, 69, 7a, 84, 00 as one of many lines.
I tried to do the following but I get an error on the hex 84 saying not a byte. I did a print to file from Brothers label program to view it in a hex editor and the hex editor shows 1B 69 7A 84 00
final ArrayList<Byte> commands = new ArrayList<Byte>();
Byte[] printinfoCommand = new Byte[] {0x1b, 0x69, 0x7a, 0x84, 0x00];
AddRange(commands, printinfoCommand);
byte[] commandToSendToPrinter = convertFromListByteArrayTobyteArray(commands);
myPrinter.writeBytes(commandToSendToPrinter);
public static void AddRange(ArrayList<Byte> array, Byte[] newData) {
for(int index=0; index<newData.length; index++) {
array.add(newData[index]);
}
}
Let's assume that you need to send a byte[] to the printer interface. With that in mind, there's a couple of issues with your code.
Firstly, you're using an array of big B Byte (which is the wrapper object), rather than an array of primitive bytes.
Secondly, in Java a byte is signed, so the maximum literal byte you can write (without casting) is 0x7F. To specify a byte of 0x84, you'll have to explicitly cast it.
Your array literal should therefore be:
byte[] printInfoCommand =
new byte[] { 0x1b, 0x69, 0x7a, (byte) 0x84, 0x00 };
and you can pass this array:
myPrinter.writeBytes(printInfoCommand);
The other lines of code you have look unnecessary.
I've a String with value 0xE20x800x93.
I try to convert them like this and it works
byte[] bs = new byte[]{
(byte) 0xE2,(byte) 0x80, (byte) 0x93
};
But what I want is without doing the explicit casting, I need to convert it into a byte array.
Or at least a way to convert into a byte object, and not a byte[] object.
You can do it in one (albeit long) line:
byte[] bytes = Arrays.copyOfRange(new ByteBuffer().putInt(Integer.parseInt(str.replace("0x", ""), 16)).array(), 1, 4);
This assumes you have exactly 3 bytes to get. If it's a variable length, the following code is more generic, but slightly more verbose, because it uses the length of the input to determine the eventual result size:
byte[] bytes = Arrays.copyOfRange(new ByteBuffer().putInt(Integer.parseInt(str.replace("0x", ""), 16)).array(), 4 - str.length() / 4, 4);
try DatatypeConverter.parseHexBinary(str) from javax.xml.bind package
I need to convert a salt value randomly generated and store it in the database. To store it in the database I converted it to a string. Then for retrieving the original value, I convert it back to byte. But both value are not matching. I have tried "UTF-8","UTF-16", BASE64Encoder.
SecureRandom ranGen = new SecureRandom();
byte[] aesKey = new byte[16]; // 16 bytes = 128 bits
ranGen.nextBytes(aesKey);
System.out.println(aesKey);
String a=new String(aesKey,"UTF-16");
byte[] b=new byte[16];
b=a.getBytes("UTF-16");
System.out.println(b);
Outputs for the above code(Executed it 2 times):
[B#11563ff
[B#1581593
and
[B#170888e
[B#11563ff
You really ought to use Base64 for converting binary data to Strings. There are lots of free implementations available, for example the one found in Apache Commons Codec.
Also, it's really easy to use, for example:
For encoding:
import org.apache.commons.codec.binary.Base64;
...
byte[] abValue = {...}; // Your data to encode
Base64 base64 = new Base64();
String strEncodedData = base64.encodeToString(abValue).trim();
For decoding:
import org.apache.commons.codec.binary.Base64;
...
String strEncodedData = "..."; // Your previously encoded data
Base64 base64 = new Base64();
byte[] abValue = base64.decode(strValue);
As your code is written above, printing aesKey and then b, what you are actually printing is the output of the toString method for an array object, which is just the default Object toString method. So I don't see how you can expect them to be the same.
If you really want to check they are the same you should compare them byte by byte.
In terms of your actual question regarding storing a byte[] as a String in the DB, your best bet is to Base64 encode it. I would suggest using the Apache Commons Codec library for this. See the user guide.
EDIT:
Using the BASE64Encode and BASE64Decoder you have referred to, the code would be like this:
SecureRandom ranGen = new SecureRandom();
byte[] aesKey = new byte[16]; // 16 bytes = 128 bits
ranGen.nextBytes(aesKey);
String a = new BASE64Encoder().encode(aesKey);
System.out.println(a);
byte[] b = new BASE64Decoder().decodeBuffer(a);
System.out.println(new BASE64Encoder().encode(b));
for (int i = 0; i < aesKey.length; i++) {
System.out.println(aesKey[i] + " " + b[i]);
}
Here, I have also looped through the bytes individually, to show that they are indeed equal.
I'm trying to encrypt some integers in java using java.security and javax.crypto.
The problem seems to be that the Cipher class only encrypts byte arrays. I can't directly convert an integer to a byte string (or can I?). What is the best way to do this?
Should I convert the integer to a string and the string to byte[]? This seems too inefficient.
Does anyone know a quick/easy or efficient way to do it?
Please let me know.
Thanks in advance.
jbu
You can turn ints into a byte[] using a DataOutputStream, like this:
ByteArrayOutputStream baos = new ByteArrayOutputStream ();
DataOutputStream dos = new DataOutputStream (baos);
dos.writeInt (i);
byte[] data = baos.toByteArray();
// do encryption
Then to decrypt it later:
byte[] decrypted = decrypt (data);
ByteArrayInputStream bais = new ByteArrayInputStream (data);
DataInputStream dis = new DataInputStream (bais);
int j = dis.readInt();
You can also use BigInteger for conversion:
BigInteger.valueOf(integer).toByteArray();
Just use NIO. It's designed for this specific purpose. ByteBuffer and IntBuffer will do what you need quickly, efficiently, and elegantly. It'll handle big/little endian conversion, "direct" buffers for high performance IO, and you can even mix data types into the byte buffer.
Convert integers into bytes:
ByteBuffer bbuffer = ByteBuffer.allocate(4*theIntArray.length);
IntBuffer ibuffer = bbuffer.asIntBuffer(); //wrapper--doesn't allocate more memory
ibuffer.put(theIntArray); //add your int's here; can use
//array if you want
byte[] rawBytes = bbuffer.array(); //returns array backed by bbuffer--
//i.e. *doesn't* allocate more memory
Convert bytes into integers:
ByteBuffer bbuffer = ByteBuffer.wrap(rawBytes);
IntBuffer ibuffer = bbuffer.asIntBuffer();
while(ibuffer.hasRemaining())
System.out.println(ibuffer.get()); //also has bulk operators
I have found the following code that may help you, since Integer in Java is always 4 bytes long.
public static byte[] intToFourBytes(int i, boolean bigEndian) {
if (bigEndian) {
byte[] data = new byte[4];
data[3] = (byte) (i & 0xFF);
data[2] = (byte) ((i >> 8) & 0xFF);
data[1] = (byte) ((i >> 16) & 0xFF);
data[0] = (byte) ((i >> 24) & 0xFF);
return data;
} else {
byte[] data = new byte[4];
data[0] = (byte) (i & 0xFF);
data[1] = (byte) ((i >> 8) & 0xFF);
data[2] = (byte) ((i >> 16) & 0xFF);
data[3] = (byte) ((i >> 24) & 0xFF);
return data;
}
}
You can find more information about the bigEndian parameter here:
http://en.wikipedia.org/wiki/Endianness
create a 4-byte array and copy the int to the array in 4 steps, with bitwise ANDs and bitshifting, like Paulo said.
But remember that block algorithms such as AES and DES work with 8 or 16 byte blocks so you will need to pad the array to what the algorithm needs. Maybe leave the first 4 bytes of an 8-byte array as 0's, and the other 4 bytes contain the integer.
Just use:
Integer.toString(int).getBytes();
Make sure you use your original int and getBytes() will return a byte array. No need to do anything else complicated.
To convert back:
Integer.parseInt(encryptedString);
My Simple Solution is that Encrypt Integer to the String by shifting ASCII Value of the Integer by the secret key you Provide.
Here is the Solution:
public String encodeDiscussionId(int Id) {
String tempEn = Id + "";
String encryptNum ="";
for(int i=0;i<tempEn.length();i++) {
int a = (int)tempEn.charAt(i);
a+=148113;
encryptNum +=(char)a;
}
return encryptNum;
}
public Integer decodeDiscussionId(String encryptText) {
String decodeText = "";
for(int i=0;i<encryptText.length();i++) {
int a= (int)encryptText.charAt(i);
a -= 148113;
decodeText +=(char)a;
}
int decodeId = Integer.parseInt(decodeText);
return decodeId;
}
Steps to Encode:
Here, First you convert the Given Integer into String by: String temp = givenInt + ""
Scan each character of String, Read ASCII of that character and add it with secret key as 148113 in this case.
Convert shifted Integer into Character and concatenate to the String encryptNum and finally return it.
Steps to Decode:
Scan each character of String, Read ASCII of that character and subtract it with secret key as previous.
Convert that value to character and concatenate with decodeText.
As previous encode output is always String '???' and vary according to number of digits of input Id.