以下是一个与Ultralight-C通信的java代码概念证明,使用Omnikey 5321/6321通过通用会话进行通信:
private static final byte AF = (byte)0xAF;
protected static final byte[] PREFIX = new byte[] { 0x01, 0x00, (byte) 0xF3, 0x00, 0x00, 0x64 };
protected final CardChannel channel;
protected void openGenericSession() throws CardException {
System.out.println("OPEN GENERIC SESSION");
transmitAssert9000(new CommandAPDU(0xFF, 0xA0, 0x00, 0x07, new byte[] { 0x01, 0x00, 0x01}));
}
protected byte[] transmitRaw(byte[] data) throws CardException {
System.out.println(" => " + toHex(data));
byte[] ret = transmitAssert9000(new CommandAPDU(0xFF, 0xA0, 0x00, 0x05, ArrayUtils.addAll(PREFIX, data), 256));
if(ret.length<2) {
throw new RuntimeException();
}
if((ret[0]==0x00)&&(ret[1]==0x00)) {
ret = Arrays.copyOfRange(ret, 2, ret.length);
System.out.println(" <= " + toHex(ret));
return ret;
}
if((ret[0]==0x08)&&(ret[1]==0x04)&&(ret.length==3)) {
switch(ret[2]) {
case 0x0A:
System.out.println(" <= ACK");
return ArrayUtils.EMPTY_BYTE_ARRAY;
default:
System.out.println(" <= NAK");
throw new RuntimeException("NAK");
}
}
ret = Arrays.copyOfRange(ret, 2, ret.length);
System.out.println(" <= " + toHex(ret));
return ret;
}
protected static byte[] assert9000(ResponseAPDU transmit) {
if(transmit.getSW()!=0x9000) {
throw new RuntimeException("Unexpected response code");
}
return transmit.getData();
}
protected byte[] transmitAssert9000(CommandAPDU commandAPDU) throws CardException {
return assert9000(transmit(commandAPDU));
}
protected ResponseAPDU transmit(CommandAPDU commandAPDU) throws CardException {
System.out.println(" -> " + toHex(commandAPDU.getBytes()));
ResponseAPDU responseAPDU = channel.transmit(commandAPDU);
System.out.println(" <- " + toHex(responseAPDU.getBytes()));
return responseAPDU;
}
public byte[] read(int offset) throws CardException {
System.out.println("READ");
return transmitRaw(new byte[] {0x30, (byte)offset});
}
注意1:此代码使用
javax.smartcardio和
Apache Commons Lang。
注意2:我写这段代码已经有一段时间了,请验证我的想法...
注意3:有关Ultralight-C身份验证代码,请参阅此
伴随答案。
Omnikey 6321与Ultralight-C的通用会话示例跟踪(单线箭头表示通用会话APDUs,双线箭头表示Ultralight-C命令):
OPEN GENERIC SESSION
-> FFA0000703010001
<- 9000
AUTHENTICATE
=> 1A00
-> FFA00005080100F30000641A0000
<- 0000AF4BDA4E34B5D04A019000
<= AF4BDA4E34B5D04A01
=> AF6F18402E0F0E5357D854833B149FBB56
-> FFA00005170100F3000064AF6F18402E0F0E5357D854833B149FBB5600
<- 000000F0F667CCF0E140419000
<= 00F0F667CCF0E14041
READ
=> 3003
-> FFA00005080100F3000064300300
<- 0000000000000000000000000000000000009000
<= 00000000000000000000000000000000
CLOSE GENERIC SESSION
-> FFA0000703010002
<- 9000
一些额外的注释:
(据我所知)这种方法适用于Windows(使用Omnikey驱动程序)。它在Linux下不起作用(即使使用Omnikey驱动程序也不行)。
请注意,PC / SC版本2.02第3部分定义了MANAGE SESSION
、TRANSAPARENT EXCHANGE
和SWITCH PROTOCOL
命令,以标准化的方式提供相同的功能(你的读者可能支持它而不是专有的通用会话机制——HID甚至参与了这个文档)。
祝你好运!