Mobile Payment: Smart IC card for NFC communication with Android mobile phones; androidnfc

Source: Internet
Author: User

Mobile Payment: Smart IC card for NFC communication with Android mobile phones; androidnfc


This article from http://blog.csdn.net/hellogv/, reference must indicate the source!
Currently, the common smart IC Card runs the JavaCard virtual machine, and the smart IC card can run the card application (Applet) compiled by the simplified Java language ). The Applet of the Smart IC card cannot be started by itself. The Select command must be sent to the card by an external terminal (such as a POS machine or a subway card swiping terminal), so that the Applet of the selected card can run. Appplet focuses on data processing without I/O functions. The Applet program has a lifecycle and a specified entry. The main methods are as follows:
  • Public static void install (byte [] bArray, short bOffset, byte bLength)



If an example of the Applet subclass is built, JRE will first call this; all initialization and Memory Allocation Operations should be implemented in this; you can obtain some app initialization parameters passed in by the off-card entity.


  • Public void process (APDU apdu)
Similar to the main of a normal java class, after installation, the execution of APDU will be implemented here.



  • Protected final void register ()
The applet is used to register the applet instance in jcret.



  • Register (byte [] bArray, short bOffset, byte bLength)
The register () function adds the ability to allocate specific AID.



  • Public boolean select ()
Once JRE receives the SELECT [by name] command, it searches for the Applet corresponding to the AID indicated in the command to make it active, and receives and processes the following APDU command; before selecting a new Applet, JRE first calls the deselect method of the current Applet; the Applet can refuse to be selected, and the select method returns false; the SELECT [by name] command will also be passed to the applet for processing. In this case, the selectingApplet is used to determine the current state.

The DEMO running effect in this article is as follows. It includes a JavaCard Applet implementation and an NFC read/Write Program on the Android end to implement simple communication between the Smart IC Card and the Android mobile phone.

Next, paste the simple Applet source code: http://download.csdn.net/detail/hellogv/8090041.

The general idea is: the Applet defines two user-defined commands, namely, pai_ins_1 and pai_ins_2, with the names starting with pai_linoleic. When Android phones send pai_ins_1 and pai_ins_2 via NFC, the Applet returns strHello and strWorld respectively.

The core source code is as follows:


public class mytest extends Applet {

private static final byte [] strHello = {(byte) 'H', (byte) 'e',
(byte) 'l', (byte) 'l', (byte) 'o'};

private static final byte [] strWorld = {(byte) 'W',
(byte) 'o', (byte) 'r', (byte) 'l', (byte) 'd',};

private static final byte CMD_CLA = (byte) 0x80;
private static final byte CMD_INS_1 = (byte) 0x10;
private static final byte CMD_INS_2 = (byte) 0x20;
The
public static void install (byte [] bArray, short bOffset, byte bLength) {
// GP-compliant JavaCard applet registration
new mytest (). register (bArray, (short) (bOffset + 1), bArray [bOffset]);
}

/ *
* When the Java Card Applet is selected, it is called by JCRE. Java Card Applet can define select () to complete initialization,
* Otherwise, JCRE calls select () of the parent class.
* @see javacard.framework.Applet # select ()
* /
public boolean select () {
short debug = 100;
debug ++; // Used for breakpoint debugging, triggered when selected.
return super.select ();
}

/ *
* When the Java Card Applet is abandoned, it is called by JCRE. Java Card Applet can define deselect () to complete the removal,
* Otherwise, JCRE calls the parent's deselect ().
* @see javacard.framework.Applet # deselect ()
* /
public void deselect () {
short debug = 100;
debug ++; // For breakpoint debugging
super.deselect ();
}
 
/ *
* Every time the APDU command is received, it will be executed
* @see javacard.framework.Applet # process (javacard.framework.APDU)
* /
public void process (APDU apdu) {
if (selectingApplet ()) {
return;
}

// Get data from external terminal
byte [] buffer = apdu.getBuffer ();
// Get the first data
byte CLA = (byte) (buffer [ISO7816.OFFSET_CLA] & 0xFF);
// Get the second data
byte INS = (byte) (buffer [ISO7816.OFFSET_INS] & 0xFF);

if (CLA! = CMD_CLA) {// The format is wrong
ISOException.throwIt (ISO7816.SW_CLA_NOT_SUPPORTED);
}

switch (INS) {
case CMD_INS_1:
sendBytes (apdu, strHello);
break;
case CMD_INS_2:
sendBytes (apdu, strWorld);
break;
default:
ISOException.throwIt (ISO7816.SW_INS_NOT_SUPPORTED);
}
}

private void sendBytes (APDU apdu, byte [] arrays) {
byte [] buffer = apdu.getBuffer ();
short length = (short) arrays.length;

Util.arrayCopyNonAtomic (arrays, (short) 0, buffer, (short) 0,
(short) length);

apdu.setOutgoingAndSend ((short) 0, length);
}
}


Next, paste the core code of Android: http://download.csdn.net/detail/hellogv/8090053.


The general idea is: the Android-side NFC reader defines the ID (AID) of an Applet, the SELECT command's message header (SELECT_APDU_HEADER), and the two custom commands pai_ins_1 and pai_ins_2. First, use AID and SELECT_APDU_HEADER to generate the complete SELECT command, transceive (send) to the card, used to start the AID corresponding Applet in the card. After the Applet in the card is started, the NFC reader sends two custom commands in SAMPLE_COMMAND, And the Applet returns "Hello" "World" respectively ".

The core source code is as follows:

public final class CardReader {
    private static final String TAG = "LoyaltyCardReader";
    // AID for our loyalty card service.
    private static final String SAMPLE_CARD_AID = "1122001122";
    // ISO-DEP command HEADER for selecting an AID.
    // Format: [Class | Instruction | Parameter 1 | Parameter 2]
    private static final String SELECT_APDU_HEADER = "00A40400";
    // "OK" status word sent in response to SELECT AID command (0x9000)
    private static final byte [] SELECT_OK_SW = {(byte) 0x90, (byte) 0x00};
    // Custom commands
    private static final String [] SAMPLE_COMMAND = {"8010000000", // The card returns "Hello"
    "8020000000"}; // Return to "World" after receiving the card
    
public static String [] [] TECHLISTS;
public static IntentFilter [] FILTERS;

static {
try {
// the tech lists used to perform matching for dispatching of the ACTION_TECH_DISCOVERED intent
TECHLISTS = new String [] [] {{IsoDep.class.getName ()}};

FILTERS = new IntentFilter [] {new IntentFilter (
NfcAdapter.ACTION_TECH_DISCOVERED, "* / *")};
} catch (Exception e) {
}
}
    
static public String tagDiscovered (Tag tag) {
Log.e (TAG, "New tag discovered");

String strResult = "";
IsoDep isoDep = IsoDep.get (tag);
if (isoDep! = null) {
try {
// Connect to the remote NFC device
isoDep.connect ();

// Send select command, the card will return SELECT_OK_SW (90 00)
byte [] cmdSelect = BuildSelectApdu (SAMPLE_CARD_AID);
Log.e (TAG, "Sending:" + ByteArrayToHexString (cmdSelect));
byte [] result = isoDep.transceive (cmdSelect);
Log.e (TAG, "Receive:" + ByteArrayToHexString (result));
byte [] [] response = getResponse (result);
byte [] statusWord = response [0];

if (Arrays.equals (SELECT_OK_SW, statusWord) == false)
return "";

// Cycle send custom commands
for (int i = 0; i <SAMPLE_COMMAND.length; i ++) {
String command = SAMPLE_COMMAND [i];
result = HexStringToByteArray (command);
Log.e (TAG, "Sending:" + command);
The
result = isoDep.transceive (result);
Log.e (TAG, "Receive:" + ByteArrayToHexString (result));
response = getResponse (result);
byte [] body = response [1];
The
strResult = strResult + new String (body) + ":" + ByteArrayToHexString (body) + "\ r \ n";
}
The

return strResult;

} catch (IOException e) {
Log.e (TAG, "Error communicating with card:" + e.toString ());
}
}
return null;
}

/ ***
* Decompose the data returned by the card
* @param b
* @return [0] means returned status value, [1] means returned text
* /
private static byte [] [] getResponse (byte [] b) {
byte [] [] result = new byte [2] [];
The
int length = b.length;
byte [] status = {b [length-2], b [length-1]};
The
byte [] body = Arrays.copyOf (b, length-2);

result [0] = status;
result [1] = body;
return result;
}
The
public static String load (Parcelable parcelable) {
// Filter out various NFC standard data from Parcelable
final Tag tag = (Tag) parcelable;
return tagDiscovered (tag);
}


    / **
     * 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);
    }

    / **
     * Utility class 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];
        int v;
        for (int j = 0; j <bytes.length; j ++) {
            v = bytes [j] & 0xFF;
            hexChars [j * 2] = hexArray [v >>> 4];
            hexChars [j * 2 + 1] = hexArray [v & 0x0F];
        }
        return new String (hexChars);
    }

    / **
     * Utility class 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
     * /
    public static byte [] HexStringToByteArray (String s) {
        int len = s.length ();
        byte [] data = new byte [len / 2];
        for (int i = 0; i <len; i + = 2) {
            data [i / 2] = (byte) ((Character.digit (s.charAt (i), 16) << 4)
                    + Character.digit (s.charAt (i + 1), 16));
        }
        return data;
    }
} 





What is NFC mobile payment

NFC is a type of close-range communication technology. NFC mobile payment means that if a mobile phone has an NFC module, NFC can be used to complete some payment functions, such as mobile phone card swiping or even phone card swiping. This is called NFC mobile payment.
 
What is the use of NFC mobile phones that do not support mobile payment? Answer

NFC, developed jointly by Philips and Sony, is a non-contact identification and interconnection technology that enables close-range wireless communication between mobile devices, consumer electronics, PCs, and smart control tools. NFC provides a simple, touch-based solution that allows consumers to easily and intuitively exchange information, access content and services.
The above is Baidu's explanation of NFC. Today we are going to talk about NFC technology and NFC mobile phones.
Mobile Payment is not all about NFC Technology
Compared with ordinary mobile phones, NFC mobile phones have the following three additional functions:
1. It can be used as a POS machine, that is, the "read" mode.
2. It can be used as a card, that is, the mobile payment function at the core of NFC technology.
3. Point-to-point communication like Bluetooth and Wi-Fi
These are the charm of NFC mobile phones, but what are the costs of carriers and mobile terminal manufacturers for these three features? First, for terminal manufacturers, if NFC chips are added to their mobile phone products, the cost will be increased by dozens of Yuan. Do not underestimate the tens of Yuan. From the terminal manufacturer's perspective, the pressure is not small. The key is that the cost has gone up, but there is no profit point. That is to say, we cannot make any money from the core mobile payment industry chain. At this time, if the customization of the operator does not provide much subsidies to the terminal manufacturer, who is willing to earn money and earn money? The profit points of operators and terminal manufacturers in the mobile payment industry chain are not clear

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.