Java Code Examples for android.nfc.tech.IsoDep

The following are top voted examples for showing how to use android.nfc.tech.IsoDep. These examples are extracted from open source projects. You can vote up the examples you like and your votes will be used in our system to generate more good examples.
Example 1
Project: mDL-ILP   File: NFCConnection.java   Source Code and License 7 votes vote down vote up
@Override
public void onTagDiscovered(final Tag tag) {
    Log.d(TAG, "Tag found: " + tag.toString());
    Log.d(TAG, "Id: " + HexStrings.toHexString(tag.getId()));
    for (String tech: tag.getTechList()) {
        Log.d(TAG, "Tech: " + tech);
    }

    if (Arrays.asList(tag.getTechList()).contains("android.nfc.tech.IsoDep")) {
        IsoDepApduInterface apduInterface;
        try {
            apduInterface = new IsoDepApduInterface(IsoDep.get(tag));
        } catch (IOException e) {
            fail(e.getMessage());
            e.printStackTrace();
            return;
        }

        dispatchLoadTask(apduInterface);
    }
}
 
Example 2
Project: coinblesk-client-gui   File: NFCServerCLTV.java   Source Code and License 6 votes vote down vote up
private DERObject transceiveDER(IsoDep isoDep, DERObject input, boolean needsSelectAidApdu) throws IOException {
    final long startTimeTransceive = System.currentTimeMillis();
    final byte[] derPayload = input.serializeToDER();
    byte[] derResponse;
    Log.d(TAG, "transceiveDER - start - send derPayload length=" + derPayload.length + " byte");

    derResponse = assembleFragment(isoDep, derPayload, needsSelectAidApdu);
    derResponse = keepAliveLoop(isoDep, derResponse);
    derResponse = concatNextResponseBytes(isoDep, derResponse);
    DERObject result = DERParser.parseDER(derResponse);

    long duration = System.currentTimeMillis() - startTimeTransceive;
    Log.d(TAG, "transceiveDER - end - " +
                        "took " + duration + " ms - " +
                        "received length=" + result.getPayload().length + " byte");
    return result;
}
 
Example 3
Project: coinblesk-client-gui   File: NFCServerCLTV.java   Source Code and License 6 votes vote down vote up
private byte[] assembleFragment(IsoDep isoDep, byte[] derPayload, boolean needsSelectAidApdu) throws IOException {
    int fragmentByte = 0;
    byte[] derResponse = new byte[0];
    while (fragmentByte < derPayload.length) {
        byte[] fragment = new byte[0];
        if (needsSelectAidApdu) {
            Log.d(TAG, "transceiveDER - select Aid Apdu");
            byte[] retval = isoDep.transceive(NFCUtils.createSelectAidApdu(NFCUtils.AID_ANDROID));
            Log.d(TAG, "transceiveDER - select Aid Apdu OK! "+retval.length);
            if(NFCUtils.isKeepAlive(retval)) {
                needsSelectAidApdu = false;
            }
        }

        int endLength = Math.min(derPayload.length, fragmentByte + NFCUtils.DEFAULT_MAX_FRAGMENT_SIZE);
        byte[] fragmentPart = Arrays.copyOfRange(derPayload, fragmentByte, endLength);
        fragment = ClientUtils.concatBytes(fragment, fragmentPart);

        Log.d(TAG, "transceiveDER - about to send fragment size: " + fragment.length);
        derResponse = isoDep.transceive(fragment);
        Log.d(TAG, "transceiveDER - received payload: " + Arrays.toString(derResponse));
        fragmentByte += fragment.length;
    }
    return derResponse;
}
 
Example 4
Project: coinblesk-client-gui   File: NFCServerCLTV.java   Source Code and License 6 votes vote down vote up
@Override
public void onTagDiscovered(Tag tag) {
    Log.d(TAG, "onTagDiscovered: " + tag);

    final long startTime = System.currentTimeMillis();
    long duration;

    try {
        IsoDep isoDep = IsoDep.get(tag);
        isoDep.connect();
        onTagDiscovered(tag, isoDep, true);
    } catch (Throwable e) {
        Log.e(TAG, "Exception in onTagDiscovered", e);
        getPaymentRequestDelegate().onPaymentError(e.getMessage());
    }
}
 
Example 5
Project: hipay-fullservice-sdk-android   File: NFCUtils.java   Source Code and License 6 votes vote down vote up
/**
 * Activate NFC dispacher to read NFC Card Set the most important priority to the foreground application
 */
public static void enableDispatch(Activity activity) {

       if (isNfcEnabled(activity)) {

           NfcAdapter adapter = getNfcAdapter(activity);

           PendingIntent pendingIntent = PendingIntent.getActivity(
                   activity,
                   0,
                   new Intent(activity, activity.getClass()).addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP),
                   0);

           IntentFilter[] intentFilter = new IntentFilter[] { new IntentFilter(NfcAdapter.ACTION_TECH_DISCOVERED) };
           String[][] techList = new String[][] { { IsoDep.class.getName() } };

           adapter.enableForegroundDispatch(activity, pendingIntent, intentFilter, techList);
       }
}
 
Example 6
Project: PIVOpacityDemo-android   File: Transceiver.java   Source Code and License 6 votes vote down vote up
/**
 * Creates a transceiver for the specified tag.
 * @return null is returned if a transceiver could not be created
 */
public static Transceiver create(Logger logger, Tag tag)
{
	IsoDep isoDep = IsoDep.get(tag);
	if (null == isoDep)
	{
		logger.warn(TAG, "Unable to create IsoDep for NFC tag: " + StringUtil.join(tag.getTechList(), ", "));
		return null;
	}

	logger.info(TAG, "Connnecting to ISO-DEP: " + isoDep.isConnected());
	try
	{
		isoDep.connect();
		isoDep.setTimeout(30000);
		return new Transceiver(logger, isoDep);
	}
	catch (Exception ex)
	{
		logger.error(TAG, "Unable to connect to ISO-DEP", ex);
		return null;
	}
}
 
Example 7
Project: FMTech   File: NfcReader.java   Source Code and License 6 votes vote down vote up
@TargetApi(10)
private static CreditCardNfcResult readRecord(IsoDep paramIsoDep, byte paramByte1, byte paramByte2)
  throws IOException, TagReadTimeoutException
{
  ResponseApdu localResponseApdu = new ResponseApdu(transceive(paramIsoDep, ApduUtil.buildReadCommand(paramByte1, paramByte2).command));
  if (ApduUtil.matchesStatus(localResponseApdu, ResponseApdu.WRONG_LENGTH_LE)) {
    localResponseApdu = new ResponseApdu(transceive(paramIsoDep, ApduUtil.buildReadCommand(paramByte1, paramByte2, localResponseApdu.statusWord2).command));
  }
  if (ApduUtil.matchesStatus(localResponseApdu, ResponseApdu.SUCCESS_SW))
  {
    CreditCardNfcResult localCreditCardNfcResult = TlvUtil.parseCreditCardInfoFromTlv(TlvParser.parseTlv(localResponseApdu));
    if (localCreditCardNfcResult != null) {
      return localCreditCardNfcResult;
    }
  }
  return null;
}
 
Example 8
Project: android-u2f-demo   File: SignFragment.java   Source Code and License 6 votes vote down vote up
private void onChallengeReceived() {
    NfcAdapter adapter = NfcAdapter.getDefaultAdapter(getActivity());
    if (adapter == null) {
        Toast.makeText(getActivity(), R.string.no_nfc, Toast.LENGTH_LONG).show();
    } else if (adapter.isEnabled()) {
        Intent intent = getActivity().getIntent();
        intent.setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
        PendingIntent tagIntent = PendingIntent.getActivity(getActivity(), 0, intent, 0);
        IntentFilter iso = new IntentFilter(NfcAdapter.ACTION_TECH_DISCOVERED);

        ((MainActivity) getActivity()).setOnNFCListener(SignFragment.this);
        adapter.enableForegroundDispatch(getActivity(), tagIntent, new IntentFilter[]{iso},
                new String[][]{new String[]{IsoDep.class.getName()}});

        getView().findViewById(R.id.progressBar).setVisibility(View.INVISIBLE);
        ((TextView) getView().findViewById(R.id.status_text)).setText(R.string.swipe);
    } else {
        Toast.makeText(getActivity(), R.string.nfc_disabled, Toast.LENGTH_LONG).show();
    }
}
 
Example 9
Project: android-u2f-demo   File: EnrollFragment.java   Source Code and License 6 votes vote down vote up
private void onChallengeReceived() {
    NfcAdapter adapter = NfcAdapter.getDefaultAdapter(getActivity());
    if (adapter == null) {
        Toast.makeText(getActivity(), R.string.no_nfc, Toast.LENGTH_LONG).show();
    } else if (adapter.isEnabled()) {
        Intent intent = getActivity().getIntent();
        intent.setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
        PendingIntent tagIntent = PendingIntent.getActivity(getActivity(), 0, intent, 0);
        IntentFilter iso = new IntentFilter(NfcAdapter.ACTION_TECH_DISCOVERED);

        ((MainActivity) getActivity()).setOnNFCListener(EnrollFragment.this);
        adapter.enableForegroundDispatch(getActivity(), tagIntent, new IntentFilter[]{iso},
                new String[][]{new String[]{IsoDep.class.getName()}});

        getView().findViewById(R.id.progressBar).setVisibility(View.INVISIBLE);
        ((TextView) getView().findViewById(R.id.status_text)).setText(R.string.swipe);
    } else {
        Toast.makeText(getActivity(), R.string.nfc_disabled, Toast.LENGTH_LONG).show();
    }
}
 
Example 10
Project: IDCardReader   File: MainActivity.java   Source Code and License 6 votes vote down vote up
private String doTransceiveUTF8(IsoDep iso, byte[] command) throws IOException {
    final byte[] ret = iso.transceive(command);

    Log.d(TAG, "Sent: " + ByteArrayToHexString(command) + "\nRecv: " + ByteArrayToHexString(ret));

    final StringBuffer buffer = new StringBuffer();
    for(int i = 1; i < ret.length; i++) {
        buffer.append((char)ret[i]);
    }

    final String retStr = buffer.toString();

    Log.d(TAG, "UTF-8: " + retStr);
    return retStr;
}
 
Example 11
Project: nordpol   File: AndroidCard.java   Source Code and License 6 votes vote down vote up
public static AndroidCard get(Tag tag) throws IOException {
    IsoDep card = IsoDep.get(tag);

    if(card != null) {
        /* Workaround for the Samsung Galaxy S5 (since the
         * first connection always hangs on transceive).
         * TODO: This could be improved if we could identify
         * Samsung Galaxy S5 devices
         */
        card.connect();
        card.close();
        return new AndroidCard(card);
    } else {
        return null;
    }
}
 
Example 12
Project: MasterTap   File: CardReaderTask.java   Source Code and License 6 votes vote down vote up
@Override
protected String doInBackground(Tag... params) {
    Tag tag = params[0];

    tagCommunicator = IsoDep.get(tag);

    try {
        tagCommunicator.connect();
        tagCommunicator.setTimeout(5000);

        if (tagCommunicator.isConnected()) {
            readCard();
        }
    } catch (IOException e) {
        e.printStackTrace();
    }

    return null;
}
 
Example 13
Project: WalletCordova   File: AndroidCard.java   Source Code and License 6 votes vote down vote up
public static AndroidCard get(Tag tag) throws IOException {
    IsoDep card = IsoDep.get(tag);

    /* Workaround for the Samsung Galaxy S5 (since the
     * first connection always hangs on transceive).
     * TODO: This could be improved if we could identify
     * Samsung Galaxy S5 devices
     */
    card.connect();
    card.close();

    if(card != null) {
        return new AndroidCard(card);
    } else {
        return null;
    }
}
 
Example 14
Project: smartcard-reader   File: EmvReadActivity.java   Source Code and License 6 votes vote down vote up
@Override
public void onTagDiscovered(Tag tag) {
    doTapFeedback();
    clearImage();
    // maybe clear console or show separator, depends on settings
    if (mAutoClear) {
        clearMessages();
    } else {
        addMessageSeparator();
    }
    // get IsoDep handle and run xcvr thread
    IsoDep isoDep = IsoDep.get(tag);
    if (isoDep == null) {
        onError(getString(R.string.wrong_tag_err));
    } else {
        ReaderXcvr xcvr = new PaymentReaderXcvr(isoDep, "", this, TEST_MODE_EMV_READ);
        new Thread(xcvr).start();
    }
}
 
Example 15
Project: smartcard-reader   File: BatchSelectActivity.java   Source Code and License 6 votes vote down vote up
@Override
public void onTagDiscovered(Tag tag) {
    doTapFeedback();
    clearImage();
    // maybe clear console or show separator, depends on settings
    if (mAutoClear) {
        clearMessages();
    } else {
        // two separators between taps/discoveries
        addMessageSeparator();
        addMessageSeparator();
    }
    // get IsoDep handle and run xcvr thread
    IsoDep isoDep = IsoDep.get(tag);
    if (isoDep == null) {
        onError(getString(R.string.wrong_tag_err));
    } else {
        List<SmartcardApp> memberApps = mGrpToMembersMap.get(mSelectedGrpPos);
        new Thread(new BatchReaderXcvr(isoDep, memberApps, this)).start();
    }
}
 
Example 16
Project: android-kitkat-nfc-library   File: InternalNfcTransceiver.java   Source Code and License 6 votes vote down vote up
@Override
public void onTagDiscovered(Tag tag) {
	if (Config.DEBUG)
		Log.d(TAG, "tag discovered: " + tag);
	
	if (!enabled) {
		if (Config.DEBUG)
			Log.d(TAG, "tag discovered, but InternalNfcTransceiver not enabled");
		
		return;
	}
	
	isoDep = IsoDep.get(tag);
	try {
		isoDep.connect();
		nfcInit.tagDiscovered();
	} catch (IOException e) {
		if (Config.DEBUG)
			Log.e(TAG, "Could not connnect isodep: ", e);
		
		eventHandler.handleMessage(NfcEvent.INIT_FAILED, null);
	}
}
 
Example 17
Project: NFCSocket   File: NfcClientSocket.java   Source Code and License 6 votes vote down vote up
/**
 * Send message via a Nfc connection.
 *
 * @param message The message in byte array form
 * @return The response from {@link NfcServerSocket}. null might be returned
 * if <li>the connection is lost. <li> {@link NfcServerSocket} does
 * not return response within timeout. <li> {@link NfcServerSocket}
 * returns a null response.
 */
public byte[] send(byte[] message) {
    if (currentTag == null) {
        return null;
    }

    if (isoDep == null) {
        isoDep = IsoDep.get(currentTag);
    }

    if (isoDep.isConnected()) {
        try {
            byte[] response = isoDep.transceive(message);
            return response;
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
    } else {
        log("isodep not connected");
        return null;
    }
}
 
Example 18
Project: nfc-reader-app   File: MainActivity.java   Source Code and License 6 votes vote down vote up
/**
 * 
 */
@Override
protected void onNewIntent(Intent intent) {
	super.onNewIntent(intent);
	Log.d(TAG, "onNewIntent Called");
	if (NfcAdapter.ACTION_TAG_DISCOVERED.equals(intent.getAction())) {
		// validate that this tag can be written....
		myStatusTextView.setText("tag detected");
		pbCircular.setVisibility(View.VISIBLE);
		Tag detectedTag = intent.getParcelableExtra(NfcAdapter.EXTRA_TAG);
		Log.d(TAG, detectedTag.toString());
		Log.d(TAG, detectedTag.getTechList().toString());

		this.isoDep = IsoDep.get(detectedTag);

		// Have the background task send the image
		fileSender.execute(imageBuffer);
		fileSender = new SendFileToWISP(this);

	}// end if

}
 
Example 19
Project: irma_android_management   File: WaitingForCardActivity.java   Source Code and License 6 votes vote down vote up
@Override
public void onNewIntent(Intent intent) {
    Log.i(TAG, "Discovered tag with intent: " + intent);
    if (NfcAdapter.ACTION_TECH_DISCOVERED.equals(intent.getAction())) {
     tag = intent.getParcelableExtra(NfcAdapter.EXTRA_TAG);
 	isotag = IsoDep.get(tag);
 	if (isotag != null) {
 		Log.i(TAG,"Found IsoDep tag!");
 		
 		// Make sure we're not already communicating with a card
 		if (activityState == STATE_IDLE) {
 			askForPin();
 		}
 	}
    }
}
 
Example 20
Project: irma_android_cardproxy   File: MainActivity.java   Source Code and License 6 votes vote down vote up
@Override
protected void onCreate(Bundle savedInstanceState) {
	super.onCreate(savedInstanceState);
	setContentView(R.layout.activity_main);
	
       // NFC stuff
       nfcA = NfcAdapter.getDefaultAdapter(getApplicationContext());
       mPendingIntent = PendingIntent.getActivity(this, 0,
               new Intent(this, getClass()).addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP), 0);

       // Setup an intent filter for all TECH based dispatches
       IntentFilter tech = new IntentFilter(NfcAdapter.ACTION_TECH_DISCOVERED);
       mFilters = new IntentFilter[] { tech };

       // Setup a tech list for all IsoDep cards
       mTechLists = new String[][] { new String[] { IsoDep.class.getName() } };

    setState(STATE_IDLE);

    timer = new Timer();
    timer.scheduleAtFixedRate(new CardPollerTask(), CARD_POLL_DELAY, CARD_POLL_DELAY);
}
 
Example 21
Project: polling-station-app   File: PassportConnection.java   Source Code and License 5 votes vote down vote up
/**
 * Opens a connection with the ID by doing BAC
 * Uses hardcoded parameters for now
 *
 * @param tag - NFC tag that started this activity (ID NFC tag)
 * @return PassportService - passportservice that has an open connection with the ID
 */
public PassportService openConnection(Tag tag, final DocumentData docData) throws CardServiceException {
    try {
        IsoDep nfc = IsoDep.get(tag);
        CardService cs = CardService.getInstance(nfc);
        this.ps = new PassportService(cs);
        this.ps.open();

        // Get the information needed for BAC from the data provided by OCR
        this.ps.sendSelectApplet(false);
        BACKeySpec bacKey = new BACKeySpec() {
            @Override
            public String getDocumentNumber() {
                return docData.getDocumentNumber();
            }

            @Override
            public String getDateOfBirth() { return docData.getDateOfBirth(); }

            @Override
            public String getDateOfExpiry() { return docData.getExpiryDate(); }
        };
        ps.doBAC(bacKey);
        return ps;
    } catch (CardServiceException ex) {
        try {
            ps.close();
        } catch (Exception ex2) {
            ex2.printStackTrace();
        }
        throw ex;
    }
}
 
Example 22
Project: mi-firma-android   File: AndroidNfcConnection.java   Source Code and License 5 votes vote down vote up
/** Contructor de la clase para la gesti&oacute;n de la conexi&oacute;n por NFC.
 * @param tag <code>Tag</code> para obtener el objeto <code>IsoDep</code> y establecer la
 *            conexi&oacute;n.
 * @throws IOException Si falla el establecimiento de la conexi&oacute;n. */
public AndroidNfcConnection(final Tag tag) throws IOException {
    if (tag == null) {
        throw new IllegalArgumentException("El tag NFC no puede ser nulo"); //$NON-NLS-1$
    }
    this.mIsoDep = IsoDep.get(tag);
    this.mIsoDep.connect();
    this.mIsoDep.setTimeout(ISODEP_TIMEOUT);
}
 
Example 23
Project: mi-firma-android   File: NFCWatchdogRefresher.java   Source Code and License 5 votes vote down vote up
@Nullable
private Tag getTag() {
    final IsoDep isoDep = mIsoDep.get();
    if (isoDep != null) {
        return isoDep.getTag();
    }
    return null;
}
 
Example 24
Project: qpboc-kata   File: IsoDepAdapter.java   Source Code and License 5 votes vote down vote up
/**
 * Callback when a new tag is discovered by the system.
 *
 * <p>Communication with the card should take place here.
 *
 * @param tag Discovered tag
 */
public void onTagDiscovered(Tag tag){

    LogUtil.i(TAG, "======= Discovered Tag:" + tag + "==========");

    // Android's Host-based Card Emulation (HCE) feature implements the ISO-DEP (ISO 14443-4)
    // protocol.
    //
    // In order to communicate with a device using HCE, the discovered tag should be processed
    // using the IsoDep class.

    mIsoDep = IsoDep.get(tag);

    // Connect to the remote NFC device
    try {
        mIsoDep.connect();
    } catch (IOException e) {
        e.printStackTrace();
    }

    mIsoDep.setTimeout(TIMEOUT);

}
 
Example 25
Project: coinblesk-client-gui   File: NFCServerCLTV.java   Source Code and License 5 votes vote down vote up
private byte[] concatNextResponseBytes(IsoDep isoDep, byte[] derResponse) throws IOException {
    int responseLength = DERParser.extractPayloadEndIndex(derResponse);
    Log.d(TAG, "transceiveDER - expected response length: " + responseLength + ", actual length: " + derResponse.length);
    while (derResponse.length < responseLength) {
        derResponse = ClientUtils.concatBytes(derResponse, transceiveKeepAlive(isoDep));
        Log.d(TAG, "transceiveDER - had to ask for next bytes, length=" + derResponse.length);
    }
    return derResponse;
}
 
Example 26
Project: coinblesk-client-gui   File: NFCServerCLTV.java   Source Code and License 5 votes vote down vote up
private byte[] keepAliveLoop(IsoDep isoDep, byte[] derResponse) throws IOException {
    while (NFCUtils.isKeepAlive(derResponse) ) {
        Log.d(TAG, "transceiveDER - keep alive...");
        derResponse = transceiveKeepAlive(isoDep);
        Log.d(TAG, "transceiveDER - keep alive done, got response, length=" + derResponse.length);
    }
    return derResponse;
}
 
Example 27
Project: coinblesk-client-gui   File: NFCServerCLTV.java   Source Code and License 5 votes vote down vote up
private void softResetNFC(final Tag tag) {
    try {
        Log.d(TAG, "try soft reset");
        IsoDep isoDep = IsoDep.get(tag);
        isoDep.close();
        isoDep.connect();
        Log.d(TAG, "soft reset successful");
        onTagDiscovered(tag, isoDep, false);
    } catch (Throwable e) {
        Log.d(TAG, "Soft reset failed", e);
    }
}
 
Example 28
Project: hipay-fullservice-sdk-android   File: PaymentFormActivity.java   Source Code and License 5 votes vote down vote up
@Override
protected void onNewIntent(final Intent intent) {
    super.onNewIntent(intent);

    if (intent != null && intent.getAction().equalsIgnoreCase(NfcAdapter.ACTION_TECH_DISCOVERED)) {

        Tag tag = intent.getParcelableExtra(NfcAdapter.EXTRA_TAG);
        IsoDep isoDep = IsoDep.get(tag);

        if (isoDep != null) {

            new NFCAsyncTask().execute(isoDep);
        }
    }
}
 
Example 29
Project: Android-NFC-Paycard-Reader   File: HomeActivity.java   Source Code and License 5 votes vote down vote up
/**
 * Get ATS from isoDep
 *
 * @param pIso
 *            isodep
 * @return ATS byte array
 */
private byte[] getAts(final IsoDep pIso) {
	byte[] ret = null;
	if (pIso.isConnected()) {
		// Extract ATS from NFC-A
		ret = pIso.getHistoricalBytes();
		if (ret == null) {
			// Extract ATS from NFC-B
			ret = pIso.getHiLayerResponse();
		}
	}
	return ret;
}
 
Example 30
Project: Travel-Card-Reminder   File: ReadCardActivity.java   Source Code and License 5 votes vote down vote up
private TravelCard readCardData(Intent intent) {
    Tag tagFromIntent = intent.getParcelableExtra(NfcAdapter.EXTRA_TAG);
    IsoDep isoDep = IsoDep.get(tagFromIntent);

    try {
        isoDep.connect();
        return CardOperations.readTravelCardData(isoDep);
    } catch (IOException ioErr) {
        Toast err = Toast.makeText(this, ioErr.getMessage(), Toast.LENGTH_LONG);
        err.show();
        return new TravelCard(TravelCard.STATUS_NO_HSL_CARD);
    }
}
 
Example 31
Project: android-u2f-demo   File: SignFragment.java   Source Code and License 5 votes vote down vote up
public void onResume() {
    super.onResume();

    Intent intent = getActivity().getIntent();
    intent.setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
    PendingIntent tagIntent = PendingIntent.getActivity(getActivity(), 0, intent, 0);
    IntentFilter iso = new IntentFilter(NfcAdapter.ACTION_TECH_DISCOVERED);
    adapter.enableForegroundDispatch(getActivity(), tagIntent, new IntentFilter[]{iso},
            new String[][]{new String[]{IsoDep.class.getName()}});
}
 
Example 32
Project: android-u2f-demo   File: EnrollFragment.java   Source Code and License 5 votes vote down vote up
public void onResume() {
    super.onResume();

    Intent intent = getActivity().getIntent();
    intent.setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
    PendingIntent tagIntent = PendingIntent.getActivity(getActivity(), 0, intent, 0);
    IntentFilter iso = new IntentFilter(NfcAdapter.ACTION_TECH_DISCOVERED);
    adapter.enableForegroundDispatch(getActivity(), tagIntent, new IntentFilter[]{iso},
            new String[][]{new String[]{IsoDep.class.getName()}});
}
 
Example 33
Project: android-u2f-demo   File: U2F_V2.java   Source Code and License 5 votes vote down vote up
public U2F_V2(IsoDep tag) throws IOException, APDUError {
    this.tag = tag;
    tag.setTimeout(5000);
    tag.connect();
    try {
        send(SELECT_COMMAND);
    } catch (APDUError e) {
        if(e.getCode() == 0x6a82) {
            send(SELECT_COMMAND_YUBICO);
        } else {
            throw e;
        }
    }
}
 
Example 34
Project: android-u2f-demo   File: MainActivity.java   Source Code and License 5 votes vote down vote up
@Override
protected void onNewIntent(Intent intent) {
    Tag tag = intent.getParcelableExtra(NfcAdapter.EXTRA_TAG);
    if(tag != null && nfc_listener != null) {
        nfc_listener.onNFC(IsoDep.get(tag));
    }
}
 
Example 35
Project: IDCardReader   File: MainActivity.java   Source Code and License 5 votes vote down vote up
private void handleIntent(Intent intent) {
    final String action = intent.getAction();

    if (NfcAdapter.ACTION_TECH_DISCOVERED.equals(action) || NfcAdapter.ACTION_TAG_DISCOVERED.equals(action)) {
        Log.d(TAG, "TECH_DISCOVERED");

        final Parcelable tag = intent.getParcelableExtra(NfcAdapter.EXTRA_TAG);
        final IsoDep iso = IsoDep.get((Tag) tag);

        try {
            iso.connect();

            doGetApps(iso);
            doSelectPICC(iso);
            doGetFileIDs(iso);

            final String expiry = doGetFile(iso, (byte)0x02, (byte)0x0A);
            final String idNumber = doGetFile(iso, (byte)0x03, (byte)0x09);

            fillFields(idNumber, expiry);

            iso.close();
        } catch (IOException io) {
            Log.e(TAG, "Error communicating: " + io.toString());
        }
    }
}
 
Example 36
Project: nfcspy   File: NfcManager.java   Source Code and License 5 votes vote down vote up
static String getCardId(IsoDep isodep) {
	if (isodep != null) {
		byte[] id = isodep.getTag().getId();
		if (id != null && id.length > 0)
			return Logger.toHexString(id, 0, id.length);
	}

	return "UNKNOWN";
}
 
Example 37
Project: nfcspy   File: NfcManager.java   Source Code and License 5 votes vote down vote up
static void disconnect(IsoDep tag) {
	try {
		if (tag != null)
			tag.close();
	} catch (Exception e) {
	}
}
 
Example 38
Project: nfcspy   File: NfcManager.java   Source Code and License 5 votes vote down vote up
static byte[] transceiveApdu(IsoDep tag, byte[] cmd) {
	if (tag != null) {
		try {
			if (!tag.isConnected()) {
				tag.connect();
				tag.setTimeout(10000);
			}

			return tag.transceive(cmd);
		} catch (Exception e) {
		}
	}
	return null;
}
 
Example 39
Project: nordpol   File: TagDispatcher.java   Source Code and License 5 votes vote down vote up
private void enableForegroundDispatch(NfcAdapter adapter, Intent intent) {
    if(adapter.isEnabled()) {
        PendingIntent tagIntent = PendingIntent.getActivity(activity, 0, intent, PendingIntent.FLAG_CANCEL_CURRENT);
        IntentFilter tag = new IntentFilter(NfcAdapter.ACTION_TECH_DISCOVERED);
        adapter.enableForegroundDispatch(activity, tagIntent, new IntentFilter[]{tag},
                                         new String[][]{new String[]{IsoDep.class.getName()}});
    }
}
 
Example 40
Project: nfcard   File: StandardPboc.java   Source Code and License 5 votes vote down vote up
public static void readCard(IsoDep tech, Card card) throws InstantiationException,
		IllegalAccessException, IOException {

	final Iso7816.StdTag tag = new Iso7816.StdTag(tech);

	tag.connect();

	for (final Class<?> g[] : readers) {
		HINT hint = HINT.RESETANDGONEXT;

		for (final Class<?> r : g) {

			final StandardPboc reader = (StandardPboc) r.newInstance();

			switch (hint) {

			case RESETANDGONEXT:
				if (!reader.resetTag(tag))
					continue;

			case GONEXT:
				hint = reader.readCard(tag, card);
				break;

			default:
				break;
			}

			if (hint == HINT.STOP)
				break;
		}
	}

	tag.close();
}
 
Example 41
Project: BitcoinCardTerminal   File: NFCWrapper.java   Source Code and License 5 votes vote down vote up
protected void newCard(Tag card){ //Should cause card disconnect and replacing. Current task cancelled.
	Enter(outsideThread);
		newCard = IsoDep.get(card);
		if(workerThreadReference != null)
			workerThreadReference.interrupt();
	Leave(outsideThread);
}
 
Example 42
Project: NFCard   File: StandardPboc.java   Source Code and License 5 votes vote down vote up
public static void readCard(IsoDep tech, Card card) throws InstantiationException,
		IllegalAccessException, IOException {

	final Iso7816.StdTag tag = new Iso7816.StdTag(tech);

	tag.connect();

	for (final Class<?> g[] : readers) {
		HINT hint = HINT.RESETANDGONEXT;

		for (final Class<?> r : g) {

			final StandardPboc reader = (StandardPboc) r.newInstance();

			switch (hint) {

			case RESETANDGONEXT:
				if (!reader.resetTag(tag))
					continue;

			case GONEXT:
				hint = reader.readCard(tag, card);
				break;

			default:
				break;
			}

			if (hint == HINT.STOP)
				break;
		}
	}

	tag.close();
}
 
Example 43
Project: bankomatinfos   File: NfcBankomatCardReader.java   Source Code and License 5 votes vote down vote up
/**
 * Connects to IsoDep
 * 
 * @throws IOException
 */
public void connectIsoDep() throws IOException, NoSmartCardException {
	_localIsoDep = IsoDep.get(_nfcTag);
	if (_localIsoDep == null) {
		throw new NoSmartCardException("This NFC tag is no ISO 7816 card");
	}
	_localIsoDep.connect();
}
 
Example 44
Project: WalletCordova   File: TagDispatcher.java   Source Code and License 5 votes vote down vote up
private void enableForegroundDispatch(NfcAdapter adapter, Intent intent) {
    if(adapter.isEnabled()) {
        PendingIntent tagIntent = PendingIntent.getActivity(activity, 0, intent, PendingIntent.FLAG_CANCEL_CURRENT);
        IntentFilter tag = new IntentFilter(NfcAdapter.ACTION_TECH_DISCOVERED);

        adapter.enableForegroundDispatch(activity, tagIntent, new IntentFilter[]{tag},
                                         new String[][]{new String[]{IsoDep.class.getName()}});
    }
}
 
Example 45
Project: CampusCardReader   File: CardReaderIntentService.java   Source Code and License 5 votes vote down vote up
@Override
protected void onHandleIntent(Intent intent) {
    if(BuildConfig.DEBUG) {
        Log.i(this.getClass().getName(), "CardReaderService started");
    }
    // get an instance of the nfc tag to communicate
    IsoDep isodep = IsoDep.get((Tag)intent.getParcelableExtra(NfcAdapter.EXTRA_TAG));
    if(isodep != null) {
        try {
            // connect to the nfc tag
            isodep.connect();
            // select application which contains the credit and last transaction
            resultOk = isodep.transceive(selectAid);
            if (resultOk[0] == 0) {
                // get the credit
                creditBytes = isodep.transceive(creditPayload);
                // get the last transaction
                lastTransactionBytes = isodep.transceive(transactionPayload);
            } else {
                if (BuildConfig.DEBUG) {
                    Log.w(this.getClass().getName(), "Wrong result: " + arrayToString(resultOk));
                }
            }
            isodep.close();
        } catch (IOException e) {
            // nfc-card wasn't properly connected and thus wasn't read
            if (BuildConfig.DEBUG) {
                Log.e(this.getClass().getName(), e.getMessage());
            }
            statusCode = STATUS_UNKNOWN_ERROR;
        }
    }else{
        // i think this gets executed if an unsupported nfc-card gets connected
        // however i'm unable to test this because i have no other card to test it
        statusCode = STATUS_UNKNOWN_NFC_CARD_ERROR;
    }
    // send data back to the MainActivity
    sendBroadcast();
}
 
Example 46
Project: CampusCardReader   File: MainActivity.java   Source Code and License 5 votes vote down vote up
private void setUpNfcStuff(){
    // intercept all NFC related Intents and redirect them to this activity while this activity is activated and on the front
    // this is called the "foreground dispatch"
    mAdapter = NfcAdapter.getDefaultAdapter(this);
    mPendingIntent = PendingIntent.getActivity(this, 0,
            new Intent(this, getClass()).addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP),0);
    IntentFilter  nfcTech = new IntentFilter(NfcAdapter.ACTION_TECH_DISCOVERED);
    mFilters = new IntentFilter[]{nfcTech};
    mTechLists = new String[][] {
            new String[] { IsoDep.class.getName() },
            {NfcA.class.getName()}
    };
}
 
Example 47
Project: smartcard-reader   File: ReaderXcvr.java   Source Code and License 5 votes vote down vote up
public ReaderXcvr(IsoDep isoDep, String aid, UiCallbacks uiCallbacks) {
    this.mIsoDep = isoDep;
    this.mAid = aid;
    this.mAidBytes = Util.hexToBytes(aid);
    this.mUiCallbacks = uiCallbacks;
    this.mContext = (Context) uiCallbacks;
}
 
Example 48
Project: smartcard-reader   File: ReaderXcvr.java   Source Code and License 5 votes vote down vote up
public ReaderXcvr(IsoDep isoDep, String aid, UiCallbacks uiCallbacks, Context context) {
    this.mIsoDep = isoDep;
    this.mAid = aid;
    this.mAidBytes = Util.hexToBytes(aid);
    this.mUiCallbacks = uiCallbacks;
    this.mContext = context;
}
 
Example 49
Project: smartcard-reader   File: AppSelectActivity.java   Source Code and License 5 votes vote down vote up
@Override
public void onTagDiscovered(Tag tag) {
    doTapFeedback();
    clearImage();
    // maybe clear console or show separator, depends on settings
    if (mAutoClear) {
        clearMessages();
    } else {
        addMessageSeparator();
    }
    // get IsoDep handle and run xcvr thread
    IsoDep isoDep = IsoDep.get(tag);
    if (isoDep == null) {
        onError(getString(R.string.wrong_tag_err));
    } else {
        ReaderXcvr xcvr;
        String aid = mApps.get(mSelectedAppPos).getAid();

        if (mManual) {
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    Animation shake = AnimationUtils.loadAnimation(AppSelectActivity.this, R.anim.shake);
                    mSelectButton.startAnimation(shake);
                }
            });
            // manual select mode; for multiple selects per tap/connect
            // does not select ppse for payment apps unless specifically configured
            xcvr = new ManualReaderXcvr(isoDep, aid, this);
        } else if (mApps.get(mSelectedAppPos).getType() == SmartcardApp.TYPE_PAYMENT) {
            // payment, ie. always selects ppse first
            xcvr = new PaymentReaderXcvr(isoDep, aid, this, TEST_MODE_APP_SELECT);
        } else {
            // other/non-payment; auto select on each tap/connect
            xcvr = new OtherReaderXcvr(isoDep, aid, this);
        }

        new Thread(xcvr).start();
    }
}
 
Example 50
Project: smartcard-reader   File: BatchReaderXcvr.java   Source Code and License 5 votes vote down vote up
public BatchReaderXcvr(IsoDep isoDep, List<SmartcardApp> apps,
                       ReaderXcvr.UiCallbacks uiCallbacks) {
    mIsoDep = isoDep;
    mApps = apps;
    mUiCallbacks = uiCallbacks;
    mContext = (Context) uiCallbacks;
    mSize = apps.size();
    mIndex = 0;
}
 
Example 51
Project: NFCSocket   File: NfcClientSocket.java   Source Code and License 5 votes vote down vote up
@Override
public void onTagDiscovered(Tag tag) {
    currentTag = tag;
    isoDep = IsoDep.get(currentTag);

    if (listenerSet != null) {
        for (NfcClientSocketListener listener : listenerSet) {
            if (listener != null) {
                listener.onDiscoveryTag();
            }
        }
    }
}
 
Example 52
Project: EMV-NFC-Paycard-Enrollment   File: HomeActivity.java   Source Code and License 5 votes vote down vote up
/**
 * Get ATS from isoDep
 *
 * @param pIso
 *            isodep
 * @return ATS byte array
 */
private byte[] getAts(final IsoDep pIso) {
	byte[] ret = null;
	if (pIso.isConnected()) {
		// Extract ATS from NFC-A
		ret = pIso.getHistoricalBytes();
		if (ret == null) {
			// Extract ATS from NFC-B
			ret = pIso.getHiLayerResponse();
		}
	}
	return ret;
}
 
Example 53
Project: nfc-reader-app   File: SendFileToWISP.java   Source Code and License 5 votes vote down vote up
/**
 * Use 14443-4 block write to transfer the given number of blocks of the
 * given source buffer to the given tag
 * 
 * @param isodep
 *            Object representing IO access for a certain 14443-4 tag
 * //@param blockBuffer
 *            the byte buffer to transmit
 * //@param index
 *            How far we currently are indexed into that buffer
 * @param numOfBlocks
 *            Number of blocks to send at a time
 * @return Success or failure
 */
private byte[] writeNBlocks(IsoDep isodep, int numOfBlocks, int chunkIndex,
		byte[] myImgBuffer, byte flags) {
	byte[] response;

	try {

		byte write_multi_block_command[] = new byte[(4 * numOfBlocks) + 2];
		write_multi_block_command[0] = flags;
		write_multi_block_command[1] = (byte) (chunkIndex);

		for (int curBlock = 0; curBlock < 4 * numOfBlocks; curBlock++) {
               int index;
               index = curBlock + chunkIndex * numOfBlocks * 4;
               if(index>= myImgBuffer.length)index = myImgBuffer.length-1;
			write_multi_block_command[curBlock + INF_DATA_START_INDEX] = myImgBuffer[index];
		}

		response = isodep.transceive(write_multi_block_command);

	} catch (IOException e) {
		// Throws an error anyway, even if correctly written a block
		return null;
	}// end catch

	return response;

}
 
Example 54
Project: nfc-reader-app   File: SendFileToWISP.java   Source Code and License 5 votes vote down vote up
/**
 * Use 14443-4 block write to transfer the given number of blocks of the
 * given source buffer to the given tag
 *
 * @param isodep
 *            Object representing IO access for a certain 14443-4 tag
 * //@param blockBuffer
 *            the byte buffer to transmit
 * //@param index
 *            How far we currently are indexed into that buffer
 * @param numOfBlocks
 *            Number of blocks to send at a time
 * @return Success or failure
 */
private byte[] sendPowerBlocks(IsoDep isodep, int numOfBlocks, int chunkIndex,
                            byte[] myImgBuffer, byte flags) {
    byte[] response;

    try {

        byte write_multi_block_command[] = new byte[(4 * numOfBlocks) + 2];
        write_multi_block_command[0] = flags;
        write_multi_block_command[1] = (byte) (chunkIndex);

        for (int curBlock = 0; curBlock < 4 * numOfBlocks; curBlock++) {
            int index;
            index = curBlock + chunkIndex * numOfBlocks * 4;
            if(index>= myImgBuffer.length)index = myImgBuffer.length-1;
            write_multi_block_command[curBlock + INF_DATA_START_INDEX] = myImgBuffer[index];
        }

        response = isodep.transceive(write_multi_block_command);

    } catch (IOException e) {
        // Throws an error anyway, even if correctly written a block
        return null;
    }// end catch

    return response;

}
 
Example 55
Project: irma_android_management   File: CredentialListActivity.java   Source Code and License 5 votes vote down vote up
public void processIntent(Intent intent) {
    tag = intent.getParcelableExtra(NfcAdapter.EXTRA_TAG);
	IsoDep isotag = IsoDep.get(tag);
	if (isotag != null) {
		// We are waiting for the card, notify dialog
		if (currentState == State.WAITING_FOR_CARD) {
			cardMissingDialog.dismiss();
			gotoState(State.TEST_CARD_PRESENCE);
		}
	}
}
 
Example 56
Project: irma_android_management   File: WaitingForCardActivity.java   Source Code and License 5 votes vote down vote up
@Override
protected void onCreate(Bundle savedInstanceState) {
	super.onCreate(savedInstanceState);
	setContentView(R.layout.activity_waiting_for_card);
	
	// Make sure all configuration files can be found
    AndroidWalker aw = new AndroidWalker(getResources().getAssets());
    DescriptionStore.setTreeWalker(aw);
    IdemixKeyStore.setTreeWalker(aw);
    
    try {
		DescriptionStore.getInstance();
	} catch (InfoException e) {
		Log.e("error", "something went wrong");
		e.printStackTrace();
		AlertDialogFragment f = AlertDialogFragment.getInstance("Cannot load Description Store", e.getMessage());
		f.show(getFragmentManager(), "alert");
		setState(STATE_ERROR);
	}
	
       // NFC stuff
       nfcA = NfcAdapter.getDefaultAdapter(getApplicationContext());
       mPendingIntent = PendingIntent.getActivity(this, 0,
               new Intent(this, getClass()).addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP), 0);

       // Setup an intent filter for all TECH based dispatches
       IntentFilter tech = new IntentFilter(NfcAdapter.ACTION_TECH_DISCOVERED);
       mFilters = new IntentFilter[] { tech };

       // Setup a tech list for all IsoDep cards
       mTechLists = new String[][] { new String[] { IsoDep.class.getName() } };
       
       // Set initial state
       setState(STATE_IDLE);
       
       if(getIntent() != null) {
       	onNewIntent(getIntent());
       }
}
 
Example 57
Project: nfc-smime   File: MainActivity.java   Source Code and License 5 votes vote down vote up
@Override
protected void onCreate(Bundle savedInstanceState) {
    StrictMode.setThreadPolicy(StrictMode.ThreadPolicy.LAX);

    requestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS);

    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    fromText = (TextView) findViewById(R.id.from_text);
    toText = (EditText) findViewById(R.id.to_text);
    toText.setText(DEFAULT_RECIPIENT);
    subjectText = (EditText) findViewById(R.id.subject_text);
    bodyText = (EditText) findViewById(R.id.body_text);
    messageText = (TextView) findViewById(R.id.message);

    sendMailButton = (Button) findViewById(R.id.send_mail_button);
    sendMailButton.setOnClickListener(this);
    importPkcs12Button = (Button) findViewById(R.id.import_pkcs12_button);
    importPkcs12Button.setOnClickListener(this);
    nfcSignButton = (Button) findViewById(R.id.send_mail_nfc_button);
    nfcSignButton.setOnClickListener(this);
    nfcSignButton.setEnabled(false);

    adapter = NfcAdapter.getDefaultAdapter(this);

    pendingIntent = PendingIntent.getActivity(this, 0, new Intent(this,
            getClass()).addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP), 0);

    IntentFilter techDiscovered = new IntentFilter(
            NfcAdapter.ACTION_TECH_DISCOVERED);
    filters = new IntentFilter[] { techDiscovered };
    techLists = new String[][] { new String[] { IsoDep.class.getName() } };

    tryLoadFromKeyStore();
}
 
Example 58
Project: irma_android_cardproxy   File: MainActivity.java   Source Code and License 5 votes vote down vote up
public void processIntent(Intent intent) {
    Tag tagFromIntent = intent.getParcelableExtra(NfcAdapter.EXTRA_TAG);
	IsoDep tag = IsoDep.get(tagFromIntent);
	// Only proces tag when we're actually expecting a card.
	if (tag != null && activityState == STATE_CONNECTED) {
		setState(STATE_READY);
		postMessage(new ReaderMessage(ReaderMessage.TYPE_EVENT, ReaderMessage.NAME_EVENT_CARDFOUND, null));
		lastTag = tag;
	}    	
}
 
Example 59
Project: yubitotp-android   File: TotpGenerator.java   Source Code and License 5 votes vote down vote up
private void doChallengeYubiKey(IsoDep isoTag, int slot) throws IOException {
	long time = System.currentTimeMillis() / 1000 / totp_step;
	byte apdu[] = new byte[totpCommand.length + 4];
	System.arraycopy(totpCommand, 0, apdu, 0, totpCommand.length);

	switch(slot) {
	case 1:
		apdu[2] = SLOT_CHAL_HMAC1;
		break;
	case 2:
		apdu[2] = SLOT_CHAL_HMAC2;
		break;
	}

	apdu[totpCommand.length] = (byte) (time >> 24);
	apdu[totpCommand.length + 1] = (byte) (time >> 16);
	apdu[totpCommand.length + 2] = (byte) (time >> 8);
	apdu[totpCommand.length + 3] = (byte) time;

	byte[] totpApdu = isoTag.transceive(apdu);
	if(totpApdu.length == 22 && totpApdu[20] == (byte)0x90 && totpApdu[21] == 0x00) {
		int offset = totpApdu[19] & 0xf;
		int code = ((totpApdu[offset++] & 0x7f) << 24) |
				((totpApdu[offset++] & 0xff) << 16) |
				((totpApdu[offset++] & 0xff) << 8) |
				((totpApdu[offset++] & 0xff));
		String totp = String.format("%06d", code % 1000000);
		Intent data = getIntent();
		data.putExtra("totp", totp);
		setResult(RESULT_OK, data);
	} else {
		Toast.makeText(this, R.string.totp_failed, Toast.LENGTH_LONG).show();
	}
}
 
Example 60
Project: yubitotp-android   File: TotpGenerator.java   Source Code and License 5 votes vote down vote up
private void doProgramYubiKey(IsoDep isoTag, int slot, String secret) throws IOException {
	Base32 base32 = new Base32();
	byte[] decoded = base32.decode(secret.toUpperCase());
	byte[] key = new byte[20];
	System.arraycopy(decoded, 0, key, 0, decoded.length);

	byte[] apdu = new byte[64];
	apdu[1] = 0x01;
	apdu[2] = slot == 1 ? SLOT_CONFIG : SLOT_CONFIG2;

	Configurator cfg = new Configurator();
	cfg.setKey(Configurator.HMAC_SHA1_MODE, key);
	cfg.setCfgFlags((byte) (Configurator.CFGFLAG_CHAL_HMAC | Configurator.CFGFLAG_HMAC_LT64));
	cfg.setTktFlags(Configurator.TKTFLAG_CHAL_RESP);
	cfg.setExtFlags((byte) (Configurator.EXTFLAG_SERIAL_API_VISIBLE | Configurator.EXTFLAG_ALLOW_UPDATE));
	byte[] structure = cfg.getConfigStructure();
	apdu[4] = (byte) structure.length;
	System.arraycopy(structure, 0, apdu, 5, structure.length);

	byte[] resp = isoTag.transceive(apdu);
	if(resp[resp.length - 2] == (byte)0x90 && resp[resp.length - 1] == 0x00) {
		setResult(RESULT_OK, getIntent());
	} else {
		Toast.makeText(this, R.string.prog_fail, Toast.LENGTH_LONG).show();
		setResult(RESULT_CANCELED);
	}
}