代码改变世界

NFC交互实现--hce卡模拟

2019-11-15 17:30  指针空间  阅读(3034)  评论(0编辑  收藏  举报

目前NFC应用的大的框架上的理解:

使用API LEVEL 19及以上,支持的API有三个:

android.nfc,android.nfc.cardemulator,android.nfc.tech

NFC在手机上的应用大体分为两类:读卡器和卡

android.nfc.cardemulator接口是为NFC作为卡应用提供的接口,在较低版本的API上是没有的android.nfc.techandroid.nfc接口是为NFC作为读卡器应用提供的接口

首先说作为卡,nfc有两种实现方式,一个是使用NFC芯片作为卡,另一个是使用SIM作为卡

 

 

Figure 1. NFC card emulation with a secure element.

 

至于从读卡器发送的指令到底是传递到NFC芯片还是SIMNFC Controler控制,图中Secure Element是指SIMHost-CPUNFC芯片

 

android提供HostApduService用于NFC芯片,OffHostApduService用于SIM芯片,传递方向在res/xml文件中通过AID来控制

psHost-Based Card Emulator 简称为HCE

 

代码实现:

AndroidManifest.xml 中 配置service,因为作为卡实现的话,NFC功能是作为service存在的

<service android:name=".CardService"
         android:exported="true"
         android:permission="android.permission.BIND_NFC_SERVICE">
    <!-- Intent filter indicating that we support card emulation. -->
    <intent-filter>
        <action android:name="android.nfc.cardemulation.action.HOST_APDU_SERVICE"/>
        <category android:name="android.intent.category.DEFAULT"/>
    </intent-filter>
    <!-- Required XML configuration file, listing the AIDs that we are emulating cards
         for. This defines what protocols our card emulation service supports. -->
    <meta-data android:name="android.nfc.cardemulation.host_apdu_service"
               android:resource="@xml/aid_list"/>
</service>

 

       

res/xml/aid_list.xml 中配置service响应的AID 

 

<?xml version="1.0" encoding="utf-8"?>

<host-apdu-service xmlns:android="http://schemas.android.com/apk/res/android"
    android:description="@string/service_name"
    android:requireDeviceUnlock="false">

<aid-group android:description="@string/card_title" android:category="other">
        <aid-filter android:name="F222222222"/>
  </aid-group>
</host-apdu-service>

android:requireDeviceUnlock="false"程序运行,手机亮屏不解锁的情况下,服务可以启动

 这一行很关键<aid-filter android:name="F222222222"/>

读卡器想要识别一个卡,肯定要有一个识别的标记,这个就是指定的识别标记,需要和代码中发送的指令进行统一, 必须偶数位

配置文件完成后编写service的处理方法:

CardService需要继承HostApduService交互逻辑在processCommandApdu方法中实现。交互的数据格式使用的是APDU指令格式。demo地址:

APDUApplication Protocol data unit,,是智能卡与智能卡读卡器之间传送的信息单元(向智能卡发送的命令)指令(ISO 7816-4规范有定义)

 

以上是Host-CPU方式的实现,SIM方式,API介绍中说该方式没有提供可供操作的API,也就是说Android不会监听SIM卡与读卡器之间的通信

 

所以NFCOffService 只需要实现onBind接口,这样绑定该ServiceActivity可以对NFCOffService进行有限操作

public class NFCOffService extends OffHostApduService {

    

    @Override

    public IBinder onBind(Intent intent) {

        // TODO Auto-generated method stub

        return null;

    }

 

}

参考链接:

https://blog.csdn.net/demon_w/article/details/50174737

https://blog.csdn.net/okletsgo007/article/details/46727831

apdu指令 

https://blog.csdn.net/wwt18811707971/article/details/85785354

 

 

service代码实现

/*
* Copyright (C) 2013 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

package com.example.android.cardemulation;

import android.nfc.cardemulation.HostApduService;
import android.os.Bundle;
import android.os.Environment;
import android.widget.Toast;

import com.example.android.common.logger.Log;

import java.io.File;
import java.util.Arrays;

/**
* This is a sample APDU Service which demonstrates how to interface with the card emulation support
* added in Android 4.4, KitKat.
*
* <p>This sample replies to any requests sent with the string "Hello World". In real-world
* situations, you would need to modify this code to implement your desired communication
* protocol.
*
* <p>This sample will be invoked for any terminals selecting AIDs of 0xF11111111, 0xF22222222, or
* 0xF33333333. See src/main/res/xml/aid_list.xml for more details.
*
* <p class="note">Note: This is a low-level interface. Unlike the NdefMessage many developers
* are familiar with for implementing Android Beam in apps, card emulation only provides a
* byte-array based communication channel. It is left to developers to implement higher level
* protocol support as needed.
*/
public class CardService extends HostApduService {
private static final String TAG = "CardService";
// AID for our loyalty card service.
private static final String SAMPLE_LOYALTY_CARD_AID = "F222222222";
// ISO-DEP command HEADER for selecting an AID.
// Format: [Class | Instruction | Parameter 1 | Parameter 2]
private static final String SELECT_APDU_HEADER = "00A40400";
// Format: [Class | Instruction | Parameter 1 | Parameter 2]
private static final String GET_DATA_APDU_HEADER = "00CA0000";
// "OK" status word sent in response to SELECT AID command (0x9000)
private static final byte[] SELECT_OK_SW = HexStringToByteArray("9000");
// "UNKNOWN" status word sent in response to invalid APDU command (0x0000)
private static final byte[] UNKNOWN_CMD_SW = HexStringToByteArray("0000");
private static final byte[] SELECT_APDU = BuildSelectApdu(SAMPLE_LOYALTY_CARD_AID);
private static final byte[] GET_DATA_APDU = BuildGetDataApdu();

private static final String WRITE_DATA_APDU_HEADER = "00DA0000";
private static final String READ_DATA_APDU_HEADER = "00EA0000";
private static final byte[] WRITE_DATA_APDU = BuildWriteDataApdu();
private static final byte[] READ_DATA_APDU = BuildReadDataApdu();
private static String dataStr = null;

/*File IO Stuffs*/
File sdcard = Environment.getExternalStorageDirectory();
File file = new File(sdcard,"file.txt");
StringBuilder text = new StringBuilder();
int pointer;

/**
* Called if the connection to the NFC card is lost, in order to let the application know the
* cause for the disconnection (either a lost link, or another AID being selected by the
* reader).
*
* @param reason Either DEACTIVATION_LINK_LOSS or DEACTIVATION_DESELECTED
*/
@Override
public void onDeactivated(int reason) { }

/**
* This method will be called when a command APDU has been received from a remote device. A
* response APDU can be provided directly by returning a byte-array in this method. In general
* response APDUs must be sent as quickly as possible, given the fact that the user is likely
* holding his device over an NFC reader when this method is called.
*
* <p class="note">If there are multiple services that have registered for the same AIDs in
* their meta-data entry, you will only get called if the user has explicitly selected your
* service, either as a default or just for the next tap.
*
* <p class="note">This method is running on the main thread of your application. If you
* cannot return a response APDU immediately, return null and use the {@link
* #sendResponseApdu(byte[])} method later.
*
* @param commandApdu The APDU that received from the remote device
* @param extras A bundle containing extra data. May be null.
* @return a byte-array containing the response APDU, or null if no response APDU can be sent
* at this point.
*/

@Override
public byte[] processCommandApdu(byte[] commandApdu, Bundle extras) {
Log.i(TAG, "Received APDU: " + ByteArrayToHexString(commandApdu));
byte[] cmd = null;
//length 6 is define by WRITE_DATA_APDU from read and emulatior
//长度由reader端及卡端的命令WRITE_DATA_APDU来协商的
if(commandApdu.length >= 6){
cmd = Arrays.copyOf(commandApdu,6);
}
// If the APDU matches the SELECT AID command for this service,
// send the loyalty card account number, followed by a SELECT_OK status trailer (0x9000).
if (Arrays.equals(SELECT_APDU, commandApdu)) {
String account = "some string random data";
byte[] accountBytes = account.getBytes();
Log.i(TAG, "Sending account number: " + account);
readFromFile();
return ConcatArrays(accountBytes, SELECT_OK_SW);
} else if ((Arrays.equals(GET_DATA_APDU, commandApdu))) {
String stringToSend;
try {
stringToSend = text.toString().substring(pointer, pointer + 200);
} catch (IndexOutOfBoundsException e) {
Toast.makeText(this, "Reached the end of the file", Toast.LENGTH_SHORT).show();
stringToSend = "END";
}
pointer += 200;byte[] accountBytes = stringToSend.getBytes();
Log.i(TAG, "Sending substring, pointer : " + pointer + " , " + stringToSend);
return ConcatArrays(accountBytes, SELECT_OK_SW);
} else if (cmd != null && Arrays.equals(WRITE_DATA_APDU, cmd)){
//length 6 is define by WRITE_DATA_APDU from read and emulatior
//长度由reader端及卡端的命令WRITE_DATA_APDU来协商的
byte[] data = Arrays.copyOfRange(commandApdu,6,commandApdu.length);
try {
dataStr = new String(data, "UTF-8");
Log.i(TAG, "dataStr:" + dataStr);
}catch (Exception e){
e.printStackTrace();
}
String account = "write success";
byte[] accountBytes = account.getBytes();
Log.i(TAG, "Sending account number: " + account);
return ConcatArrays(accountBytes, SELECT_OK_SW);
} else if (Arrays.equals(READ_DATA_APDU, cmd)){
if(dataStr!=null) {
byte[] accountBytes = dataStr.getBytes();
Log.i(TAG, "Sending account number: " + dataStr);
return ConcatArrays(accountBytes, SELECT_OK_SW);
}else {
byte[] accountBytes = "data error".getBytes();
Log.i(TAG, "Sending account number: " + dataStr);
return ConcatArrays(accountBytes, SELECT_OK_SW);
}
} else {
return UNKNOWN_CMD_SW;

}
}

/**
* Build APDU for SELECT AID command. This command indicates which service a reader is
* interested in communicating with. See ISO 7816-4.
*
* @param aid Application ID (AID) to select
* @return APDU for SELECT AID command
*/
public static byte[] BuildSelectApdu(String aid) {
// Format: [CLASS | INSTRUCTION | PARAMETER 1 | PARAMETER 2 | LENGTH | DATA]
return HexStringToByteArray(SELECT_APDU_HEADER + String.format("%02X",
aid.length() / 2) + aid);
}

/**
* Build APDU for GET_DATA command. See ISO 7816-4.
*
* @return APDU for SELECT AID command
*/
public static byte[] BuildGetDataApdu() {
// Format: [CLASS | INSTRUCTION | PARAMETER 1 | PARAMETER 2 | LENGTH | DATA]
return HexStringToByteArray(GET_DATA_APDU_HEADER + "0FFF");
}

/**
* Utility method to convert a byte array to a hexadecimal string.
*
* @param bytes Bytes to convert
* @return String, containing hexadecimal representation.
*/
public static String ByteArrayToHexString(byte[] bytes) {
final char[] hexArray = {'0','1','2','3','4','5','6','7','8','9','A','B','C','D','E','F'};
char[] hexChars = new char[bytes.length * 2]; // Each byte has two hex characters (nibbles)
int v;
for (int j = 0; j < bytes.length; j++) {
v = bytes[j] & 0xFF; // Cast bytes[j] to int, treating as unsigned value
hexChars[j * 2] = hexArray[v >>> 4]; // Select hex character from upper nibble
hexChars[j * 2 + 1] = hexArray[v & 0x0F]; // Select hex character from lower nibble
}
return new String(hexChars);
}

/**
* Utility method to convert a hexadecimal string to a byte string.
*
* <p>Behavior with input strings containing non-hexadecimal characters is undefined.
*
* @param s String containing hexadecimal characters to convert
* @return Byte array generated from input
* @throws java.lang.IllegalArgumentException if input length is incorrect
*/
public static byte[] HexStringToByteArray(String s) throws IllegalArgumentException {
int len = s.length();
if (len % 2 == 1) {
throw new IllegalArgumentException("Hex string must have even number of characters");
}
byte[] data = new byte[len / 2]; // Allocate 1 byte per 2 hex characters
for (int i = 0; i < len; i += 2) {
// Convert each character into a integer (base-16), then bit-shift into place
data[i / 2] = (byte) ((Character.digit(s.charAt(i), 16) << 4)
+ Character.digit(s.charAt(i+1), 16));
}
return data;
}

/**
* Utility method to concatenate two byte arrays.
* @param first First array
* @param rest Any remaining arrays
* @return Concatenated copy of input arrays
*/
public static byte[] ConcatArrays(byte[] first, byte[]... rest) {
int totalLength = first.length;
for (byte[] array : rest) {
totalLength += array.length;
}
byte[] result = Arrays.copyOf(first, totalLength);
int offset = first.length;
for (byte[] array : rest) {
System.arraycopy(array, 0, result, offset, array.length);
offset += array.length;
}
return result;
}

private void readFromFile() {
// try {
// BufferedReader br = new BufferedReader(new FileReader(file));
// String line;
//
// while ((line = br.readLine()) != null) {
// text.append(line);
// text.append('\n');
// }
// }
// catch (IOException e) {
// e.printStackTrace();
// }
text.append("some string random data some string random data some string random data some string random data some string random data \n");
text.append("some string random data some string random data some string random data some string random data some string random data \n");
text.append("some string random data some string random data some string random data some string random data some string random data \n");
text.append("some string random data some string random data some string random data some string random data some string random data \n");
text.append("some string random data some string random data some string random data some string random data some string random data \n");
text.append("some string random data some string random data some string random data some string random data some string random data \n");
}

public static byte[] BuildWriteDataApdu() {
// Format: [CLASS | INSTRUCTION | PARAMETER 1 | PARAMETER 2 | LENGTH | DATA]
return HexStringToByteArray(WRITE_DATA_APDU_HEADER + "0FFF");
}
public static byte[] BuildReadDataApdu() {
// Format: [CLASS | INSTRUCTION | PARAMETER 1 | PARAMETER 2 | LENGTH | DATA]
return HexStringToByteArray(READ_DATA_APDU_HEADER + "0FFF");
}

}


demo:git@github.com:zhan3080/NfcHCE-Reader-Emulation.git