I am suffering of a massive lack of speed when it comes to mutual authenticate with the card. This takes about 13 to 20 seconds which seems at least 10 times to much.
The slowest part is the "Get-Challenge" and I think it might be because of my construction of a non-leaking map and the seperate "rotate-left"
public static byte[] NLM (byte[] x, byte[] y) {
final byte[] f1 = new byte[] {(byte) 0x35, (byte) 0xB0,(byte) 0x88,(byte) 0xCC,(byte) 0xE1,(byte) 0x73}; //48-bit unsigned integer
final byte[] constant = new byte[] {(byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x01}; //constant
byte[] Y = new byte[6]; //48-bit unsigned integer
byte[] Y1 = new byte[6]; //48-bit unsigned integer
byte[] R = new byte[6]; //48-bit unsigned integer
byte[] R1 = new byte[6]; //48-bit unsigned integer
short size = 6;
JCArrayInt[] Red = new JCArrayInt[2]; // array of 48-bit unsigned integers
JCArrayInt[] Mul = new JCArrayInt[2]; // array of 48-bit unsigned integers
byte k = 48;
Red[0] = new JCArrayInt(size);
Mul[0] = new JCArrayInt(size);
Red[1] = new JCArrayInt(size);
Mul[1] = new JCArrayInt(size);
Red[1].jcint = Utils.XOR(f1, constant);
Mul[1].jcint = x;
Y = y;
for (short i = 0; i < 48; i++) {
R = rotateLeft48(R);
R1 = Utils.AND(R, constant);
R = Utils.XOR(R, Red[R1[5]].jcint);
Y = rotateLeft48(Y);
Y1 = Utils.AND(Y, constant);
R = Utils.XOR(R, Mul[Y1[5]].jcint);
}
return R;
}
public static byte[] rotateLeft48 (byte[] data) {
byte t = (byte)((data[0] >>> 7) & 0x001);
short l = (short) (data.length - 1);
for (short i = 0; i < l; ++i) {
data[i] = (byte)(((data[i] << 1) & 0x0FE) | ((data[i + 1] >>> 7) & 0x001));
}
data[l] = (byte)(((data[l] << 1) & 0x0FE) | t);
return data;
}
I can live with it taking a little longer due to this overhead besides doing some XOR, AND, rotation and all they key generation and actual encrypting (done with AES-128).
should I use transient arrays (would that make that big of a difference)?
Using JCOP for all that!
Related
I have some byte-int operations. But I cant figure out the problem.
First of all I have a hex data and I am holding it as an integer
public static final int hexData = 0xDFC10A;
And I am converting it to byte array with this function:
public static byte[] hexToByteArray(int hexNum)
{
ArrayList<Byte> byteBuffer = new ArrayList<>();
while (true)
{
byteBuffer.add(0, (byte) (hexNum % 256));
hexNum = hexNum / 256;
if (hexNum == 0) break;
}
byte[] data = new byte[byteBuffer.size()];
for (int i=0;i<byteBuffer.size();i++){
data[i] = byteBuffer.get(i).byteValue();
}
return data;
}
And I want to convert 3 byte array to integer back again how can I do that?
Or you can also suggest other converting functions like hex-to-3-bytes-array and 3-bytes-to-int thank you again.
UPDATE
In c# someone use below function but not working in java
public static int byte3ToInt(byte[] byte3){
int res = 0;
for (int i = 0; i < 3; i++)
{
res += res * 0xFF + byte3[i];
if (byte3[i] < 0x7F)
{
break;
}
}
return res;
}
This will give you the value:
(byte3[0] & 0xff) << 16 | (byte3[1] & 0xff) << 8 | (byte3[2] & 0xff)
This assumes, the byte array is 3 bytes long. If you need to convert also shorter arrays you can use a loop.
The conversion in the other direction (int to bytes) can be written with logical operations like this:
byte3[0] = (byte)(hexData >> 16);
byte3[1] = (byte)(hexData >> 8);
byte3[2] = (byte)(hexData);
You could use Java NIO's ByteBuffer:
byte[] bytes = ByteBuffer.allocate(4).putInt(hexNum).array();
And the other way round is possible too. Have a look at this.
As an example:
final byte[] array = new byte[] { 0x00, (byte) 0xdf, (byte) 0xc1, 0x0a };//you need 4 bytes to get an integer (padding with a 0 byte)
final int x = ByteBuffer.wrap(array).getInt();
// x contains the int 0x00dfc10a
If you want to do it similar to the C# code:
public static int byte3ToInt(final byte[] byte3) {
int res = 0;
for (int i = 0; i < 3; i++)
{
res *= 256;
if (byte3[i] < 0)
{
res += 256 + byte3[i]; //signed to unsigned conversion
} else
{
res += byte3[i];
}
}
return res;
}
to convert Integer to hex: integer.toHexString()
to convert hexString to Integer: Integer.parseInt("FF", 16);
I'm attempting to create a check sum by calculating the two's complement of the least significant byte of the sum of all the data bytes in an array.
So given an array:
byte[] bytes = new byte[] { 0x01, 0x02 };
would something like this work...
public static void main(String []args)
{
byte[] bytes = new byte[] { 0x01, 0x02 };
BigInteger bi = new BigInteger(bytes);
BigInteger biRes = bi.not().add(BigInteger.ONE);
byte[] result = biRes.toByteArray();
System.out.println("a: " + result);
System.out.println("b: " + javax.xml.bind.DatatypeConverter.printHexBinary(result));
}
Produces...
a: [B#34bdb859
b: FEFE
Is this correct?
I have another solution :
private static byte calculateChecksum8(byte[] bytes){
byte result = 0;
for(int i = 0; i < bytes.length; i++){
result += bytes[i];
}
result = (byte) (~ result & 0xFF);
result = (byte) (result +1 & 0xFF);
String str = String.format("%02x", result);
System.out.println(result+" = "+str.toUpperCase());
return result;
}
Someone to confirm ?
Just add up all the bytes, negate the resuit, cast or truncate it to a byte, and you're done.
Hello stackoverflow community,
I need to convert a byte array to a binary byte-array (yes, binary bytes). See this example:
byte[] source = new byte[] {0x0A, 0x00};
//shall be converted to this:
byte[] target = new byte[] {0x00, 0x00, 0x10, 0x10, 0x00, 0x00, 0x00, 0x00};
//this would be ok as well:
also[0] = new byte[] {0x00, 0x00, 0x10, 0x10};
also[1] = new byte[] {0x00, 0x00, 0x00, 0x00};
At the moment I'm solving this by using Integer.toBinaryString to get the binary string and hexStringToByteArray to convert the binary string to a byte array:
for(int o = 0; o < cPage.getCpData().length; o+=cPage.getWidth()) {
String fBinString = "";
for(int u = 0; u < cPage.getWidth(); u++) {
byte[] value = new byte[1];
raBa.read(value);
Byte part = new BigInteger(value).byteValue();
String binString = Integer.toBinaryString(0xFF & part);
fBinString+=("00000000" + binString).substring(binString.length());
}
cPage.addBinaryString(fBinString);
//binaryCodepage.add(fBinString);
testwidth = fBinString.length();
//System.out.println(fBinString);
}
//other class:
public byte[][] getBinaryAsByteArray() {
Object[] binary = getBinaryStrings().toArray();
byte[][] binAsHex = new byte[binary.length][getWidth()*8];
for(int i = 0; i < binary.length; i++) {
binAsHex[i] = ByteUtil.hexStringToByteArray(((String) binary[i]));
}
return binAsHex;
}
This works fine for small source byte-arrays but takes ages for large byte-arrays. Thats probably caused by the conversion to binary String and back.
Any ideas how to improve this by not converting the source to a String?
I don't know what's the motivation to this strange conversion, but you could do something similar to the implementation of Integer.toBinaryString :
private static byte[] toFourBytes(byte i) {
byte[] buf = new byte[4];
int bytePos = 4;
do {
buf[--bytePos] = i & 0x3;
i >>>= 2;
} while (i != 0);
return buf;
}
This should convert (I haven't tested it) each byte to a 4 byte array, in which each byte contains 2 bits of the original byte.
EDIT:
I may have missed the exact requirement. If the two bits extracted from the input byte should be in positions 0 and 4 of the output byte, the code would change to :
private static byte[] toFourBytes(byte i) {
byte[] buf = new byte[4];
int bytePos = 4;
do {
byte temp = i & 0x1;
i >>>= 1;
buf[--bytePos] = ((i & 0x1) << 4) | temp;
i >>>= 1;
} while (i != 0);
return buf;
}
What's the best way to put an int at a certain point in a byte[] array?
Say you have a byte array:
byte[] bytes = {0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00};
int someInt = 12355; //0x43, 0x30
How can I do like bytes[4] = someInt; so that now bytes[4] will equal 0x43 and bytes[5] will be equal to 0x30?
I'm used to just using memcpy with C++ and don't know the alternatives in Java.
Thanks
If you want also high 0-bytes of the int put into the byte[]:
void place(int num, byte[] store, int where){
for(int i = 0; i < 4; ++i){
store[where+i] = (byte)(num & 0xFF);
num >>= 8;
}
}
If you only want the bytes to the highest nonzero byte:
void place(int num, byte[] store, int where){
while(num != 0){
store[where++] = (byte)(num & 0xFF);
num >>>= 8;
}
}
If you want the bytes big-endian (highest byte at lowest index), the version storing all four bytes is very easy, the other one slightly more difficult:
void placeBigEndian(int num , byte[] store, int where){
for(int i = 3; i >= 0; --i){
store[where+i] = (byte)(num & 0xFF);
num >>= 8;
}
}
void placeBigEndian(int num, byte[] store, int where){
in mask = 0xFF000000, shift = 24;
while((mask & num) == 0){
mask >>>= 8;
shift -= 8;
}
while(shift > 0){
store[where++] = (byte)((num & mask) >>> shift);
mask >>>= 8;
shift -= 8;
}
}
Note, you assume a big endian ordering! x86 is little endian... What's more, your int is 32bits long, hence 0x00004330 in big endian.
If this is what you want, use a ByteBuffer (which uses big endian ordering by default):
ByteBuffer buf = ByteBuffer.allocate(8);
// then use buf.putInt(yourint, index)
// buf.get(index) will read byte at index index, starting from 0
I don't see the problem, it looks like you solved it your own way:
public static void putShort(bytes[] array, int position, short value)
{
byte leftByte = (byte) (value >>> 8);
byte rightByte = (byte) (value & 0xFF);
array[position] = leftByte;
array[position + 1] = rightByte;
}
Note that an int is 4 bytes and a short is 2 bytes.
First of all, in Java you don't need to initialize byte arrays to zeroes. All arrays are initialized on construction time to 0/false/null.
Second, ints are signed 32-bit big-endian integers, so 12355 is actually 0x00003043. If you want to use 16-bit integers, use the short type.
Then, to get the individual bytes in your integer, you could do:
bytes[ i ] = (byte) (someInt >> 24);
bytes[ i+1 ] = (byte) (someInt >> 16);
bytes[ i+2 ] = (byte) (someInt >> 8);
bytes[ i+3 ] = (byte) (someInt);
The conversion to byte truncates the remaining bits, so no & 0xFF mask is needed. I'm assuming i is the index of the array. To change the endianness, swap the offsets at the indices.
One approach would be to use a DataOutputStream and it's writeInt() method, wrapped around a ByteArrayOutputStream. e.g. (with no error-handling)
public byte[] writeIntAtPositionX(int position, int iVal) throws IOException {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
DataOutputStream dos = new DataOutputStream(baos);
// now, advancing to a specific spot is awkward.
// presumably you are actually writing other stuff out before the integer
// but if you really want to advance to a specific position
for (int i = 0; i < position; i++)
dos.writeByte(0);
dos.writeInt(iVal);
dos.flush();
dos.close();
return baos.toByteArray();
}
The big advantage of this method is that the guys who wrote Java figured out the byte ordering and the masking with 0xFF and all that stuff. Plus, if you ever envision writing doubles, shorts, longs or Strings etc. to your buffer you won't need to add all those methods, the work is already done.
I'm trying to send a Java UUID to C++, where it will be used as a GUID, then send it back and see it as a UUID, and I'm hoping to send it across as just 16 bytes.
Any suggestions on an easy way to do this?
I've got a complicated way of doing it, sending from Java to C++, where I ask the UUID for its least and most significant bits, write this into a ByteBuffer, and then read it out as bytes.
Here is my silly-complicated way of getting 2 longs out of a UUID, sending them to C++:
Java
public static byte[] asByteArray(UUID uuid)
{
long msb = uuid.getMostSignificantBits();
long lsb = uuid.getLeastSignificantBits();
byte[] buffer = new byte[16];
for (int i = 0; i < 8; i++) {
buffer[i] = (byte) (msb >>> 8 * (7 - i));
}
for (int i = 8; i < 16; i++) {
buffer[i] = (byte) (lsb >>> 8 * (7 - i));
}
return buffer;
}
byte[] bytesOriginal = asByteArray(uuid);
byte[] bytes = new byte[16];
// Reverse the first 4 bytes
bytes[0] = bytesOriginal[3];
bytes[1] = bytesOriginal[2];
bytes[2] = bytesOriginal[1];
bytes[3] = bytesOriginal[0];
// Reverse 6th and 7th
bytes[4] = bytesOriginal[5];
bytes[5] = bytesOriginal[4];
// Reverse 8th and 9th
bytes[6] = bytesOriginal[7];
bytes[7] = bytesOriginal[6];
// Copy the rest straight up
for ( int i = 8; i < 16; i++ )
{
bytes[i] = bytesOriginal[i];
}
// Use a ByteBuffer to switch our ENDIAN-ness
java.nio.ByteBuffer buffer = java.nio.ByteBuffer.allocate(16);
buffer.order(java.nio.ByteOrder.BIG_ENDIAN);
buffer.put(bytes);
buffer.order(java.nio.ByteOrder.LITTLE_ENDIAN);
buffer.position(0);
UUIDComponents x = new UUIDComponents();
x.id1 = buffer.getLong();
x.id2 = buffer.getLong();
C++
google::protobuf::int64 id1 = id.id1();
google::protobuf::int64 id2 = id.id2();
char* pGuid = (char*) &guid;
char* pGuidLast8Bytes = pGuid + 8;
memcpy(pGuid, &id1, 8);
memcpy(pGuidLast8Bytes, &id2, 8);
This works, but seems way too complex, and I can't yet get it working in the other direction.
(I'm using google protocol buffers to send the two longs back and forth)
Alex
I got something working.
Instead of sending it across as two longs, I send it across as bytes, here is the Java code:
public static UUID fromBytes( ByteString byteString)
{
byte[] bytesOriginal = byteString.toByteArray();
byte[] bytes = new byte[16];
// Reverse the first 4 bytes
bytes[0] = bytesOriginal[3];
bytes[1] = bytesOriginal[2];
bytes[2] = bytesOriginal[1];
bytes[3] = bytesOriginal[0];
// Reverse 6th and 7th
bytes[4] = bytesOriginal[5];
bytes[5] = bytesOriginal[4];
// Reverse 8th and 9th
bytes[6] = bytesOriginal[7];
bytes[7] = bytesOriginal[6];
// Copy the rest straight up
for ( int i = 8; i < 16; i++ )
{
bytes[i] = bytesOriginal[i];
}
return toUUID(bytes);
}
public static ByteString toBytes( UUID uuid )
{
byte[] bytesOriginal = asByteArray(uuid);
byte[] bytes = new byte[16];
// Reverse the first 4 bytes
bytes[0] = bytesOriginal[3];
bytes[1] = bytesOriginal[2];
bytes[2] = bytesOriginal[1];
bytes[3] = bytesOriginal[0];
// Reverse 6th and 7th
bytes[4] = bytesOriginal[5];
bytes[5] = bytesOriginal[4];
// Reverse 8th and 9th
bytes[6] = bytesOriginal[7];
bytes[7] = bytesOriginal[6];
// Copy the rest straight up
for ( int i = 8; i < 16; i++ )
{
bytes[i] = bytesOriginal[i];
}
return ByteString.copyFrom(bytes);
}
private static byte[] asByteArray(UUID uuid)
{
long msb = uuid.getMostSignificantBits();
long lsb = uuid.getLeastSignificantBits();
byte[] buffer = new byte[16];
for (int i = 0; i < 8; i++) {
buffer[i] = (byte) (msb >>> 8 * (7 - i));
}
for (int i = 8; i < 16; i++) {
buffer[i] = (byte) (lsb >>> 8 * (7 - i));
}
return buffer;
}
private static UUID toUUID(byte[] byteArray) {
long msb = 0;
long lsb = 0;
for (int i = 0; i < 8; i++)
msb = (msb << 8) | (byteArray[i] & 0xff);
for (int i = 8; i < 16; i++)
lsb = (lsb << 8) | (byteArray[i] & 0xff);
UUID result = new UUID(msb, lsb);
return result;
}
Doing it this way, the bytes can be used straight up on the C++ side. I suppose the switching around of the order of the bytes could be done on either end.
C++
memcpy(&guid, data, 16);
It's possibly easiest to use getMostSignificantBits and getLeastSignificant bits to get long values, and send those. Likewise you can reconstruct the UUID from those two longs using the appropriate constructor.
It's a shame there isn't a toByteArray/fromByteArray pair of methods :(
Your current way is fine, nothing wrong about doing it that way.
Another approace is yo just communicate with the string representation of the uuid, send the string, parse it in c++.
Btw, bytes do not have endianess, Unless you're casting a byte/char array or similar to an integer type, you just determine the endianess by assigning the bytes back in the approprate order.
Here is what I do to convert a C++ GUID to a Java UUID. On the C++ side, the GUID struct is just converted to bytes. The conversion to C++ can then just go along the same lines.
public static UUID cppGuidBytesToUuid(byte[] cppGuid) {
ByteBuffer b = ByteBuffer.wrap(cppGuid);
b.order(ByteOrder.LITTLE_ENDIAN);
java.nio.ByteBuffer out = java.nio.ByteBuffer.allocate(16);
out.order(ByteOrder.BIG_ENDIAN);
out.putInt(b.getInt());
out.putShort(b.getShort());
out.putShort(b.getShort());
out.put(b);
out.position(0);
return new UUID(out.getLong(), out.getLong());
}
// Here is the JNI code ;-)
jbyteArray GUID2ByteArray(JNIEnv *env,GUID* guid)
{
if (guid == NULL)
return NULL;
jbyteArray jGUID = env->NewByteArray(sizeof(GUID));
if (jGUID == NULL)
return NULL;
env->SetByteArrayRegion(jGUID,0,sizeof(GUID),(signed char*)(guid));
if (env->ExceptionOccurred() != NULL)
return NULL;
return jGUID;
}
Perhaps you could explain why you are not just doing.
UUID uuid =
x.id1 = uuid.getMostSignificantBits();
x.id2 = uuid.getLeastSignificantBits();
P.S. As I read #Jon Skeet's post again, I think this is much the same advice. ;)