Back to project page android-nfc-reader.
The source code is released under:
MIT License
If you think the Android project android-nfc-reader listed in this page is inappropriate, such as containing malicious code/tools or violating the copyright, please email info at java2s dot com, thanks.
package net.mklbravo.lib.nfcreader.readers; /* ww w .ja va2 s. c o m*/ import android.nfc.Tag; import android.nfc.tech.MifareClassic; import net.mklbravo.lib.nfcreader.tags.MifareClassicTag; import net.mklbravo.lib.nfcreader.utils.Converter; import java.io.IOException; import java.util.ArrayList; public class MifareClassicReader extends AbstractReader { private final int MIFARE_SECTOR_COUNT = 16; private ArrayList<String> passwords = new ArrayList<String>(); private MifareClassicTag mifareTag; private int sectorsToRead = 16; public MifareClassicReader(Tag pAndroidTag) { super(pAndroidTag); initializeReader(); } public MifareClassicReader(Tag pAndroidTag, int pSectorsToRead){ super(pAndroidTag); initializeReader(); } private void initializeReader(){ mifareTag = new MifareClassicTag(tagId); setDefaultPasswords(); } private void setDefaultPasswords(){ setReadPassword("A0A1A2A3A4A5"); } public MifareClassicTag getMifareClassicTag(){ return mifareTag; } @Override public void setReadPassword(String pPassword) { passwords.add(0,pPassword); } @Override public void readTag() { try { MifareClassic androidMifare = MifareClassic.get(androidTag); androidMifare.connect(); for (int sectorIndex = 0; sectorIndex < MIFARE_SECTOR_COUNT; sectorIndex++) { readSector(androidMifare,sectorIndex); } } catch (IOException e) { //TODO } } private void readSector(MifareClassic tag,int sectorIndex) throws IOException{ if (authenticateSector(tag,sectorIndex)) { int blockCount = tag.getBlockCountInSector(sectorIndex); int firstBlockIndex = tag.sectorToBlock(sectorIndex); for (int blockIndex = 0; blockIndex < blockCount; blockIndex++) { byte[] data = tag.readBlock(firstBlockIndex + blockIndex); mifareTag.addData(sectorIndex,blockIndex,data); } } } private boolean authenticateSector(MifareClassic tag,int sectorIndex) throws IOException{ if(passwords.isEmpty())return false; boolean authOk = false; for(String psw: passwords ){ byte[] bytePsw = Converter.hexStringToByteArray(psw); authOk = tag.authenticateSectorWithKeyA(sectorIndex,bytePsw); if(authOk) break; } return authOk; } }