Ejemplo n.º 1
0
        public byte[] ReadByteBlock(int block, byte[] key, NfcKeyType nfcKeyType)
        {
            //TODO 4. MIFARE OPERATIONS 2
            try
            {
                //No card found
                if (!LoadCurrentMifareClassic())
                {
                    return(null);
                }

                //Different card ids
                if (!CheckCardId())
                {
                    return(null);
                }

                //No authenticated
                if (!AuthenticateSector(block, nfcKeyType, key))
                {
                    return(null);
                }

                byte[] data = currentMifareClassic.ReadBlock(block);
                return(data);
            }
            catch
            {
                return(null);
            }
        }
Ejemplo n.º 2
0
 public static void MifareTest()
 {
     using (var context = new NfcContext())
         using (var device = context.OpenDevice()) // Try to open the NFC reader
         {
             MifareClassic mfc = new MifareClassic(device);
             mfc.InitialDevice();
             mfc.SelectCard();
             mfc.Authentication(0, KeyType.KeyA, 0xFFFFFFFFFFFFu);
             var block0 = mfc.ReadBlock(0);
             Program.PrintHex(block0, 16);
             mfc.Authentication(1, KeyType.KeyA, 0xFFFFFFFFFFFFu);
             mfc.WriteBlock(4, new byte[16] {
                 1, 2, 3, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0
             });
             var block4 = mfc.ReadBlock(4);
             Program.PrintHex(block4, 16);
             Console.ReadLine();
         }
 }
Ejemplo n.º 3
0
        public List <byte[]> MifareClassic_ReadSector(MifareClassic mfc, int Sector)
        {
            int blockCount = mfc.GetBlockCountInSector(Sector);
            var lst        = new List <byte[]>(blockCount);
            int readIndex  = mfc.SectorToBlock(1);

            for (int i = 0; i < blockCount; i++)
            {
                lst[i] = mfc.ReadBlock(readIndex);
                readIndex++;
            }
            return(lst);
        }
Ejemplo n.º 4
0
        private bool TryAndReadFromTag(Tag tag)
        {
            MifareClassic mfc = MifareClassic.Get(tag);

            byte[] data;
            bool   auth = false;

            try
            {
                mfc.Connect();
                String UID      = byte2hex(mfc.Tag.GetId());
                String cardData = null;
                int    secCount = 1;
                int    bCount   = 3; //Just read 2 block for now
                int    bIndex   = 0;
                for (int j = 1; j <= secCount; j++)
                {
                    auth = mfc.AuthenticateSectorWithKeyB(j, KEY_DEFAULT);
                    if (auth)
                    {
                        //bCount = mfc.GetBlockCountInSector(j);
                        bIndex = mfc.SectorToBlock(j);
                        for (int i = 0; i < bCount; i++)
                        {
                            data      = mfc.ReadBlock(bIndex);
                            cardData += Encoding.ASCII.GetString(data);
                            bIndex++;
                        }
                        DisplayMessage(cardData);
                        mfc.Close();
                        return(true);
                    }
                    else
                    {
                        Log.Error(Tag, "Sector read authentication failed");
                        mfc.Close();
                        return(false);
                    }
                }
            }
            catch (Exception e)
            {
                Log.Error(Tag, e.Message);
            }
            return(false);
        }
Ejemplo n.º 5
0
        private void ReadIcData(Intent intent)
        {
            m_intent    = intent;
            ic.icserial = ic.FindIC(m_intent);

            Car = new CarInfo();    //初始化一个CarInfo类

            //取出封装在intent中的TAG
            var tag = intent.GetParcelableExtra(NfcAdapter.ExtraTag) as Tag;

            if (tag == null)
            {
                return;
            }
            m_tag = tag;

            #region 清空文本
            carNumber      = FindViewById <EditText>(Resource.Id.carNumber);
            carNumber.Text = "";
            #endregion

            MifareClassic mfc = MifareClassic.Get(m_tag);
            if (mfc != null)
            {
                #region 获取到tag
                try
                {
                    mfc.Connect();
                    var type = mfc.GetType();
                    if (type.Equals(typeof(Android.Nfc.Tech.MifareClassic)))
                    {
                        #region 循环读取5个扇区数据
                        for (int i = 0; i < ic.sectors.Length; i++)
                        {
                            for (int k = 0; k < 3; k++)
                            {
                                int sec = mfc.BlockToSector(ic.sectors[i] * 4 + k);
                                if (sec < mfc.SectorCount)
                                {
                                    if (mfc.AuthenticateSectorWithKeyB(sec, ic.ToDigitsBytes(ic.mb)))
                                    {
                                        int c = mfc.SectorCount;
                                        c = mfc.BlockCount;

                                        byte[] data = new byte[16];
                                        data = mfc.ReadBlock(ic.sectors[i] * 4 + k);
                                        if (data != null)
                                        {
                                            ic.IcDatas[i, k] = ic.ToHexString(data);
                                            ic.isReadIcOK    = true;
                                        }
                                        else
                                        {
                                            CommonFunction.ShowMessage("读取" + ic.sectors[i].ToString() + "扇区" + Convert.ToString(ic.sectors[i] * 4 + k) + "块失败!", this, true);
                                            ic.isReadIcOK = false;
                                            return;
                                        }
                                    }
                                    else
                                    {
                                        CommonFunction.ShowMessage("密码验证失败!", this, true);
                                        ic.isReadIcOK = false;
                                        return;
                                    }
                                }
                            }
                        }
                        #endregion
                    }
                }
                catch (Exception ex)
                {
                    CommonFunction.ShowMessage(ex.Message, this, true);
                }
                finally
                {
                    mfc.Close();
                }

                if (ic.isReadIcOK)
                {
                    try
                    {
                        //解析扇区数据
                        Car = ic.GetCarInfo(ic.IcDatas);

                        if (Car != null)
                        {
                            CommonFunction.ShowMessage("", this, false);

                            #region 读卡正确,显示在窗体文本内,按钮复活

                            carNumber.Text = Car.CarPlate;
                            // carNumber.Text = "GT030108";//暂用

                            //根据车号查询 相关收发货路线信息
                            goodsInfo();
                            #endregion
                        }
                        else
                        {
                            #region 读卡异常,按钮不可用
                            btSender.Enabled = false;

                            btGet.Enabled = false;
                            CommonFunction.ShowMessage("卡内信息错误!", this, true);
                            #endregion
                        }
                    }
                    catch (System.ArgumentOutOfRangeException ax)
                    {
                        CommonFunction.ShowMessage("读卡信息错误!", this, true);
                    }
                    catch (Exception ex)
                    {
                        CommonFunction.ShowMessage(ex.Message, this, true);
                    }
                }

                #endregion
            }
            else
            {
                #region 判断卡类型
                btGet.Enabled    = false;
                btSender.Enabled = false;

                btGet.Checked    = false;
                btSender.Checked = false;
                CommonFunction.ShowMessage("不支持该类型的卡", this, true);
                ic.isReadIcOK = false;
                return;

                #endregion
            }
        }
        public List <object> LerTodosOsSetoresDoCartao()
        {
            byte[]        byteRead;                           // Irá armazenar os byte lidos do cartão
            bool          auth         = false;               // Valida se existe ou não permissão para ler o bloco
            int           quantSetores = 0;                   // Quantidade de setores existentes no cartão
            int           blocoCount   = 0;                   // Quantidades de blocos existentes no cartão
            int           blocoIndex   = 0;                   // Irá armazenar o indice que esta sendo lido do cartão
            List <object> ByteRetorno  = new List <object>(); // Lista com a leitura de todos os blocos e setores

            try
            {
                // Faz a conexão com o cartão
                ValidConexaoCartao();

                // Irá armazenar a quantidade de setores existentes no cartão
                quantSetores = MifareClassic.BlockSize;

                // Percorre todos os setores existentes no cartão
                for (int i = 0; i < quantSetores; i++)
                {
                    // Faz a validação de permissão para a leitura do bloco A
                    auth = ValidPermissaoBlocoA(i);

                    if (!auth)
                    {
                        // Faz a validação de permissão para a leitura do bloco B
                        auth = ValidPermissaoBlocoB(i);
                    }

                    if (auth)
                    {
                        // Busca a quanidade de blocos em um setor
                        blocoCount = mifareClassic.GetBlockCountInSector(i);

                        // Percore todos os blocos do setor
                        for (int j = 0; j < blocoCount; j++)
                        {
                            // É necessário fazer novamente a validação de permissão Bloco a bloco

                            // Faz a validação de permissão para a leitura do bloco A
                            auth = ValidPermissaoBlocoA(j);

                            if (!auth)
                            {
                                // Faz a validação de permissão para a leitura do bloco B
                                auth = ValidPermissaoBlocoB(j);
                            }

                            if (auth)
                            {
                                // seta o indice do setor dentro do bloco
                                blocoIndex = mifareClassic.SectorToBlock(j);

                                // Faz a leitura de um BLOCO no setor
                                byteRead = mifareClassic.ReadBlock(blocoIndex);
                                ByteRetorno.Add(byteRead);
                            }
                        }
                    }
                }
            }
            catch (IOException e)
            {
                throw new IOException(e.Message);
            }
            finally
            {
                // Fecha a conexão com o cartão
                DesconectaCartao();
                this.GravaTempoFinal();
            }

            return(ByteRetorno);
        }
Ejemplo n.º 7
0
        private void ReadIcData(Intent intent)
        {
            m_intent    = intent;
            ic.icserial = ic.FindIC(m_intent);

            Car = new CarInfo();    //初始化一个CarInfo类

            //取出封装在intent中的TAG
            tag = intent.GetParcelableExtra(NfcAdapter.ExtraTag) as Tag;
            if (tag == null)
            {
                return;
            }
            m_tag = tag;

            //清空文本
            extra_bags.Text     = "";
            samp_bags.Text      = "";
            samp_factory.Text   = "";
            samp_goodsname.Text = "";
            samp_carNumber.Text = "";
            cmeasure_Id.Text    = "";
            MifareClassic mfc = MifareClassic.Get(m_tag);

            if (mfc != null)
            {
                #region 获取到tag
                try
                {
                    mfc.Connect();
                    var type = mfc.GetType();
                    if (type.Equals(typeof(Android.Nfc.Tech.MifareClassic)))
                    {
                        #region 循环读取5个扇区数据
                        for (int i = 0; i < ic.sectors.Length; i++)
                        {
                            for (int k = 0; k < 3; k++)
                            {
                                int sec = mfc.BlockToSector(ic.sectors[i] * 4 + k);
                                if (sec < mfc.SectorCount)
                                {
                                    if (mfc.AuthenticateSectorWithKeyB(sec, ic.ToDigitsBytes(ic.mb)))
                                    {
                                        int c = mfc.SectorCount;
                                        c = mfc.BlockCount;

                                        byte[] data = new byte[16];
                                        data = mfc.ReadBlock(ic.sectors[i] * 4 + k);
                                        if (data != null)
                                        {
                                            ic.IcDatas[i, k] = ic.ToHexString(data);
                                            ic.isReadIcOK    = true;
                                        }
                                        else
                                        {
                                            CommonFunction.ShowMessage("读取" + ic.sectors[i].ToString() + "扇区" + Convert.ToString(ic.sectors[i] * 4 + k) + "块失败!", this, true);
                                            ic.isReadIcOK = false;
                                            return;
                                        }
                                    }
                                    else
                                    {
                                        CommonFunction.ShowMessage("密码验证失败!", this, true);
                                        ic.isReadIcOK = false;
                                        return;
                                    }
                                }
                            }
                        }
                        #endregion
                    }
                }
                catch (Exception ex)
                {
                    CommonFunction.ShowMessage(ex.Message, this, true);
                }
                finally
                {
                    mfc.Close();
                }

                if (ic.isReadIcOK)
                {
                    try
                    {
                        //解析扇区数据
                        Car = ic.GetCarInfo(ic.IcDatas);

                        if (Car != null)
                        {
                            // CommonFunction.ShowMessage("", this, false);

                            //将摇号信息写入本地数据表
                            // isEqualFactory();

                            #region 读卡正确,显示在窗体文本内,按钮复活
                            //是否为同一张卡 重复卡不得重复刷
                            if (!isEqualFactory())
                            {
                                samp_carNumber.Text = Car.CarPlate;

                                // bussnise.Text = Car.BusinessType;

                                // measuremode.Text = Car.MeasureMode;

                                cmeasure_Id.Text = Car.MeasureID;

                                //根据车号和计量单号 从计量系统中查询 采购订单号 供应商编号 供应商名称 货物编号 货物名称等信息
                                bsif.selectCmInfo(Car.CarPlate, Car.MeasureID, out cMeasureID, out purchaseOrderID, out car_factoryCode, out car_factoryName, out car_goodsCode, out car_goodsName);
                                samp_factory.Text   = car_factoryName;
                                samp_goodsname.Text = car_goodsName;
                            }
                            #endregion
                        }
                        else
                        {
                            #region 读卡异常,按钮不可用
                            ToggleButton samp = FindViewById <ToggleButton>(Resource.Id.btExtract);
                            samp.Enabled = false;
                            CommonFunction.ShowMessage("卡内信息错误!", this, true);
                            #endregion
                        }
                    }
                    catch (System.ArgumentOutOfRangeException ax)
                    {
                        CommonFunction.ShowMessage("读卡信息错误!", this, true);
                    }
                    catch (Exception ex)
                    {
                        CommonFunction.ShowMessage(ex.Message, this, true);
                    }
                }

                #endregion
            }
            else
            {
                #region 判断卡类型
                btExtra.Enabled = false;

                btExtra.Checked = false;
                CommonFunction.ShowMessage("不支持该类型的卡", this, true);
                ic.isReadIcOK = false;
                return;

                #endregion
            }
        }
Ejemplo n.º 8
0
        private void ReadIcData(Intent intent)
        {
            m_intent    = intent;
            ic.icserial = ic.FindIC(m_intent);

            Car = new CarInfo();    //初始化一个CarInfo类

            //取出封装在intent中的TAG
            tag = intent.GetParcelableExtra(NfcAdapter.ExtraTag) as Tag;
            if (tag == null)
            {
                return;
            }
            m_tag = tag;

            MifareClassic mfc = MifareClassic.Get(m_tag);

            if (mfc != null)
            {
                #region 获取到tag
                try
                {
                    mfc.Connect();
                    var type = mfc.GetType();
                    if (type.Equals(typeof(Android.Nfc.Tech.MifareClassic)))
                    {
                        #region 循环读取5个扇区数据
                        for (int i = 0; i < ic.sectors.Length; i++)
                        {
                            for (int k = 0; k < 3; k++)
                            {
                                int sec = mfc.BlockToSector(ic.sectors[i] * 4 + k);
                                if (sec < mfc.SectorCount)
                                {
                                    if (mfc.AuthenticateSectorWithKeyB(sec, ic.ToDigitsBytes(ic.mb)))
                                    {
                                        int c = mfc.SectorCount;
                                        c = mfc.BlockCount;

                                        byte[] data = new byte[16];
                                        data = mfc.ReadBlock(ic.sectors[i] * 4 + k);
                                        if (data != null)
                                        {
                                            ic.IcDatas[i, k] = ic.ToHexString(data);
                                            ic.isReadIcOK    = true;
                                        }
                                        else
                                        {
                                            CommonFunction.ShowMessage("读取" + ic.sectors[i].ToString() + "扇区" + Convert.ToString(ic.sectors[i] * 4 + k) + "块失败!", this, true);
                                            ic.isReadIcOK = false;
                                            return;
                                        }
                                    }
                                    else
                                    {
                                        CommonFunction.ShowMessage("密码验证失败!", this, true);
                                        ic.isReadIcOK = false;
                                        return;
                                    }
                                }
                            }
                        }
                        #endregion
                    }
                }
                catch (Exception ex)
                {
                    CommonFunction.ShowMessage(ex.Message, this, true);
                }
                finally
                {
                    mfc.Close();
                }
                if (ic.isReadIcOK)
                {
                    ToggleButton samp = FindViewById <ToggleButton>(Resource.Id.btSamp);
                    //Button samp = FindViewById<Button>(Resource.Id.btSamp);
                    samp.Enabled = true;
                    btSamp.SetBackgroundColor(Android.Graphics.Color.ParseColor("#DB3E3E"));
                }
                else
                {
                    #region 读卡异常,按钮不可用
                    Button samp = FindViewById <Button>(Resource.Id.btSamp);
                    samp.Enabled = false;
                    CommonFunction.ShowMessage("卡内信息错误!", this, true);
                    #endregion
                }
                #endregion
            }
            else
            {
                #region 判断卡类型
                btSamp.Enabled = false;

                btSamp.Checked = false;
                CommonFunction.ShowMessage("不支持该类型的卡", this, true);
                ic.isReadIcOK = false;
                return;

                #endregion
            }
        }
Ejemplo n.º 9
0
        private void ReadIcData(Intent intent)
        {
            m_intent    = intent;
            ic.icserial = ic.FindIC(m_intent);

            Car = new CarInfo();    //初始化一个CarInfo类

            //取出封装在intent中的TAG
            var tag = intent.GetParcelableExtra(NfcAdapter.ExtraTag) as Tag;

            if (tag == null)
            {
                return;
            }
            m_tag = tag;

            #region 清空文本
            EditText carinfo = FindViewById <EditText>(Resource.Id.tuCarInfo);
            carinfo.Text = "";

            EditText bussnise = FindViewById <EditText>(Resource.Id.tuBussnise);
            bussnise.Text = "";

            EditText measuretype = FindViewById <EditText>(Resource.Id.tuMeasureType);
            measuretype.Text = "";

            EditText measuremode = FindViewById <EditText>(Resource.Id.tuMeasureMode);
            measuremode.Text = "";

            EditText measureid = FindViewById <EditText>(Resource.Id.tuMeasureID);
            measureid.Text = "";

            EditText goodweight = FindViewById <EditText>(Resource.Id.tuGoodWeight);
            goodweight.Text = "";

            EditText measuredt = FindViewById <EditText>(Resource.Id.tuMeasureDT);
            measuredt.Text = "";

            EditText buckleweight = FindViewById <EditText>(Resource.Id.eBuckleWeight);
            buckleweight.Text = "0";

            #endregion

            MifareClassic mfc = MifareClassic.Get(m_tag);
            if (mfc != null)
            {
                #region 获取到tag
                try
                {
                    mfc.Connect();
                    var type = mfc.GetType();
                    if (type.Equals(typeof(Android.Nfc.Tech.MifareClassic)))
                    {
                        #region 循环读取5个扇区数据
                        for (int i = 0; i < ic.sectors.Length; i++)
                        {
                            for (int k = 0; k < 3; k++)
                            {
                                int sec = mfc.BlockToSector(ic.sectors[i] * 4 + k);
                                if (sec < mfc.SectorCount)
                                {
                                    if (mfc.AuthenticateSectorWithKeyB(sec, ic.ToDigitsBytes(ic.mb)))
                                    {
                                        int c = mfc.SectorCount;
                                        c = mfc.BlockCount;

                                        byte[] data = new byte[16];
                                        data = mfc.ReadBlock(ic.sectors[i] * 4 + k);
                                        if (data != null)
                                        {
                                            ic.IcDatas[i, k] = ic.ToHexString(data);
                                            ic.isReadIcOK    = true;
                                        }
                                        else
                                        {
                                            CommonFunction.ShowMessage("读取" + ic.sectors[i].ToString() + "扇区" + Convert.ToString(ic.sectors[i] * 4 + k) + "块失败!", this, true);
                                            ic.isReadIcOK = false;
                                            return;
                                        }
                                    }
                                    else
                                    {
                                        CommonFunction.ShowMessage("密码验证失败!", this, true);
                                        ic.isReadIcOK = false;
                                        return;
                                    }
                                }
                            }
                        }
                        #endregion
                    }
                }
                catch (Exception ex)
                {
                    CommonFunction.ShowMessage(ex.Message, this, true);
                }
                finally
                {
                    mfc.Close();
                }

                if (ic.isReadIcOK)
                {
                    try
                    {
                        //解析扇区数据
                        Car = ic.GetCarInfo(ic.IcDatas);

                        if (Car != null)
                        {
                            CommonFunction.ShowMessage("", this, false);

                            #region 读卡正确,显示在窗体文本内,按钮复活

                            carinfo.Text = Car.CarPlate;

                            bussnise.Text = Car.BusinessType;

                            measuretype.Text = Car.MeasurementType;

                            measuremode.Text = Car.MeasureMode;

                            measureid.Text = Car.CardID;

                            goodweight.Text = Car.Gross.ToString();

                            measuredt.Text = Car.GrossDateTime;

                            Button unload = FindViewById <Button>(Resource.Id.buUnLoad);
                            unload.Enabled = true;
                            unload.SetBackgroundColor(Android.Graphics.Color.ParseColor("#BD2B32"));
                            unload.SetTextColor(Android.Graphics.Color.ParseColor("#ffffff"));

                            Button halfreturn = FindViewById <Button>(Resource.Id.buHalfReturn);
                            halfreturn.Enabled = true;
                            halfreturn.SetBackgroundColor(Android.Graphics.Color.ParseColor("#BD2B32"));
                            halfreturn.SetTextColor(Android.Graphics.Color.ParseColor("#ffffff"));

                            Button allreturn = FindViewById <Button>(Resource.Id.buAllReturn);
                            allreturn.Enabled = true;
                            allreturn.SetBackgroundColor(Android.Graphics.Color.ParseColor("#BD2B32"));
                            allreturn.SetTextColor(Android.Graphics.Color.ParseColor("#ffffff"));

                            Button unloadandload = FindViewById <Button>(Resource.Id.buUnloadAndLoad);
                            unloadandload.Enabled = true;
                            unloadandload.SetBackgroundColor(Android.Graphics.Color.ParseColor("#BD2B32"));
                            unloadandload.SetTextColor(Android.Graphics.Color.ParseColor("#ffffff"));

                            #endregion
                        }
                        else
                        {
                            #region 读卡异常,按钮不可用
                            Button unload = FindViewById <Button>(Resource.Id.buUnLoad);
                            unload.Enabled = false;

                            Button halfreturn = FindViewById <Button>(Resource.Id.buHalfReturn);
                            halfreturn.Enabled = false;

                            Button allreturn = FindViewById <Button>(Resource.Id.buAllReturn);
                            allreturn.Enabled = false;

                            Button unloadandload = FindViewById <Button>(Resource.Id.buUnloadAndLoad);
                            unloadandload.Enabled = false;

                            CommonFunction.ShowMessage("卡内信息错误!", this, true);
                            #endregion
                        }
                    }
                    catch (System.ArgumentOutOfRangeException ax)
                    {
                        CommonFunction.ShowMessage("读卡信息错误!", this, true);
                    }
                    catch (Exception ex)
                    {
                        CommonFunction.ShowMessage(ex.Message, this, true);
                    }
                }

                #endregion
            }
            else
            {
                #region 判断卡类型
                bunload.Enabled        = false;
                bhalfreturn.Enabled    = false;
                ballreturn.Enabled     = false;
                bunloadandload.Enabled = false;

                bunload.Checked        = false;
                bhalfreturn.Checked    = false;
                ballreturn.Checked     = false;
                bunloadandload.Checked = false;
                CommonFunction.ShowMessage("不支持该类型的卡", this, true);
                ic.isReadIcOK = false;
                return;

                #endregion
            }
        }
Ejemplo n.º 10
0
 public byte[] MifareClassic_ReadBlock(MifareClassic mfc, int Block)
 {
     return(mfc.ReadBlock(Block));
 }