Esempio n. 1
0
        public bool WriteDutyOfficerData(DutyOfficerData data, string readerName = null)
        {
            try
            {
                if (readerName == null)
                {
                    readerName = _readerName;
                }

                // get list blocks will be read/write
                List <MifareCard_Block> lstBlocks = GetAll_Blocks_MifareClassic(EnumSmartCardTypes.MifareClassic4K);
                if (lstBlocks == null || lstBlocks.Count() == 0)
                {
                    throw new Exception("Can not get card blocks");
                }

                // calculate storage size of smartcard
                int totalBytes = lstBlocks.Count(block => block.BlockType == EnumBlockTypes.Data) * 16;

                SmartCardData_Original cardData = new SmartCardData_Original()
                {
                    DutyOfficerData = data
                };

                // convert object to json
                var jsonData = JsonConvert.SerializeObject(cardData);

                // encrypting
                var encryptedString = CommonUtil.EncryptString(jsonData, _passphrase);

                // check length of encryptContent, remove last HistoricalRecord
                while (encryptedString.Length > totalBytes)
                {
                    throw new Exception("Data length of DutyOfficerData is overflow");
                }

                // data to write
                byte[] byteData = Encoding.ASCII.GetBytes(jsonData);

                bool result = WriteData_MifareClassic(byteData, readerName);

                // return value
                return(result);
            }
            catch (Exception ex)
            {
                Debug.WriteLine("WriteData_MifareClassic exception: " + ex.ToString());
                return(false);
            }
        }
Esempio n. 2
0
        public static bool ReadData()
        {
            try
            {
                SmartCardReaderUtil smartCardReaderUtil = SmartCardReaderUtil.Instance;

                // get card UID
                string cardUID = smartCardReaderUtil.GetCardUID();
                if (string.IsNullOrEmpty(cardUID))
                {
                    throw new Exception("Can not get card UID");
                }

                // get card data
                SmartCardData_Original smartCardData_Original = null;
                bool readDataResult = smartCardReaderUtil.ReadAllData_MifareClassic(ref smartCardData_Original);
                //MessageBox.Show(readDataResult.ToString());
                if (!readDataResult)
                {
                    throw new Exception("Can not get card data");
                }

                if (smartCardData_Original == null)
                {
                    throw new Exception("Card data is null");
                }

                _cardUID = cardUID;
                //MessageBox.Show(cardUID);
                _cardData_Original = smartCardData_Original;
                //MessageBox.Show(Newtonsoft.Json.JsonConvert.SerializeObject(_cardData_Original));

                return(true);
            }
            catch (Exception ex)
            {
                Debug.WriteLine("GetData exception: " + ex.ToString());
                return(false);
            }
        }
Esempio n. 3
0
 public static void Remove()
 {
     _cardUID           = null;
     _cardData_Original = null;
 }
Esempio n. 4
0
        public bool AppendHistoricalRecord(SmartCardData_Original cardData, HistoricalRecord record)
        {
            try
            {
                // get list blocks will be read/write
                List <MifareCard_Block> lstBlocks = GetAll_Blocks_MifareClassic(EnumSmartCardTypes.MifareClassic4K);
                if (lstBlocks == null || lstBlocks.Count() == 0)
                {
                    throw new Exception("Can not get card blocks");
                }

                // calculate storage size of smartcard
                int totalBytes = lstBlocks.Count(block => block.BlockType == EnumBlockTypes.Data) * 16;

                // create SmartCardData object
                if (cardData == null)
                {
                    throw new Exception("SuperviseeBiodata in the card can not be null");
                }
                else
                {
                    if (cardData.HistoricalRecords == null || cardData.HistoricalRecords.Count == 0)
                    {
                        List <HistoricalRecord> historicalRecords = new List <HistoricalRecord>();
                        historicalRecords.Add(record);

                        cardData.HistoricalRecords = historicalRecords;
                    }
                    else
                    {
                        cardData.HistoricalRecords.Insert(0, record);
                    }
                }

                // convert object to json
                var jsonData = JsonConvert.SerializeObject(cardData);

                // encrypting
                var encryptedString = CommonUtil.EncryptString(jsonData, _passphrase);

                // check length of encryptContent, remove last HistoricalRecord
                while (encryptedString.Length > totalBytes)
                {
                    // remove last record
                    if (cardData.HistoricalRecords != null || cardData.HistoricalRecords.Count() > 0)
                    {
                        cardData.HistoricalRecords.Remove(cardData.HistoricalRecords.Last());
                    }

                    // convert new data to json
                    jsonData = JsonConvert.SerializeObject(cardData);

                    // encrypting
                    encryptedString = CommonUtil.EncryptString(jsonData, _passphrase);
                }

                // data to write
                byte[] byteData = Encoding.ASCII.GetBytes(jsonData);

                bool result = WriteData_MifareClassic(byteData);

                // return value
                return(result);
            }
            catch (Exception ex)
            {
                Debug.WriteLine("WriteData_MifareClassic exception: " + ex.ToString());
                return(false);
            }
        }
Esempio n. 5
0
        public bool ReadAllData_MifareClassic(ref SmartCardData_Original smartCardData_Original)
        {
            try
            {
                Debug.WriteLine("starting ReadAllData_MifareClassic...");

                string readerName = EnumDeviceNames.SmartCardContactlessReader;

                // get list blocks will be read/write
                List <MifareCard_Block> lstBlocks = GetAll_Blocks_MifareClassic(EnumSmartCardTypes.MifareClassic4K);

                if (lstBlocks == null || lstBlocks.Count() == 0)
                {
                    throw new Exception("Can not get card blocks");
                }

                // key slot
                byte MSB = 0x00;

                // create mifare card
                MifareCard card = CreateMifareCardInstance(MSB);

                if (card == null)
                {
                    throw new Exception("Can not create card instance with keys: " + BitConverter.ToString(_authenticationKeys));
                }

                // loop all blocks read/write to read binary data
                StringBuilder sbData        = new StringBuilder();
                int           currentSector = -1; // authenticate each sector, not block
                foreach (var block in lstBlocks.Where(block => block.BlockType == EnumBlockTypes.Data))
                {
                    if (currentSector != block.Sector_Index)
                    {
                        currentSector = block.Sector_Index;

                        // authentication
                        // typeB
                        bool authSuccessful = card.Authenticate(MSB, block.Block_Index_Hex, KeyType.KeyA, 0x00);
                        if (!authSuccessful)
                        {
                            throw new Exception("AUTHENTICATE failed at block " + block.Block_Index_Dec + " with key " + BitConverter.ToString(_authenticationKeys));
                        }
                    }

                    // get data
                    byte[] result = card.ReadBinary(MSB, block.Block_Index_Hex, 16);

                    // display data writen
                    string dataString = (result != null) ? Encoding.UTF8.GetString(result) : string.Empty;
                    string dateBit    = (result != null) ? BitConverter.ToString(result) : string.Empty;
                    //sbData.AppendLine($"Block {block.Block_Index_Dec}: " + dateBit);
                    sbData.Append(dataString);
                }

                string encryptedData = sbData.ToString().Trim();
                //encryptedData = encryptedData.Replace('-', '+');
                //encryptedData = encryptedData.Replace('_', '/');

                //// decrypting result
                //var decrytedtData = CommonUtil.DecryptString(encryptedData, _passphrase);
                // set card data
                //_cardData = JsonConvert.DeserializeObject<SmartCardData_Original>(encryptedData);
                smartCardData_Original = JsonConvert.DeserializeObject <SmartCardData_Original>(encryptedData);

                // return value
                return(true);
            }
            catch (Exception ex)
            {
                Debug.WriteLine("ReadAllData_MifareClassic exception: " + ex.ToString());
                return(false);
            }
        }
Esempio n. 6
0
        public bool PrintAndWriteSmartCard(PrintAndWriteSmartCardInfo cardInfo, Action <PrintAndWriteCardResult> OnCompleted)
        {
            try
            {
                // validate
                if (cardInfo == null)
                {
                    throw new Exception("cardInfo can not be null");
                }
                PrintAndWriteCardResult returnValue = new PrintAndWriteCardResult()
                {
                    Success = false
                };

                if (IsPrinterConnected(EnumDeviceNames.SmartCardPrinterName))
                {
                    #region use SmartCardPrinterName
                    byte[] img      = null;
                    byte[] bmpFront = null;
                    byte[] bmpBack  = null;

                    Job            job = null;
                    ZMotifGraphics g   = null;

                    string frontImagePath, backImagePath = null;

                    try
                    {
                        job = new Job();
                        g   = new ZMotifGraphics();

                        // Opens a connection with a ZXP Printer
                        //     if it is in an alarm condition, exit function
                        // -------------------------------------------------

                        if (!Connect(ref job))
                        {
                            throw new Exception("Unable to open device [" + _smartCardPrinterName + "]\r\n");
                        }

                        // Determines if the ZXP device supports smart card encoding
                        // ---------------------------------------------------------
                        if (!GetPrinterConfiguration(ref job, out bool isContactless))
                        {
                            throw new Exception("Unable to get printer configuration");
                        }

                        if (!isContactless)
                        {
                            throw new Exception("Printer is not configured for Contactless Encoding");
                        }

                        if (_alarm != 0)
                        {
                            throw new Exception("Printer is in alarm condition\r\n");
                        }

                        frontImagePath = cardInfo.FrontCardImagePath;
                        backImagePath  = cardInfo.BackCardImagePath;

                        // Builds the front side image (color)
                        // -----------------------------------

                        g.InitGraphics(0, 0, ZMotifGraphics.ImageOrientationEnum.Landscape,
                                       ZMotifGraphics.RibbonTypeEnum.Color);

                        img = g.ImageFileToByteArray(frontImagePath);
                        g.DrawImage(ref img, ZMotifGraphics.ImagePositionEnum.Centered, 1024, 648, 0);

                        int dataLen = 0;
                        bmpFront = g.CreateBitmap(out dataLen);
                        g.ClearGraphics();

                        // Builds the back side image (monochrome)
                        // ---------------------------------------

                        g.InitGraphics(0, 0, ZMotifGraphics.ImageOrientationEnum.Landscape,
                                       ZMotifGraphics.RibbonTypeEnum.MonoK);

                        img = g.ImageFileToByteArray(backImagePath);
                        g.DrawImage(ref img, ZMotifGraphics.ImagePositionEnum.Centered, 1024, 648, 0);

                        bmpBack = g.CreateBitmap(out dataLen);
                        g.ClearGraphics();

                        // Start a contactless smart card job
                        // -----------------------

                        //job.JobControl.CardType = GetContactlessCardType(ref job);
                        //job.JobControl.CardType = "PVC,MIFARE,4K";

                        job.JobControl.FeederSource = FeederSourceEnum.CardFeeder;
                        job.JobControl.Destination  = DestinationTypeEnum.Eject;

                        job.JobControl.SmartCardConfiguration(SideEnum.Front, SmartCardTypeEnum.MIFARE, true);

                        job.BuildGraphicsLayers(SideEnum.Front, PrintTypeEnum.Color, 0, 0, 0,
                                                -1, GraphicTypeEnum.BMP, bmpFront);

                        job.BuildGraphicsLayers(SideEnum.Back, PrintTypeEnum.MonoK, 0, 0, 0,
                                                -1, GraphicTypeEnum.BMP, bmpBack);

                        int actionID = 0;
                        job.PrintGraphicsLayers(1, out actionID);

                        job.ClearGraphicsLayers();

                        // Waits for the card to reach the smart card station
                        // --------------------------------------------------
                        string status = string.Empty;
                        AtStation(ref job, actionID, 30, out status);

                        // ***** Smart Card Code goes here *****
                        SmartCardData_Original cardData = new SmartCardData_Original()
                        {
                            SuperviseeBiodata = cardInfo.SuperviseeBiodata,
                            DutyOfficerData   = cardInfo.DutyOfficerData
                        };
                        // write data
                        bool writeDataResult = SmartCardReaderUtil.Instance.WriteData(cardData, EnumDeviceNames.SmartCardPrinterContactlessReader);
                        if (writeDataResult)
                        {
                            // get card UID
                            returnValue.CardUID = SmartCardReaderUtil.Instance.GetCardUID(EnumDeviceNames.SmartCardPrinterContactlessReader);
                        }

                        // At the completion of smart card process
                        //     if the smart card encoding was successful JobResume
                        //     if the smart card encoding was Unsuccessful JobAbort
                        // --------------------------------------------------------

                        if (writeDataResult)
                        {
                            JobResume(ref job);
                        }
                        else
                        {
                            JobAbort(ref job, true);
                        }

                        JobWait(ref job, actionID, 180, out status);

                        // need to verify printing status
                    }
                    catch (Exception e)
                    {
                        Debug.WriteLine(e.Message);
                    }
                    finally
                    {
                        g.CloseGraphics();
                        g = null;

                        img      = null;
                        bmpFront = null;
                        bmpBack  = null;

                        Disconnect(ref job);
                    }
                    #endregion
                }
                else if (SmartCardReaderUtil.Instance.GetDeviceStatus().Contains(EnumDeviceStatus.Connected))
                {
                    #region use card reader
                    SmartCardData_Original cardData = new SmartCardData_Original()
                    {
                        SuperviseeBiodata = cardInfo.SuperviseeBiodata,
                        DutyOfficerData   = cardInfo.DutyOfficerData
                    };
                    // write data
                    bool writeDataResult = SmartCardReaderUtil.Instance.WriteData(cardData);
                    if (writeDataResult)
                    {
                        // get card UID
                        returnValue.CardUID = SmartCardReaderUtil.Instance.GetCardUID(EnumDeviceNames.SmartCardContactlessReader);
                    }
                    #endregion
                }
                else
                {
                    returnValue.Description = "Smart card printer is not connected!";
                }


                if (!string.IsNullOrEmpty(returnValue.CardUID))
                {
                    returnValue.Success = true;
                }
                else if (string.IsNullOrEmpty(returnValue.CardUID) && string.IsNullOrEmpty(returnValue.Description))
                {
                    returnValue.Description = "Smart card type unsupported!";
                }

                OnCompleted(returnValue);
                return(returnValue.Success);
            }
            catch (Exception ex)
            {
                Debug.WriteLine("PrintAndWriteSmartcardData exception: " + ex.ToString());
                OnCompleted(new PrintAndWriteCardResult()
                {
                    Success = false, Description = "Oops!.. Something went wrong ..."
                });
                return(false);
            }
        }