智能卡发送和接收

对于连接,这里有一个片段可以帮助你理解:

//Allows you to enumerate and communicate with connected USB devices.
UsbManager mUsbManager = (UsbManager) getSystemService(Context.USB_SERVICE);
//Explicitly asking for permission
final String ACTION_USB_PERMISSION = "com.android.example.USB_PERMISSION";
PendingIntent mPermissionIntent = PendingIntent.getBroadcast(this, 0, new Intent(ACTION_USB_PERMISSION), 0);
HashMap<String, UsbDevice> deviceList = mUsbManager.getDeviceList();

UsbDevice device = deviceList.get("//the device you want to work with");
if (device != null) {
    mUsbManager.requestPermission(device, mPermissionIntent);
}

现在你必须要了解,在 java 中,通过使用不能用于 Android 的包 javax.smarcard 进行通信,所以看看这里是为了了解如何通信或发送/接收 APDU(智能卡命令)。

现在正如上面提到的答案所述

你不能简单地通过批量输出端点发送 APDU(智能卡命令),并期望通过批量输入端点接收响应 APDU。要获取端点,请参阅下面的代码段:

UsbEndpoint epOut = null, epIn = null;
UsbInterface usbInterface;

UsbDeviceConnection connection = mUsbManager.openDevice(device);

    for (int i = 0; i < device.getInterfaceCount(); i++) {
        usbInterface = device.getInterface(i);
        connection.claimInterface(usbInterface, true);

        for (int j = 0; j < usbInterface.getEndpointCount(); j++) {
            UsbEndpoint ep = usbInterface.getEndpoint(j);

            if (ep.getType() == UsbConstants.USB_ENDPOINT_XFER_BULK) {
                if (ep.getDirection() == UsbConstants.USB_DIR_OUT) {
                    // from host to device
                    epOut = ep;

                } else if (ep.getDirection() == UsbConstants.USB_DIR_IN) {
                    // from device to host
                    epIn = ep;
                }
            }
        }
    }

现在你有了批量输入和批量输出端点来发送和接收 APDU 命令和 APDU 响应块:

有关发送命令的信息,请参阅下面的代码段:

public void write(UsbDeviceConnection connection, UsbEndpoint epOut, byte[] command) {
    result = new StringBuilder();
    connection.bulkTransfer(epOut, command, command.length, TIMEOUT);
    //For Printing logs you can use result variable
    for (byte bb : command) {
        result.append(String.format(" %02X ", bb));
    }
}

要获得/阅读回复,请参阅下面的代码段:

public int read(UsbDeviceConnection connection, UsbEndpoint epIn) {
result = new StringBuilder();
final byte[] buffer = new byte[epIn.getMaxPacketSize()];
int byteCount = 0;
byteCount = connection.bulkTransfer(epIn, buffer, buffer.length, TIMEOUT);

//For Printing logs you can use result variable
if (byteCount >= 0) {
    for (byte bb : buffer) {
        result.append(String.format(" %02X ", bb));
    }

    //Buffer received was : result.toString()
} else {
    //Something went wrong as count was : " + byteCount
}

return byteCount;
}

现在,如果你在此处看到此答案,则要发送的第一个命令是:

PC_to_RDR_IccPowerOn 命令用于激活卡。

你可以通过阅读 USB 设备类规范文档的 6.1.1 节创建。

现在让我们举一个这个命令的例子,如下所示:62000000000000000000 如何发送它是:

write(connection, epOut, "62000000000000000000");

现在,在成功发送 APDU 命令后,你可以使用以下命令读取响应:

read(connection, epIn);

并收到类似的东西

80 18000000 00 00 00 00 00 3BBF11008131FE45455041000000000000000000000000F1

现在,代码中收到的响应将来自代码中的 read() 方法的 result 变量