add APDUCommand class and test

This commit is contained in:
Andrea Franz 2018-08-24 12:11:04 +02:00
parent cbd580ee5c
commit dfdc61bb5e
No known key found for this signature in database
GPG Key ID: 4F0D2F2D9DE7F29D
3 changed files with 93 additions and 0 deletions

View File

@ -0,0 +1,39 @@
package im.status.applet_installer_test.appletinstaller;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
public class APDUCommand {
protected int cla;
protected int ins;
protected int p1;
protected int p2;
protected int lc;
protected byte[] data;
public APDUCommand(int cla, int ins, int p1, int p2, byte[] data) {
this.cla = cla;
this.ins = ins;
this.p1 = p1;
this.p2 = p2;
this.data = data;
}
public byte[] serialize() throws IOException {
ByteArrayOutputStream out = new ByteArrayOutputStream();
out.write(this.cla);
out.write(this.ins);
out.write(this.p1);
out.write(this.p2);
int lc = this.data.length;
if (lc > 0) {
out.write(lc);
out.write(this.data);
}
out.write(0); // Response length
return out.toByteArray();
}
}

View File

@ -0,0 +1,30 @@
package im.status.applet_installer_test.appletinstaller;
public class HexUtils {
public static byte[] hexStringToByteArray(String s) {
int len = s.length();
byte[] data = new byte[len/2];
for(int i = 0; i < len; i+=2){
data[i/2] = (byte) ((Character.digit(s.charAt(i), 16) << 4) + Character.digit(s.charAt(i+1), 16));
}
return data;
}
final protected static char[] hexArray = {'0','1','2','3','4','5','6','7','8','9','A','B','C','D','E','F'};
public static String byteArrayToHexString(byte[] bytes) {
char[] hexChars = new char[bytes.length * 2];
int v;
for(int j=0; j < bytes.length; j++) {
v = bytes[j] & 0xFF;
hexChars[j * 2] = hexArray[v>>>4];
hexChars[j * 2 + 1] = hexArray[v & 0x0F];
}
return new String(hexChars);
}
}

View File

@ -0,0 +1,24 @@
package im.status.applet_installer_test.appletinstaller;
import org.junit.Test;
import java.io.IOException;
import static org.junit.Assert.*;
public class APDUCommandTest {
@Test
public void serialize() throws IOException {
int cla = 0x80;
int ins = 0x50;
int p1 = 0;
int p2 = 0;
byte[] data = HexUtils.hexStringToByteArray("84762336c5187fe8");
APDUCommand c = new APDUCommand(cla, ins, p1, p2, (byte[])data);
String expected = "805000000884762336C5187FE800";
String actual = HexUtils.byteArrayToHexString(c.serialize());
assertEquals(expected, actual);
}
}