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

时间:2018-07-13 18:34:02

标签: android nfc apdu contactless-smartcard hce

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

我已经创建了我的HCE服务,以使用响应APDU进行响应,如以下线程所示:How to define an APDU for STORE DATA for Host Card Emulation?

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

1 个答案:

答案 0 :(得分:2)

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

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

您可以这样创建它:

import {Directive, ElementRef, Output, EventEmitter, HostListener} from '@angular/core';

@Directive({
    selector: '[clickOutside]'
})
export class ClickOutsideDirective {
    constructor(private elementRef: ElementRef) {
    }

    @Output()
    public clickOutside = new EventEmitter<MouseEvent>();

    @HostListener('document:click', ['$event', '$event.target'])
    public onClick(event: MouseEvent, targetElement: HTMLElement): void {
        if (!targetElement) {
            return;
        }

        const clickedInside = this.elementRef.nativeElement.contains(targetElement);
        if (!clickedInside) {
            this.clickOutside.emit(event);
        }
    }
}

然后您可以将这样的APDU命令发送到通过阅读器模式API找到的标签/ HCE设备:

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