如何以编程方式使用 android 中的智能卡 reader 读取智能卡/微处理器卡

How to read a smart card/ microprocessor card using a smart card reader in android programmatically

所以最近我一直在使用包含一些信息的智能卡,我在这里想要实现的是使用智能卡 reader 通过任何 [=66= 从这些智能卡中获取这些数据] 手机。 我一直在使用 HID OMNIKEY 3021 USB 智能卡 reader 来读取这些卡(而且我知道这个 reader 通过 windows 应用程序与这些卡一起工作,因为我已经亲自测试过这个)

现在 Android 提供 USB Host 可以读取任何 USB 主机,前提是 Android 智能手机支持它。

我正在尝试使用 USB 主机提供的这些 类 来访问此卡中的数据。

我检测任何 USB 主机的代码:

private static final String ACTION_USB_PERMISSION = "com.android.example.USB_PERMISSION";
PendingIntent mPermissionIntent = PendingIntent.getBroadcast(this, 0, new Intent(ACTION_USB_PERMISSION), 0);

IntentFilter filter = new IntentFilter(ACTION_USB_PERMISSION);
registerReceiver(mUsbReceiver, filter);

IntentFilter attachedFilter = new IntentFilter(UsbManager.ACTION_USB_DEVICE_ATTACHED);
registerReceiver(mUsbAttachedReceiver, attachedFilter);

private final BroadcastReceiver mUsbAttachedReceiver = new BroadcastReceiver() {
    @Override
    public void onReceive(Context context, Intent intent) {
        String action = intent.getAction();
        Utils.writeStringToTextFile("\n1 .Get an action : " + action, FileName);
        if (UsbManager.ACTION_USB_DEVICE_ATTACHED.equals(action)) {
            synchronized (this) {
                device = intent.getParcelableExtra(UsbManager.EXTRA_DEVICE);
                if (device != null) {
                    showToast("Plugged In");
                    mUsbManager.requestPermission(device, mPermissionIntent);
                }
            }
        } else if (UsbManager.ACTION_USB_DEVICE_DETACHED.equals(action)) {
            UsbDevice device = intent.getParcelableExtra(UsbManager.EXTRA_DEVICE);
            if (device != null) {
                showToast("Plugged Out");
                // call your method that cleans up and closes communication with the device
            }
        }
    }
};

private final BroadcastReceiver mUsbReceiver = new BroadcastReceiver() {

    public void onReceive(Context context, Intent intent) {
        String action = intent.getAction();
        if (ACTION_USB_PERMISSION.equals(action)) {
            synchronized (this) {
                device = intent.getParcelableExtra(UsbManager.EXTRA_DEVICE);

                if (intent.getBooleanExtra(UsbManager.EXTRA_PERMISSION_GRANTED, false)) {
                    if (device != null) {
                        //call method to set up device communication
                        Utils.writeStringToTextFile("2 .Get an action : " + action + "\nDevice is : " + device, FileName);
                        showToast("Permission Granted for device");

                        Handler h = new Handler();
                        h.postDelayed(run, 1000);

                    }
                } else {
                    showToast("Permission denied for device" + device);
                }
            }
        }
    }
};

一切都按预期工作,因为我得到 UsbDevice device 给出了设备信息,例如:

Device is : UsbDevice[mName=/dev/bus/usb/001/002,mVendorId=1899,mProductId=12322,mClass=0,mSubclass=0,mProtocol=0,mManufacturerName=OMNIKEY AG,mProductName=Smart Card Reader USB,mVersion=2.0,mSerialNumber=null,mConfigurations=[
UsbConfiguration[mId=1,mName=CCID,mAttributes=160,mMaxPower=50,mInterfaces=[
UsbInterface[mId=0,mAlternateSetting=0,mName=null,mClass=11,mSubclass=0,mProtocol=0,mEndpoints=[
UsbEndpoint[mAddress=131,mAttributes=3,mMaxPacketSize=8,mInterval=24]
UsbEndpoint[mAddress=132,mAttributes=2,mMaxPacketSize=64,mInterval=0]
UsbEndpoint[mAddress=5,mAttributes=2,mMaxPacketSize=64,mInterval=0]]]]

现在我正尝试使用此 UsbDevice device 从卡中获取数据和详细信息,但我没有成功,而且我找不到任何有用的信息 post。

我知道我必须使用 UsbInterfaceUsbEndpointUsbDeviceConnection 从卡中获取我想要的东西,但我无法这样做。

此外,我找不到任何样本或类似的东西。 谁能指出我正确的方向?

抱歉这么久了 post 也提前致谢 :)

编辑: 感谢 Mr. Michael Roland,我能够阅读有关 CCID 的信息,因为 reader 设备通过 USB 接口使用 CCID。

所以我使用了以下代码:

        UsbDeviceConnection connection = mUsbManager.openDevice(device);
        UsbEndpoint epOut = null, epIn = null;

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

            for (int j = 0; j < usbInterface.getEndpointCount(); j++) {
                UsbEndpoint ep = usbInterface.getEndpoint(j);
                showToast("Endpoint is : " + ep.toString() + " endpoint's type : " + ep.getType() + " endpoint's direction : " + ep.getDirection());
                Log.d(" ", "EP " + i + ": " + ep.getType());
                if (ep.getType() == UsbConstants.USB_ENDPOINT_XFER_BULK) {
                    if (ep.getDirection() == UsbConstants.USB_DIR_OUT) {
                        epOut = ep;

                    } else if (ep.getDirection() == UsbConstants.USB_DIR_IN) {
                        epIn = ep;
                    }

                }
            }

            int dataTransferred = 0;
            byte[] PC_to_RDR_IccPowerOn = hexStringToByteArray("62" + "00000000" + "00" + "00" + "00" + "0000");

            if (epOut != null) {
                //Firstly send Power in on Bulk OUT endpoint
                dataTransferred = connection.bulkTransfer(epOut, PC_to_RDR_IccPowerOn, PC_to_RDR_IccPowerOn.length, TIMEOUT);
            }

            StringBuilder result = new StringBuilder();

            if (epIn != null) {
                final byte[] RDR_to_PC_DataBlock = new byte[epIn.getMaxPacketSize()];
                result = new StringBuilder();
                //Secondly send Power out on Bulk OUT endpoint
                dataTransferred = connection.bulkTransfer(epIn, RDR_to_PC_DataBlock, RDR_to_PC_DataBlock.length, TIMEOUT);
                for (byte bb : RDR_to_PC_DataBlock) {
                    result.append(String.format(" %02X ", bb));
                }

                if (dataTransferred > 0) {
                    Utils.writeStringToTextFile("\n2nd buffer received was : " + result.toString(), "Card_communication_data.txt");
                    String s1 = Arrays.toString(RDR_to_PC_DataBlock);
                    String s2 = new String(RDR_to_PC_DataBlock);
                    showToast("received - " + s1 + " - " + s2);
                } else {
                    showToast("received length at 2nd buffer transfer was " + dataTransferred);
                }
            }
        }

我收到了 80 13 00 00 00 00 00 00 00 00 3B 9A 96 C0 10 31 FE 5D 00 64 05 7B 01 02 31 80 90 00 76 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 但我仍然不确定如何处理数据字段:ATR 或如何为 PC_to_RDR_XfrBlock 命令形成 Command APDU..

我想我应该

Send command APDU wrapped into PC_to_RDR_XfrBlock command

现在;谁能帮我解决这个问题?

编辑 2: 我弄清楚了 ATR 的含义以及如何形成命令 APDU。

但现在我应该切换协议

The default Protocol is T=0. To set the T=1 protocol, a PTS (also known as PPS) must be sent to the card by the device As both T=0 and T=1 protocols are mandatory for the card, the basic PTS for protocol switching is mandatory for the card. The PTS can be used, as indicated in ISO/IEC 7816-3, to switch to higher baud rates than the default one proposed by the card in the ATR if any (TA(1) byte).

我不确定这意味着什么以及如何实现!!

典型的 USB 智能卡读卡器实现 USB CCID device class specification. Consequently, you need to implement that protocol in your application in order to communicate with the reader (and the card). See Communicate with smartcard reader through Android USB host 作为(部分工作的)起点,了解如何实现它。

由于没有合适的指南或任何示例列出可以遵循的基本步骤,所以这里是我设法交流的方式(这更像是一个菜鸟指南,如果我错了请纠正我): 首先使用 USB Host API 我能够通过智能卡 reader.

连接到智能卡

为了连接,这里有一个片段可以帮助您理解:

    //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 中,通信是使用 package javax.smarcard which is not available for Android so take a look here 进行的,以了解如何通信或 send/receive APDU(智能卡命令)。

现在如上述回答所述

You cannot simply send an APDU (smartcard command) over the bulk-out endpoint and expect to receive a response APDU over the bulk-in endpoint.

要获取端点,请参阅下面的代码片段:

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;
}

现在,如果您看到 this answer here,要发送的第一个命令是:

PC_to_RDR_IccPowerOn命令激活卡

您可以通过阅读 USB Device Class Specifications doc here 的第 6.1.1 节来创建。

现在让我们举一个像这里这样的命令的例子:62000000000000000000 发送方式是:

write(connection, epOut, "62000000000000000000");

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

read(connection, epIn);

并收到类似

的东西

80 18000000 00 00 00 00 00 3BBF11008131FE45455041000000000000000000000000F1

现在,此处代码中收到的响应将位于上面代码中 read() 方法的 result 变量中,您可以使用该代码从相同的 [=] 中获取 Data field: ATR 24=]

你必须know/read了解如何阅读这个ATR,它可以用来检测卡的类型和其他东西,比如它是否正在使用T0 或 T1 协议然后什么是 TA(1) 可以告诉 FI Index into clock conversion factor tableDI Index into Baud rate adjustment factor table 等等

Check this website 用于解析 ATR.

现在如果你想切换协议说 T0T1 即发送 PPS/PTS 或者你想设置任何参数,那么你可以使用 PC_to_RDR_SetParameters 命令(document 的第 6.1.7 节)。

在我的例子中,从 T0 切换到 T1PPS/PTS 示例是:"61 00000007 00 00 01 0000 9610005D00FE00" .

这将给出一些结果,例如:"82 07000000 00 00 00 00 01 96 10 00 5D 00 FE 00"。你用 RDR_to_PC_Parametersdocument 的第 6.2.3 节)

检查

有关此命令的详细信息,请参阅 CCID protocol Document 的第 6.1.7 节。 我能够使用从 ATR 块接收到的详细信息来形成此命令,然后使用 write() 方法发送命令,然后使用 read() 方法读取响应。

还可以选择任何文件或发送任何命令,您可以使用 PC_to_RDR_XfrBlock 使用 write() 方法发送,然后使用 [= 接收响应22=] 代码中的方法。您也可以在 read() 方法中更改要读取的 btyes 的编号。

记得使用线程进行通信,也read here获得更多提示。