写入 mifareclassic 标签的问题

problem with writing to mifareclassic tag

我正在尝试读取和写入 MifareClassic 标签。到目前为止,我已经能够将我的应用程序设置为在前台接收意图。要读取标签,我首先获取一个 MifareClassic 实例,对其进行身份验证并读取一个块。它工作正常。

但是当我写入标签时没有任何反应。代码似乎没有任何问题地执行,但标签上的数据没有改变。有趣的是,我试图在没有先进行身份验证的情况下写入标签。代码再次执行而没有抛出任何异常。但是当我尝试 读取 一个块而不先进行身份验证时,我得到了一个异常(收发失败)。

    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        nfcAdapter = NfcAdapter.getDefaultAdapter(this);


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

        IntentFilter ndef = new IntentFilter(NfcAdapter.ACTION_TECH_DISCOVERED);
        filters =  new IntentFilter[] {ndef, };
        techListsArray = new String[][] { new String[] { MifareClassic.class.getName()} };

        if(nfcAdapter!=null && nfcAdapter.isEnabled() ){}
        else{

            Toast.makeText(this, "nfc not available", Toast.LENGTH_LONG).show();
            //finish();
        }
    }


    @Override
    protected void onResume() {
        super.onResume();
        nfcAdapter.enableForegroundDispatch(this, pendingIntent, filters, techListsArray);

    }

    @Override
    protected void onPause() {
        super.onPause();
        nfcAdapter.disableForegroundDispatch(this);

    }


protected void onNewIntent(Intent intent) {
    super.onNewIntent(intent);
    Tag tagFromIntent = intent.getParcelableExtra(NfcAdapter.EXTRA_TAG);



    MifareClassic mfc = MifareClassic.get(tagFromIntent);
    mfc.connect();
    byte [] data2=new byte[16];
    for(int i =0;i<16;i++)
        data2[i]=0;

   //auth = mfc.authenticateSectorWithKeyA(4, key[1]);

    int blo=mfc.sectorToBlock(4);
    mfc.writeBlock(blo,data2);
    mfc.close();}

我想通了。

卡上有关数据块的访问位设置为 100。因此根据 MifareClassic 文档,为了能够写入此块,我应该使用密钥 B。(但我能够读取带有键 A)

的块

显然,如果您使用错误的密钥对卡进行身份验证,然后调用 writeblock(block,data),您不会得到异常。同时,如果您使用错误的密钥进行身份验证,然后调用 readblock(block),您将得到一个异常。

显然你完全可以不进行身份验证并调用 writeblock 函数。而且您仍然不会例外。但数据不会写入卡中。