1. 程式人生 > >Android使用NFC模擬M卡實現 (一)

Android使用NFC模擬M卡實現 (一)

 

在百度找一遍,沒有一篇,講的比較通俗易懂的檔案。講解Android 的NFC 功能 card emulation。

略有點用的附在下面。

參考:
安卓 NFC 主機卡模擬
來自 <https://blog.csdn.net/chenyuebo11/article/details/54894296> 

修改配置檔案方式
Android使用NFC模擬IC卡
來自 <https://blog.csdn.net/qq_21051503/article/details/73064910>
Android使用NFC模擬IC卡
來自 <https://blog.csdn.net/chenhao0428/article/details/51917634>

自己動手,豐衣足食。那首先就得看官方的文件。

https://developer.android.google.cn/guide/topics/connectivity/nfc/hce

那就的細看,都翻譯下。我的半桶水英語水平,向谷歌翻譯借力。

如果想了解具體的,必須細看本文,只想結果,只想擼,那就看我的另篇:Android使用NFC模擬M卡實現 (二)

原文全拷過來,進行翻譯備註,此次文件是API 28,勉強作下面官方翻譯。

Host-based card emulation overview

基於主機的卡模擬概述

Many Android-powered devices that offer NFC functionality already support NFC card emulation. In most cases, the card is emulated by a separate chip in the device, called a secure element

. Many SIM cards provided by wireless carriers also contain a secure element.

許多的Android裝置提供NFC功能已經支援NFC卡模擬。在大多數情況下,卡的模擬在裝置中有單獨晶片,稱為安全元件。無線運營商提供的許多SIM卡也包含安全元件。

Android 4.4 introduces an additional method of card emulation that does not involve a secure element, called host-based card emulation

. This allows any Android application to emulate a card and talk directly to the NFC reader. This document describes how host-based card emulation (HCE) works on Android and how you can develop an app that emulates an NFC card using this technique.

Android4.4引入了另一種卡模擬方法,該方法不涉及稱為基於主機的卡模擬的安全元素。這允許任何Android應用程式模擬卡並直接與NFC閱讀器對話。本文件介紹了基於主機的卡模擬(HCE)如何在Android上執行,以及如何使用此技術開發模擬NFC卡的應用程式。

Card Emulation with a secure element

具有安全元素的卡模擬

When NFC card emulation is provided using a secure element, the card to be emulated is provisioned into the secure element on the device through an Android application. Then, when the user holds the device over an NFC terminal, the NFC controller in the device routes all data from the reader directly to the secure element. Figure 1 illustrates this concept.

當使用安全元件提供NFC卡模擬時,要模擬的卡通過Android應用程式提供到裝置上的安全元件中。然後,當用戶將裝置保持在NFC終端上時,裝置中的NFC控制器將來自讀取器的所有資料直接路由到安全元件。

Figure 1. NFC card emulation with a secure element.

圖1說明了這個概念。

The secure element itself performs the communication with the NFC terminal, and no Android application is involved in the transaction at all. After the transaction is complete, an Android application can query the secure element directly for the transaction status and notify the user.

安全元件本身執行與NFC終端的通訊,並且交易中根本不涉及Android應用程式。事務完成後,Android應用程式可以直接查詢安全元素以獲取事務狀態並通知使用者。

Host-based card emulation

基於主機的卡模擬

When an NFC card is emulated using host-based card emulation, the data is routed to the host CPU on which Android applications are running directly, instead of routing the NFC protocol frames to a secure element. Figure 2 illustrates how host-based card emulation works.

使用基於主機的卡模擬模擬NFC卡時,資料將路由到直接執行Android應用程式的主機CPU,而不是將NFC協議幀路由到安全元件。圖2說明了基於主機的卡模擬的工作原理。

Figure 2. NFC card emulation without a secure element.

圖2.沒有安全元件的NFC卡模擬。

 

Supported NFC cards and protocols

支援的NFC卡和協議

The NFC standards offer support for many different protocols, and there are different types of cards that can be emulated.

NFC標準提供對許多不同協議的支援,並且可以模擬不同型別的卡。

Android 4.4 supports several protocols that are common in the market today. Many existing contactless cards are already based on these protocols, such as contactless payment cards. These protocols are also supported by many NFC readers in the market today, including Android NFC devices functioning as readers themselves (see the IsoDep class). This allows you to build and deploy an end-to-end NFC solution around HCE using only Android-powered devices.

Android 4.4支援當今市場上常見的幾種協議。許多現有的非接觸式卡已經基於這些協議,例如非接觸式支付卡。當今市場上的許多NFC閱讀器也支援這些協議,包括作為閱讀器本身的Android NFC裝置(參見IsoDep課程)。這使您可以僅使用Android驅動的裝置圍繞HCE構建和部署端到端NFC解決方案。

Specifically, Android 4.4 supports emulating cards that are based on the NFC-Forum ISO-DEP specification (based on ISO/IEC 14443-4) and process Application Protocol Data Units (APDUs) as defined in the ISO/IEC 7816-4 specification. Android mandates emulating ISO-DEP only on top of the Nfc-A (ISO/IEC 14443-3 Type A) technology. Support for Nfc-B (ISO/IEC 14443-4 Type B) technology is optional. The layering of all these specifications is shown in the figure 3.

具體而言,Android 4.4支援模擬基於NFC論壇ISO-DEP規範(基於ISO / IEC 14443-4)和ISO / IEC 7816-4規範中定義的處理應用協議資料單元(APDU)的卡。Android要求僅在Nfc-A(ISO / IEC 14443-3 A類)技術之上模擬ISO-DEP。支援Nfc-B(ISO / IEC 14443-4 B類)技術是可選的。所有這些規範的分層如圖3所示。

 

Figure 3. Android's HCE protocol stack.

圖3. Android的HCE協議棧。

HCE services

HCE服務 【即Host-based card emulation services

The HCE architecture in Android is based around Android Service components (known as "HCE services"). One of the key advantages of a service is that it can run in the background without any user interface. This is a natural fit for many HCE applications like loyalty or transit cards, with which the user shouldn't need to launch the app to use it. Instead, tapping the device against the NFC reader starts the correct service (if not already running) and executes the transaction in the background. Of course, you are free to launch additional UI (such as user notifications) from your service if that makes sense.

Android中的HCE架構基於Android Service元件(稱為“HCE服務”)。服務的一個主要優點是它可以在後臺執行而無需任何使用者介面。這很適合許多HCE應用程式,如忠誠度[優惠]卡或轉接[交通]卡,使用者無需啟動應用程式即可使用它。相反,在NFC閱讀器上點選裝置會啟動正確的服務(如果尚未執行)並在後臺執行事務。當然,如果有意義,您可以自由地從服務中啟動其他UI(例如使用者通知)。

Service selection

服務選擇

When the user taps a device to an NFC reader, the Android system needs to know which HCE service the NFC reader actually wants to talk to. This is where the ISO/IEC 7816-4 specification comes in: it defines a way to select applications, centered around an Application ID (AID). An AID consists of up to 16 bytes. If you are emulating cards for an existing NFC reader infrastructure, the AIDs that those readers are looking for are typically well-known and publicly registered (for example, the AIDs of payment networks such as Visa and MasterCard).

當用戶將裝置輕敲到NFC讀取器時,Android系統需要知道NFC讀取器實際想要與哪個HCE服務通訊。這就是ISO / IEC 7816-4規範的用武之地:它定義了一種以應用程式ID(AID)為中心選擇應用程式的方法。AID最多包含16個位元組。如果您要模擬現有NFC讀卡器基礎設施的卡,那些讀者正在尋找的AID通常是眾所周知的並且是公開註冊的(例如,支付網路的AID,例如Visa和MasterCard)。

If you want to deploy new reader infrastructure for your own application, you will need to register your own AID(s). The registration procedure for AIDs is defined in the ISO/IEC 7816-5 specification. Google recommends registering an AID as per 7816-5 if you are deploying a HCE application for Android, as it will avoid collisions with other applications.

如果要為自己的應用程式部署新的閱讀器基礎結構,則需要註冊自己的AID。AID的註冊程式在ISO / IEC 7816-5規範中定義。如果您要為Android部署HCE應用程式,Google建議按照7816-5註冊AID,因為這樣可以避免與其他應用程式發生衝突。

AID groups

AID組

In some cases, an HCE service may need to register multiple AIDs to implement a certain application, and it needs to be sure that it is the default handler for all of these AIDs (as opposed to some AIDs in the group going to another service).

在某些情況下,HCE服務可能需要註冊多個AID來實現某個應用程式,並且需要確保它是所有這些AID的預設處理程式(而不是該組中的某些AID轉到另一個服務) 。

An AID group is a list of AIDs that should be considered as belonging together by the OS. For all AIDs in an AID group, Android guarantees one of the following:

AID組是應被視為OS所屬的AID列表。對於AID組中的所有AID,Android保證以下其中一項:

  • All AIDs in the group are routed to this HCE service
  • 組中的所有AID都路由到[對應]HCE服務
  • No AIDs in the group are routed to this HCE service (for example, because the user preferred another service which requested one or more AIDs in your group as well)
  • 組中沒有AID被路由到此HCE服務(例如,因為使用者更喜歡在您的組中請求一個或多個AID的另一個服務)

In other words, there is no in-between state, where some AIDs in the group can be routed to one HCE service, and some to another.

換句話說,沒有中間狀態,其中組中的一些AID可以路由到一個HCE服務,一些到另一個。

AID groups and categories

AID組和類別

Each AID group can be associated with a category. This allows Android to group HCE services together by category, and that in turn allows the user to set defaults at the category level instead of the AID level. In general, avoid mentioning AIDs in any user-facing parts of your application: they do not mean anything to the average user.

每個AID組可以與一個類別相關聯。這允許Android按類別將HCE服務組合在一起,這反過來允許使用者在類別級別而不是AID級別設定預設值。通常,避免在應用程式的任何面向使用者的部分中提及AID:它們對普通使用者沒有任何意義。

Android 4.4 supports two categories: CATEGORY_PAYMENT (covering industry-standard payment apps) and CATEGORY_OTHER (for all other HCE apps).

Android 4.4支援兩類:( CATEGORY_PAYMENT涵蓋行業標準支付應用)和CATEGORY_OTHER (適用於所有其他HCE應用)。

Note: Only one AID group in the CATEGORY_PAYMENT category may be enabled in the system at any given time. Typically, this will be an app that understands major credit card payment protocols and which can work at any merchant.

注意:CATEGORY_PAYMENT在任何給定時間,系統中只能啟用 該類別中的一個AID組。通常情況下,這將是一個瞭解主要信用卡支付協議的應用程式,可以在任何商家工作。

For closed-loop payment apps that only work at one merchant (such as stored-value cards), you should use CATEGORY_OTHER. AID groups in this category can be always active, and can be given priority by NFC readers during AID selection if necessary.

對於僅在一個商家(例如儲值卡)工作的閉環支付應用,您應該使用CATEGORY_OTHER。此類別中的AID組可以始終處於活動狀態,並且如果需要,可以在AID選擇期間由NFC讀取器給予優先順序。

Implementing an HCE service

實[現]HCE服務

To emulate an NFC card using host-based card emulation, you need to create a Service component that handles the NFC transactions.

要使用基於主機的卡模擬模擬NFC卡,您需要建立一個Service處理NFC事務的元件。

Checking for HCE support

檢查HCE支援

Your application can check whether a device supports HCE by checking for the FEATURE_NFC_HOST_CARD_EMULATIONfeature. You should use the <uses-feature> tag in the manifest of your application to declare that your app uses the HCE feature, and whether it is required for the app to function or not.

您的應用程式可以通過檢查FEATURE_NFC_HOST_CARD_EMULATION功能來檢查裝置是否支援HCE 。您應該使用<uses-feature>應用程式清單中的 標記來宣告您的應用程式使用HCE功能,以及應用程式是否需要執行。

上面這些講的,是在功能清單檔案中,新增下面幾個。AndroidManifes.mxl
<!--API 9 裝置可以使用近場通訊(NFC)進行通訊。-->
<!--<uses-feature android:name="android.hardware.nfc" android:required="true">-->
<!--API 19 該裝置支援基於主機的NFC卡模擬。-->
<!--<uses-feature android:name="android.hardware.nfc.hcef" android:required="true" />-->
<!--API 24 該裝置支援基於主機的NFC-F卡模擬。-->
<!--<uses-feature android:name="android.hardware.nfc.hce" android:required="true" />-->

Service implementation

服務實施

Android 4.4 comes with a convenience Service class that can be used as a basis for implementing a HCE service: the HostApduService class.

Android 4.4帶有一個便利Service類,可以作為實現HCE服務的基礎:HostApduService類。

The first step is therefore to extend HostApduService.

因此,第一步是擴充套件HostApduService

JAVA實現,KOTLIN略。

public class MyHostApduService extends HostApduService {
    @Override
    public byte[] processCommandApdu(byte[] apdu, Bundle extras) {
       ...
    }
    @Override
    public void onDeactivated(int reason) {
       ...
    }
}

 

HostApduService declares two abstract methods that need to be overridden and implemented.

HostApduService 宣告需要重寫和實現的兩個抽象方法。

processCommandApdu() is called whenever a NFC reader sends an Application Protocol Data Unit (APDU) to your service. APDUs are defined in the ISO/IEC 7816-4 specification as well. APDUs are the application-level packets being exchanged between the NFC reader and your HCE service. That application-level protocol is half-duplex: the NFC reader will send you a command APDU, and it will wait for you to send a response APDU in return.

processCommandApdu() 只要NFC閱讀器向您的服務傳送應用程式協議資料單元(APDU),就會呼叫此方法。APDU也在ISO / IEC 7816-4規範中定義。APDU是NFC讀取器和HCE服務之間交換的應用程式級資料包。該應用程式級協議是半雙工的:NFC讀取器將向您傳送命令APDU,它將等待您傳送響應APDU作為回報。

 

Note: The ISO/IEC 7816-4 specification also defines the concept of multiple logical channels, where you can have multiple parallel APDU exchanges on separate logical channels. Android’s HCE implementation however only supports a single logical channel, so there’s only a single-threaded exchange of APDUs.

注: ISO / IEC 7816-4規範還定義了多個邏輯通道的概念,您可以在不同的邏輯通道上進行多個並行APDU交換。然而,Android的HCE實現僅支援單個邏輯通道,因此只有APDU的單執行緒交換。

As mentioned previously, Android uses the AID to determine which HCE service the reader wants to talk to. Typically, the first APDU an NFC reader sends to your device is a "SELECT AID" APDU; this APDU contains the AID that the reader wants to talk to. Android extracts that AID from the APDU, resolves it to an HCE service, then forwards that APDU to the resolved service.

如前所述,Android使用AID來確定讀者想要與之通訊的HCE服務。通常,NFC讀取器傳送到您的裝置的第一個APDU是“SELECT AID”APDU; 此APDU包含讀者想要與之交談的AID。Android從APDU中提取該AID,將其解析為HCE服務,然後將該APDU轉發到已解析的服務。

You can send a response APDU by returning the bytes of the response APDU from processCommandApdu(). Note that this method will be called on the main thread of your application, which shouldn't be blocked. So if you can't compute and return a response APDU immediately, return null. You can then do the necessary work on another thread, and use the sendResponseApdu() method defined in the HostApduService class to send the response when you are done.

您可以通過返回響應APDU的位元組來發送響應APDU processCommandApdu()。請注意,此方法將在應用程式的主執行緒上呼叫,不應阻止。因此,如果您無法立即計算並返回響應APDU,則返回null。然後,您可以在另一個執行緒上執行必要的工作,並使用類中sendResponseApdu()定義的方法在完成HostApduService後傳送響應。

Android will keep forwarding new APDUs from the reader to your service, until either:

  1. The NFC reader sends another "SELECT AID" APDU, which the OS resolves to a different service;
  2. The NFC link between the NFC reader and your device is broken.

Android將繼續從閱讀器向您的服務轉發新的APDU,直到:

  1. NFC讀取器傳送另一個“SELECT AID”APDU,OS解析為另一個服務;
  2. NFC讀卡器與您的裝置之間的NFC連結已斷開。

In both of these cases, your class's onDeactivated() implementation is called with an argument indicating which of the two happened.

在這兩種情況下,onDeactivated() 都會呼叫類的 實現,並帶有一個引數,指示兩者中的哪一個發生了。

If you are working with existing reader infrastructure, you need to implement the existing application-level protocol that the readers expect in your HCE service.

如果您正在使用現有的閱讀器基礎結構,則需要實現讀者期望在HCE服務中使用的現有應用程式級協議。

If you are deploying new reader infrastructure which you control as well, you can define your own protocol and APDU sequence. In general try to limit the amount of APDUs and the size of the data that needs to be exchanged: this makes sure that your users will only have to hold their device over the NFC reader for a short amount of time. A reasonable upper bound is about 1KB of data, which can usually be exchanged within 300ms.

如果您正在部署您控制的新讀卡器基礎結構,則可以定義自己的協議和APDU序列。通常嘗試限制APDU的數量和需要交換的資料的大小:這可以確保您的使用者只需要在短時間內將裝置放在NFC讀取器上。合理的上限是大約1KB的資料,通常可以在300ms內交換。

Service manifest declaration and AID registration

服務清單宣告和AID註冊

Your service must be declared in the manifest as usual, but some additional pieces must be added to the service declaration as well.

您的服務必須照常在清單中宣告,但也必須在服務宣告中新增一些其他部分。

First, to tell the platform that it is a HCE service implementing a HostApduService interface, your service declaration must contain an intent filter for the SERVICE_INTERFACE action.

首先,要告訴平臺它是實現HostApduService介面的HCE服務 ,您的服務宣告必須包含該SERVICE_INTERFACE操作的intent過濾器。

Additionally, to tell the platform which AIDs groups are requested by this service, a SERVICE_META_DATA <meta-data>tag must be included in the declaration of the service, pointing to an XML resource with additional information about the HCE service.

另外,為了告訴平臺該服務請求哪些AID組,SERVICE_META_DATA <meta-data>必須在服務宣告中包含標記,指向具有關於HCE服務的附加資訊的XML資源。

Finally, you must set the android:exported attribute to true, and require the"android.permission.BIND_NFC_SERVICE" permission in your service declaration. The former ensures that the service can be bound to by external applications. The latter then enforces that only external applications that hold the"android.permission.BIND_NFC_SERVICE" permission can bind to your service. Since"android.permission.BIND_NFC_SERVICE" is a system permission, this effectively enforces that only the Android OS can bind to your service.

最後,您必須將該android:exported屬性設定為true,並"android.permission.BIND_NFC_SERVICE"在服務宣告中要求 許可權。前者確保服務可以由外部應用程式繫結。然後,後者強制只有擁有"android.permission.BIND_NFC_SERVICE"許可權的外部應用程式 才能繫結到您的服務。由於"android.permission.BIND_NFC_SERVICE"是系統許可權,這有效地強制了只有Android作業系統才能繫結到您的服務。

Here's an example of a HostApduService manifest declaration:

這是一個HostApduService清單宣告的示例:

<service android:name=".MyHostApduService" android:exported="true"
         android:permission="android.permission.BIND_NFC_SERVICE">
    <intent-filter>
        <action android:name="android.nfc.cardemulation.action.HOST_APDU_SERVICE"/>
    </intent-filter>
    <meta-data android:name="android.nfc.cardemulation.host_apdu_service"
               android:resource="@xml/apduservice"/>
</service>

This meta-data tag points to an apduservice.xml file. An example of such a file with a single AID group declaration containing two proprietary AIDs is shown below:

此元資料標記指向apduservice.xml檔案。具有包含兩個專有AID的單個AID組宣告的此類檔案的示例如下所示:

<host-apdu-service xmlns:android="http://schemas.android.com/apk/res/android"
           android:description="@string/servicedesc"
           android:requireDeviceUnlock="false">
    <aid-group android:description="@string/aiddescription"
               android:category="other">
        <aid-filter android:name="F0010203040506"/>
        <aid-filter android:name="F0394148148100"/>
    </aid-group>
</host-apdu-service>

The <host-apdu-service> tag is required to contain a <android:description> attribute that contains a user-friendly description of the service that may be shown in UI. The requireDeviceUnlock attribute can be used to specify that the device must be unlocked before this service can be invoked to handle APDUs.

<host-apdu-service>標籤需要包含一個<android:description> 包含了可在使用者介面中顯示的服務的使用者友好的描述屬性。該requireDeviceUnlock屬性可用於指定在呼叫此服務以處理APDU之前必須解鎖裝置。

 

The <host-apdu-service> must contain one or more <aid-group> tags. Each <aid-group> tag is required to:

  • Contain an android:description attribute that contains a user-friendly description of the AID group, suitable for display in UI.
  • Have its android:category attribute set to indicate the category the AID group belongs to, e.g. the string constants defined by CATEGORY_PAYMENT or CATEGORY_OTHER.
  • Each <aid-group> must contain one or more <aid-filter> tags, each of which contains a single AID. The AID must be specified in hexadecimal format, and contain an even number of characters.

<host-apdu-service>必須包含一個或多個<aid-group>標籤。每個 <aid-group>標籤都需要:

  • 包含一個android:description屬性,該屬性包含AID組的使用者友好描述,適合在UI中顯示。
  • android:category設定其屬性以指示AID組所屬的類別,例如由CATEGORY_PAYMENT 或定義的字串常量CATEGORY_OTHER
  • 每個<aid-group>必須包含一個或多個 <aid-filter>標籤,每個標籤包含一個AID。AID必須以十六進位制格式指定,幷包含偶數個字元。

As a final note, your application also needs to hold the NFC permission to be able to register as a HCE service.

最後,您的應用程式還需要擁有NFC能夠註冊為HCE服務的 許可權。

AID conflict resolution

AID衝突解決方案

Multiple HostApduService components may be installed on a single device, and the same AID can be registered by more than one service. The Android platform resolves AID conflicts depending on which category an AID belongs to. Each category may have a different conflict resolution policy.

多個HostApduService元件可以在單個裝置上安裝,並且可以通過多個服務註冊相同的AID。Android平臺根據AID所屬的類別解決AID衝突。每個類別可能有不同的衝突解決策略。

For example, for some categories (like payment) the user may be able to select a default service in the Android settings UI. For other categories, the policy may be to always ask the user which service is to be invoked in case of conflict. To query the conflict resolution policy for a certain category, see getSelectionModeForCategory().

例如,對於某些類別(如支付),使用者可能能夠在Android設定UI中選擇預設服務。對於其他類別,策略可以是始終詢問使用者在發生衝突時要呼叫哪個服務。要查詢特定類別的衝突解決策略,請參閱 getSelectionModeForCategory()

Check if your service is the default

檢查您的服務是否是預設服務

Applications can check whether their HCE service is the default service for a certain category by using theisDefaultServiceForCategory(ComponentName, String) API.

應用程式可以使用isDefaultServiceForCategory(ComponentName, String)API 檢查其HCE服務是否是特定類別的預設服務 。

If your service is not the default, you can request it to be made the default. See ACTION_CHANGE_DEFAULT.

如果您的服務不是預設服務,則可以請求將其設為預設服務。見ACTION_CHANGE_DEFAULT

 

Payment applications

付款申請

Android considers HCE services that have declared an AID group with the "payment" category as payment applications. The Android 4.4 release contains a top-level Settings menu entry called "tap & pay", which enumerates all such payment applications. In this settings menu, the user can select the default payment application that will be invoked when a payment terminal is tapped.

Android將已宣告具有“付款”類別的AID組的HCE服務視為支付應用程式。Android 4.4版本包含一個名為“tap&pay”的頂級設定選單條目,其中列舉了所有此類支付應用程式。在此設定選單中,使用者可以選擇在點選支付終端時將呼叫的預設支付應用程式。

Required assets for payment applications

支付應用程式所需的資產

To provide a more visually attractive user experience, HCE payment applications are required to provide an additional asset for their service: a so-called service banner.

為了提供更具視覺吸引力的使用者體驗,HCE支付應用程式需要為其服務提供額外資產:所謂的服務橫幅。

This asset should be sized 260x96 dp, and can be specified in your meta-data XML file by adding the android:apduServiceBanner attribute to the <host-apdu-service> tag, which points to the drawable resource. An example is shown below:

此資產的大小應為260x96 dp,並且可以通過向標記新增android:apduServiceBanner屬性來指定元資料XML檔案,該<host-apdu-service>標記指向可繪製資源。一個例子如下所示:

<host-apdu-service xmlns:android="http://schemas.android.com/apk/res/android"
        android:description="@string/servicedesc"
        android:requireDeviceUnlock="false"
        android:apduServiceBanner="@drawable/my_banner">
    <aid-group android:description="@string/aiddescription"
               android:category="payment">
        <aid-filter android:name="F0010203040506"/>
        <aid-filter android:name="F0394148148100"/>
    </aid-group>
</host-apdu-service>

 

Screen off and lock-screen behavior

螢幕關閉和鎖屏行為

Current Android implementations turn the NFC controller and the application processor off completely when the screen of the device is turned off. HCE services will therefore not work when the screen is off.

當裝置的螢幕關閉時,當前的Android實現完全關閉NFC控制器和應用程式處理器。因此,當螢幕關閉時,HCE服務將不起作用。

HCE services can function from the lock-screen however: this is controlled by the android:requireDeviceUnlockattribute in the <host-apdu-service> tag of your HCE service. By default, device unlock is not required, and your service will be invoked even if the device is locked.

然而,HCE服務可以從鎖定螢幕執行:這由HCE服務android:requireDeviceUnlock<host-apdu-service>標籤中的屬性控制。預設情況下,不需要裝置解鎖,即使裝置已鎖定,也會呼叫您的服務。

If you set the android:requireDeviceUnlock attribute to "true" for your HCE service, Android will prompt the user to unlock the device when you tap an NFC reader that selects an AID that is resolved to your service. After unlocking, Android will show a dialog prompting the user to tap again to complete the transaction. This is necessary because the user may have moved the device away from the NFC reader in order to unlock it.

如果您android:requireDeviceUnlock為HCE服務將屬性設定為“true”,則當您點選選擇已解析為您的服務的AID的NFC閱讀器時,Android將提示使用者解鎖裝置。解鎖後,Android將顯示一個對話方塊,提示使用者再次點按以完成交易。這是必要的,因為使用者可能已經將裝置從NFC讀取器移開以便解鎖它。

 

Coexistence with secure element cards

與安全元素卡共存

This section is of interest for developers that have deployed an application that relies on a secure element for card emulation. Android's HCE implementation is designed to work in parallel with other methods of implementing card emulation, including the use of secure elements.

對於部署了依賴於卡模擬的安全元素的應用程式的開發人員而言,此部分很有用。Android的HCE實現旨在與其他實現卡模擬的方法並行工作,包括使用安全元素。

Note: Android does not offer APIs for directly communicating with a secure element itself.

注意: Android不提供用於直接與安全元素本身通訊的API。

This coexistence is based on a principle called "AID routing": the NFC controller keeps a routing table that consists of a (finite) list of routing rules. Each routing rule contains an AID and a destination. The destination can either be the host CPU (where Android apps are running), or a connected secure element.

這種共存基於稱為“AID路由”的原理:NFC控制器保留由(有限的)路由規則列表組成的路由表。每個路由規則都包含AID和目標。目標可以是主機CPU(執行Android應用程式的位置),也可以是連線的安全元素。

When the NFC reader sends an APDU with a "SELECT AID", the NFC controller parses it and checks whether the AIDs matches with any AID in its routing table. If it matches, that APDU and all APDUs following it will be sent to the destination associated with the AID, until another "SELECT AID" APDU is received or the NFC link is broken.

當NFC讀取器傳送具有“SELECT AID”的APDU時,NFC控制器解析它並檢查AID是否與其路由表中的任何AID匹配。如果匹配,則APDU及其後面的所有APDU將被髮送到與AID相關聯的目的地,直到接收到另一個“SELECT AID”APDU或NFC鏈路中斷。

Note: While ISO/IEC 7816-4 defines the concept of “partial matches” as well, this is currently not supported by Android HCE devices.

This architecture is illustrated in figure 4.

注意: 雖然ISO / IEC 7816-4也定義了“部分匹配”的概念,但Android HCE裝置目前不支援此功能。

該架構如圖4所示。

Figure 4. Android operating with both secure element and host-card emulation.

圖4.使用安全元素和主機卡模擬的Android操作。

The NFC controller typically also contains a default route for APDUs. When an AID is not found in the routing table, the default route is used. While this setting might different from device to device, Android devices are required to ensure that the AIDs being registered by your app are properly routed to the host.

Android applications that implement a HCE service or that use a secure element don't have to worry about configuring the routing table - that is taking care of by Android automatically. Android merely needs to know which AIDs can be handled by HCE services and which ones can be handled by the secure element. Based on which services are installed and which the user has configured as preferred, the routing table is configured automatically.

We've already described how to declare AIDs for HCE services. The following section explains how to declare AIDs for applications that use a secure element for card emulation.

NFC控制器通常還包含APDU的預設路由。如果在路由表中找不到AID,則使用預設路由。雖然此設定可能因裝置而異,但Android裝置需要確保應用註冊的AID正確路由到主機。

實現HCE服務或使用安全元素的Android應用程式不必擔心配置路由表 - 這是由Android自動處理的。Android只需要知道哪些AID可以由HCE服務處理,哪些可以由安全元素處理。根據安裝的服務以及使用者已將其配置為首選服務,將自動配置路由表。

我們已經描述瞭如何為HCE服務宣告AID。以下部分說明如何為使用安全元素進行卡模擬的應用程式宣告AID。

 

Secure element AID registration

安全元素AID註冊

Applications using a secure element for card emulation can declare a so-called "off host service" in their manifest. The declaration of such a service is almost identical to the declaration of a HCE service. The exceptions are:

  • The action used in the intent-filter must be set to SERVICE_INTERFACE.
  • The meta-data name attribute must be set to SERVICE_META_DATA.
  • The meta-data XML file must use the <offhost-apdu-service> root tag.

使用安全元素進行卡模擬的應用程式可以在其清單中宣告所謂的“關閉主機服務”。此類服務的宣告幾乎與HCE服務的宣告相同。例外情況是:

  • 必須將intent-filter中使用的操作設定為 SERVICE_INTERFACE
  • 元資料名稱屬性必須設定為 SERVICE_META_DATA
  • 元資料XML檔案必須使用<offhost-apdu-service>根標記。

<service android:name=".MyOffHostApduService" android:exported="true"
         android:permission="android.permission.BIND_NFC_SERVICE">
    <intent-filter>
        <action android:name="android.nfc.cardemulation.action.OFF_HOST_APDU_SERVICE"/>
    </intent-filter>
    <meta-data android:name="android.nfc.cardemulation.off_host_apdu_service"
               android:resource="@xml/apduservice"/>
</service>

An example of the corresponding apduservice.xml file registering two AIDs:

apduservice.xml註冊兩個AID 的相應檔案的示例:

 

<offhost-apdu-service xmlns:android="http://schemas.android.com/apk/res/android"
           android:description="@string/servicedesc">
    <aid-group android:description="@string/subscription" android:category="other">
        <aid-filter android:name="F0010203040506"/>
        <aid-filter android:name="F0394148148100"/>
    </aid-group>
</offhost-apdu-service>

The android:requireDeviceUnlock attribute does not apply to off host services, because the host CPU is not involved in the transaction and therefore cannot prevent the secure element from executing transactions when the device is locked.

The android:apduServiceBanner attribute must be used for off host services that are payment applications as well in order to be selectable as a default payment application.

android:requireDeviceUnlock屬性不適用於關閉主機服務,因為主機CPU不參與事務,因此無法阻止安全元件在裝置鎖定時執行事務。

android:apduServiceBanner屬性必須用於支付應用程式的關閉主機服務,以便可選擇作為預設支付應用程式。

 

Off host service invocation

關閉主機服務呼叫

Android itself will never start or bind to a service that is declared as "off host". This is because the actual transactions are executed by the secure element and not by the Android service itself. The service declaration merely allows applications to register AIDs present on the secure element.

Android本身永遠不會啟動或繫結到宣告為“off host”的服務。這是因為實際的事務是由安全元素執行的,而不是由Android服務本身執行的。服務宣告僅允許應用程式註冊安全元素上存在的AID。

 

HCE and security

HCE和安全

The HCE architecture itself provides one core piece of security: because your service is protected by the BIND_NFC_SERVICE system permission, only the OS can bind to and communicate with your service. This ensures that any APDU you receive is actually an APDU that was received by the OS from the NFC controller, and that any APDU you send back will only go to the OS, which in turn directly forwards the APDUs to the NFC controller.

The core remaining piece is where you get your data that your app sends to the NFC reader. This is intentionally decoupled in the HCE design: it does not care where the data comes from, it just makes sure that it is safely transported to the NFC controller and out to the NFC reader.

For securely storing and retrieving the data that you want to send from your HCE service, you can, for example, rely on the Android Application Sandbox, which isolates your app's data from other apps. For more details on Android security, readSecurity Tips.

HCE體系結構本身提供了一個核心安全性:因為您的服務受BIND_NFC_SERVICE 系統許可權保護,所以只有作業系統可以繫結到您的服務並與之通訊。這可確保您收到的任何APDU實際上是作業系統從NFC控制器接收的APDU,並且您發回的任何APDU將僅轉發到作業系統,而作業系統又直接將APDU轉發到NFC控制器。

剩下的核心部分是您獲取應用程式傳送給NFC閱讀器的資料。這在HCE設計中有意去耦:它不關心資料來自何處,它只是確保它被安全地傳輸到NFC控制器並輸出到NFC讀取器。

例如,為了安全地儲存和檢索要從HCE服務傳送的資料,您可以依賴Android應用程式沙箱,它將您的應用程式資料與其他應用程式隔離開來。有關Android安全性的更多詳細資訊,請閱讀 安全提示

 

 

Protocol parameters and details

協議引數和細節

This section is of interest for developers that want to understand what protocol parameters HCE devices use during the anti-collision and activation phases of the NFC protocols. This allows building a reader infrastructure that is compatible with Android HCE devices.

對於希望瞭解HCE裝置在NFC協議的防衝突和啟用階段使用的協議引數的開發人員而言,此部分很有用。這允許構建與Android HCE裝置相容的讀取器基礎結構。

 

Nfc-A (ISO/IEC 14443 type A) protocol anti-collision and activation

Nfc-A(ISO / IEC 14443 A型)協議防衝突和啟用

As part of the Nfc-A protocol activation, multiple frames are exchanged.

In the first part of the exchange the HCE device will present its UID; HCE devices should be assumed to have a random UID. This means that on every tap, the UID that is presented to the reader will be a randomly generated UID. Because of this, NFC readers should not depend on the UID of HCE devices as a form of authentication or identification.

The NFC reader can subsequently select the HCE device by sending a SEL_REQ command. The SEL_RES response of the HCE device will at least have the 6th bit (0x20) set, indicating that the device supports ISO-DEP. Note that other bits in the SEL_RES may be set as well, indicating for example support for the NFC-DEP (p2p) protocol. Since other bits may be set, readers wanting to interact with HCE devices should explicitly check for the 6th bit only, and not compare the complete SEL_RES with a value of 0x20.

作為Nfc-A協議啟用的一部分,交換多個幀。

在交換的第一部分,HCE裝置將呈現其UID; 應假設HCE裝置具有隨機UID。這意味著在每次點選時,呈現給閱讀器的UID將是隨機生成的UID。因此,NFC讀取器不應該依賴於HCE裝置的UID作為認證或識別的形式。

隨後,NFC讀取器可以通過傳送SEL_REQ命令來選擇HCE裝置。HCE裝置的SEL_RES響應將至少設定第6位(0x20),表示裝置支援ISO-DEP。注意,也可以設定SEL_RES中的其他位,指示例如對NFC-DEP(p2p)協議的支援。由於可以設定其他位,想要與HCE裝置互動的讀者應該明確檢查第6位,並且不要將完整的SEL_RES與值0x20進行比較。

 

ISO-DEP activation

ISO-DEP啟用

After the Nfc-A protocol is activated, the ISO-DEP protocol activation is initiated by the NFC reader. It sends a "RATS" (Request for Answer To Select) command. The RATS response, the ATS, is completely generated by the NFC controller and not configurable by HCE services. However, HCE implementations are required to meet NFC Forum requirements for the ATS response, so NFC readers can count on these parameters being set in accordance with NFC Forum requirements for any HCE device.

啟用Nfc-A協議後,NFC讀取器啟動ISO-DEP協議啟用。它傳送“RATS”(請求應答選擇)命令。RATS響應ATS完全由NFC控制器生成,不能由HCE服務配置。但是,HCE實施需要滿足NFC論壇對ATS響應的要求,因此NFC讀取器可以依賴於根據NFC論壇對任何HCE裝置的要求設定這些引數。

The section below provides more details on the individual bytes of the ATS response provided by the NFC controller on a HCE device:

以下部分提供了有關HCE裝置上NFC控制器提供的ATS響應的各個位元組的更多詳細資訊:

  • TL: length of the ATS response. Must not indicate a length greater than 20 bytes.
  • T0: bits 5, 6 and 7 must be set on all HCE devices, indicating TA(1), TB(1) and TC(1) are included in the ATS response. Bits 1 to 4 indicate the FSCI, coding the maximum frame size. On HCE devices the value of FSCI must be between 0h and 8h.
  • T(A)1: defines bitrates between reader and emulator, and whether they can be asymmetric. There are no bitrate requirements or guarantees for HCE devices.
  • T(B)1: bits 1 to 4 indicate the Start-up Frame Guard time Integer (SFGI). On HCE devices, SFGI must be <= 8h. Bits 5 to 8 indicate the Frame Waiting time Integer (FWI) and codes the Frame Waiting Time (FWT). On HCE devices, FWI must be <= 8h.
  • T(C)1: bit 5 indicates support for "Advanced Protocol features". HCE devices may or may not support "Advanced Protocol features". Bit 2 indicates support for DID. HCE devices may or may not support DID. Bit 1 indicates support for NAD. HCE devices must not support NAD and set bit 1 to zero.
  • Historical bytes: HCE devices may return up to 15 historical bytes. NFC readers willing to interact with HCE services should make no assumptions about the contents of the historical bytes or their presence.
  • TL:ATS響應的長度。不得指示長度大於20個位元組。
  • T0:必須在所有HCE裝置上設定第5,6和7位,表示TA(1),TB(1)和TC(1)包含在ATS響應中。位元1到4表示FSCI,編碼最大幀大小。在HCE裝置上,FSCI的值必須介於0h和8h之間。
  • T(A)1:定義讀取器和模擬器之間的位元率,以及它們是否可以是非對稱的。HCE裝置沒有位元率要求或保證。
  • T(B)1:位1到4表示啟動幀保護時間整數(SFGI)。在HCE裝置上,SFGI必須<= 8h。位5到8指示幀等待時間整數(FWI)並編碼幀等待時間(FWT)。在HCE裝置上,FWI必須<= 8h。
  • T(C)1:位5表示支援“高階協議功能”。HCE裝置可能支援也可能不支援“高階協議功能”。位2表示支援DID。HCE裝置可能支援也可能不支援DID。位1表示支援NAD。HCE裝置不得支援NAD並將第1位設定為零。
  • 歷史位元組:HCE裝置最多可返回15個歷史位元組。願意與HCE服務互動的NFC讀者不應對歷史位元組的內容或它們的存在做出任何假設。

Note that many HCE devices are likely made compliant with protocol requirements that the payment networks united in EMVCo have specified in their "Contactless Communication Protocol" specification. In particular:

請注意,許多HCE裝置可能符合協議要求,EMVCo中的支付網路已在其“非接觸式通訊協議”規範中指定。特別是:

  • T0中的FSCI必須在2h到8h之間。
  • T(A)1必須設定為0x80,表示僅支援106 kbit / s位元率,並且不支援讀取器和模擬器之間的非對稱位元率。
  • T(B)1中的FWI必須<= 7h。
  • FSCI in T0 must be between 2h and 8h.
  • T(A)1 must be set to 0x80, indicating only the 106 kbit/s bitrate is supported, and asymmetric bitrates between reader and emulator are not supported.
  • FWI in T(B)1 must be <= 7h.

 

APDU data exchange

APDU資料交換

As noted earlier, HCE implementations only support a single logical channel. Attempting to select applications on different logical channels will not work on a HCE device.

如前所述,HCE實現僅支援單個邏輯通道。嘗試在不同邏輯通道上選擇應用程式將無法在HCE裝置上執行。