如何向 HCE 设备发送命令 APDU?

How to send a command APDU to a HCE device?

我的应用程序的AID是F239856324897348,我已经为它构建了一个SelectAID APDU。现在我如何将它实际发送到使用主机卡仿真的接收 Android 设备。

我已经创建了我的 HCE 服务来响应 APDU,就像在这个线程中一样:

public static byte[] SelectAID = new byte[]{
        (byte) 0xF2, (byte) 0x39, (byte) 0x85, (byte) 0x63,
        (byte) 0x24, (byte) 0x89, (byte) 0x73, (byte) 0x48};

private void commandAPDU(byte[] apdu){
   //where do I go from here...
}

commandAPDU(SelectAID);

A​​PDU 的格式在 ISO/IEC 7816-4 中定义。典型的 SELECT(通过 AID)命令如下所示:

+-----+-----+-----+-----+-----+-------------------------+-----+
| CLA | INS | P1  | P2  | Lc  | DATA                    | Le  |
+-----+-----+-----+-----+-----+-------------------------+-----+
| 00  | A4  | 04  | 00  | XX  | AID                     | 00  |
+-----+-----+-----+-----+-----+-------------------------+-----+

您可以这样创建它:

private byte[] selectApdu(byte[] aid) {
    byte[] commandApdu = new byte[6 + aid.length];
    commandApdu[0] = (byte)0x00;  // CLA
    commandApdu[1] = (byte)0xA4;  // INS
    commandApdu[2] = (byte)0x04;  // P1
    commandApdu[3] = (byte)0x00;  // P2
    commandApdu[4] = (byte)(aid.length & 0x0FF);       // Lc
    System.arraycopy(aid, 0, commandApdu, 5, aid.length);
    commandApdu[commandApdu.length - 1] = (byte)0x00;  // Le
    return commandApdu;
}

然后您可以将此类 APDU 命令发送到通过 reader-模式发现的 tag/HCE 设备 API:

public abstract void onTagDiscovered(Tag tag) {
    IsoDep isoDep = IsoDep.get(tag);
    if (isoDep != null) {
        try {
            isoDep.connect();
            byte[] result = isoDep.transceive(selectApdu(SelectAID));
        } except (IOException ex) {
        } finally {
            try {
                isoDep.close();
            } except (Exception ignored) {}
        }
    }
}