diff --git a/.gitignore b/.gitignore index 4a9eafe..b6ce1cc 100644 --- a/.gitignore +++ b/.gitignore @@ -26,4 +26,5 @@ /setup example.wxs *.pdf *.xml -*.zip \ No newline at end of file +*.zip +*.htm diff --git a/RFiDGear/Arguments.txt b/RFiDGear/Arguments.txt new file mode 100644 index 0000000..68ac161 --- /dev/null +++ b/RFiDGear/Arguments.txt @@ -0,0 +1 @@ +REPORTTARGETPATH="D:\CardCheck_data\KP-000005-5_final.pdf" REPORTTEMPLATEFILE="D:\CardCheck_data\KP-000005-5_.pdf" CUSTOMPROJECTFILE="D:\CardCheck_data\KPruefung_Vorlagen\00_RFID_Gear_Vorlage\CardCheckAssistant_FreeMemDesfireOnly.rfPrj" $JOBNUMBER="KP-000005" $CHIPNUMBER="5" AUTORUN=1 \ No newline at end of file diff --git a/RFiDGear/DataAccessLayer/Local/Constants.cs b/RFiDGear/DataAccessLayer/Local/Constants.cs index 32a06c3..ddc4305 100644 --- a/RFiDGear/DataAccessLayer/Local/Constants.cs +++ b/RFiDGear/DataAccessLayer/Local/Constants.cs @@ -20,7 +20,7 @@ namespace RFiDGear.DataAccessLayer public static class Constants { - public static readonly int MAX_WAIT_INSERTION = 200; //timeout for chip response in ms + public static readonly uint MAX_WAIT_INSERTION = 200; //timeout for chip response in ms public static readonly string TITLE_SUFFIX = ""; //turns out special app versions //public const string TITLE_SUFFIX = "DEVELOPER PREVIEW"; //turns out special app versions } diff --git a/RFiDGear/DataAccessLayer/Remote/FromFile/DatabaseReaderWriter.cs b/RFiDGear/DataAccessLayer/Remote/FromFile/DatabaseReaderWriter.cs index a310229..699eeb3 100644 --- a/RFiDGear/DataAccessLayer/Remote/FromFile/DatabaseReaderWriter.cs +++ b/RFiDGear/DataAccessLayer/Remote/FromFile/DatabaseReaderWriter.cs @@ -42,8 +42,6 @@ public DatabaseReaderWriter() { try { - //AsyncRelayCommandLoadDB = new AsyncRelayCommand(LoadXML,AsyncRelayCommandOptions.AllowConcurrentExecutions); - // Combine the base folder with the specific folder.... appDataPath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), "RFiDGear"); @@ -120,7 +118,6 @@ public bool ReadDatabase(string _fileName = "") try { - //var serializer = new XmlSerializer(typeof(ChipTaskHandlerModel)); AsyncRelayCommandLoadDB.ExecuteAsync(reader); } catch (Exception e) @@ -167,6 +164,7 @@ public bool ReadDatabase(string _fileName = "") { XmlSerializer serializer = new XmlSerializer(typeof(ChipTaskHandlerModel)); SetupModel = (serializer.Deserialize(reader) as ChipTaskHandlerModel); + reader.Close(); } catch (Exception e) { @@ -251,7 +249,6 @@ public void WriteDatabase(ChipTaskHandlerModel objModel, string _path = "") catch (XmlException e) { LogWriter.CreateLogEntry(e, FacilityName); - Environment.Exit(0); } } diff --git a/RFiDGear/DataAccessLayer/Remote/FromIO/LibLogicalAccessProvider.cs b/RFiDGear/DataAccessLayer/Remote/FromIO/LibLogicalAccessProvider.cs index 46d024c..48afcee 100644 --- a/RFiDGear/DataAccessLayer/Remote/FromIO/LibLogicalAccessProvider.cs +++ b/RFiDGear/DataAccessLayer/Remote/FromIO/LibLogicalAccessProvider.cs @@ -1,2386 +1,2469 @@ using LibLogicalAccess; +using LibLogicalAccess.Card; +using LibLogicalAccess.Reader; +using LibLogicalAccess.Crypto; using ByteArrayHelper.Extensions; -using RFiDGear.Model; - -using Log4CSharp; - -using System; -using System.Threading; - -namespace RFiDGear.DataAccessLayer.Remote.FromIO -{ - /// - /// Description of LibLogicalAccessProvider. - /// - /// Initialize Reader - /// - /// - public class LibLogicalAccessProvider : ReaderDevice, IDisposable - { - // global (cross-class) Instances go here -> - private static readonly string FacilityName = "RFiDGear"; - private readonly IReaderProvider readerProvider; - private readonly IReaderUnit readerUnit; - private chip card; - private bool _disposed; - - private FileSetting desfireFileSetting { get; set; } - - #region contructor - public LibLogicalAccessProvider() - { - } - - public LibLogicalAccessProvider(ReaderTypes readerType) - { - try - { - readerProvider = new LibraryManagerClass().GetReaderProvider(Enum.GetName(typeof(ReaderTypes), readerType)); - readerUnit = readerProvider.CreateReaderUnit(); - - GenericChip = new GenericChipModel("", CARD_TYPE.Unspecified); - } - catch (Exception e) - { - LogWriter.CreateLogEntry(e, FacilityName); - } - } - - #endregion contructor - - #region common - - public override ERROR Connect() - { - return initPCSC(); - } - - private ERROR initPCSC() - { - try - { - if (readerUnit.ConnectToReader()) - { - if (readerUnit.WaitInsertion(Constants.MAX_WAIT_INSERTION)) - { - if (readerUnit.Connect()) - { - ReaderUnitName = readerUnit.ConnectedName; - - card = readerUnit.GetSingleChip(); - - return ERROR.NoError; - } - } - } - - return ERROR.IOError; - } - catch (Exception e) - { - LogWriter.CreateLogEntry(e, FacilityName); - - return ERROR.IOError; - } - } - - public override ERROR ReadChipPublic() - { - if (initPCSC() == ERROR.NoError && !string.IsNullOrWhiteSpace(card.ChipIdentifier)) - { - try - { - GenericChip = new GenericChipModel(card.ChipIdentifier, (CARD_TYPE)Enum.Parse(typeof(CARD_TYPE), card.Type)); - - if (Enum.GetName(typeof(CARD_TYPE), GenericChip.CardType).Contains("DESFire")) - { - var cmd = card.Commands as DESFireCommands; - - var version = cmd.GetVersion(); - - switch (version.hardwareMjVersion & 0x0F) // Desfire(Sub)Type by lower Nibble of Major Version - { - case 0: //DESFIRE EV0 - GenericChip.CardType = CARD_TYPE.DESFire; - - switch (version.hardwareStorageSize) - { - case 0x10: - GenericChip.CardType = CARD_TYPE.DESFire_256; // DESFIRE 256B - break; - case 0x16: - GenericChip.CardType = CARD_TYPE.DESFire_2K; // DESFIRE 2K - break; - case 0x18: - GenericChip.CardType = CARD_TYPE.DESFire_4K; // 4K - break; - default: - break; - } // Size ? - break; - - case 1: // DESFIRE EV1 - GenericChip.CardType = CARD_TYPE.DESFireEV1; - - switch (version.hardwareStorageSize) - { - case 0x10: - GenericChip.CardType = CARD_TYPE.DESFireEV1_256; //DESFIRE 256B - break; - case 0x16: - GenericChip.CardType = CARD_TYPE.DESFireEV1_2K; // DESFIRE 2K - break; - case 0x18: - GenericChip.CardType = CARD_TYPE.DESFireEV1_4K; // 4K - break; - case 0x1A: - GenericChip.CardType = CARD_TYPE.DESFireEV1_8K; // 8K - break; - default: - break; - } // Size ? - break; - - case 2: // EV2 - GenericChip.CardType = CARD_TYPE.DESFireEV2; - - switch (version.hardwareStorageSize) - { - case 0x16: - GenericChip.CardType = CARD_TYPE.DESFireEV2_2K; // DESFIRE 2K - break; - case 0x18: - GenericChip.CardType = CARD_TYPE.DESFireEV2_4K; // 4K - break; - case 0x1A: - GenericChip.CardType = CARD_TYPE.DESFireEV2_8K; // 8K - break; - case 0x1C: - GenericChip.CardType = CARD_TYPE.DESFireEV2_16K; // 16K - break; - case 0x1E: - GenericChip.CardType = CARD_TYPE.DESFireEV2_32K; // 32K - break; - default: - break; - } // SIZE ? - break; - - case 3: // EV3 - GenericChip.CardType = CARD_TYPE.DESFireEV3; - - switch (version.hardwareStorageSize) - { - case 0x16: - GenericChip.CardType = CARD_TYPE.DESFireEV3_2K; // DESFIRE 2K - break; - case 0x18: - GenericChip.CardType = CARD_TYPE.DESFireEV3_4K; // 4K - break; - case 0x1A: - GenericChip.CardType = CARD_TYPE.DESFireEV3_8K; // 8K - break; - case 0x1C: - GenericChip.CardType = CARD_TYPE.DESFireEV3_16K; // 16K - break; - case 0x1E: - GenericChip.CardType = CARD_TYPE.DESFireEV3_32K; // 32K - break; - default: - break; - } // SIZE ? - break; - - default: - GenericChip.CardType = CARD_TYPE.Unspecified; - - break; - } - - - } - - DesfireChip = DesfireChip ?? new MifareDesfireChipModel(GenericChip); - - return ERROR.NoError; - } - catch (Exception e) - { - LogWriter.CreateLogEntry(e, FacilityName); - - return ERROR.IOError; - } - } - else - { - return ERROR.NotReadyError; - } - } - - #endregion common - - #region mifare classic - public override ERROR ReadMifareClassicSingleSector(int sectorNumber, string aKey, string bKey) - { - Sector = new MifareClassicSectorModel(); - - var keyA = new MifareKey() { Value = CustomConverter.KeyFormatQuickCheck(aKey) ? aKey : CustomConverter.FormatMifareClassicKeyWithSpacesEachByte(aKey) }; - var keyB = new MifareKey() { Value = CustomConverter.KeyFormatQuickCheck(bKey) ? bKey : CustomConverter.FormatMifareClassicKeyWithSpacesEachByte(bKey) }; - - if (initPCSC() == ERROR.NoError && !string.IsNullOrWhiteSpace(card.ChipIdentifier)) - { - try - { - GenericChip = new GenericChipModel(card.ChipIdentifier, (CARD_TYPE)Enum.Parse(typeof(CARD_TYPE), card.Type)); - - try - { //try to Auth with Keytype A - - var cmd = card.Commands as IMifareCommands; - - for (var k = 0; k < (sectorNumber > 31 ? 16 : 4); k++) // if sector > 31 is 16 blocks each sector i.e. mifare 4k else its 1k or 2k with 4 blocks each sector - { - cmd.LoadKeyNo((byte)0, keyA, MifareKeyType.KT_KEY_A); - - DataBlock = new MifareClassicDataBlockModel( - (byte)CustomConverter.GetChipBasedDataBlockNumber(sectorNumber, k), - k); - - try - { - cmd.AuthenticateKeyNo((byte)CustomConverter.GetChipBasedDataBlockNumber(sectorNumber, k), - (byte)0, - MifareKeyType.KT_KEY_A); - - Sector.IsAuthenticated = true; - - try - { - var data = cmd.ReadBinary( - (byte)CustomConverter.GetChipBasedDataBlockNumber(sectorNumber, k), - 48); - - DataBlock.Data = (byte[])data; - - DataBlock.IsAuthenticated = true; - - Sector.DataBlock.Add(DataBlock); - } - catch - { - DataBlock.IsAuthenticated = false; - Sector.DataBlock.Add(DataBlock); - } - } - catch - { // Try Auth with keytype b - - try - { - cmd.LoadKeyNo((byte)1, keyB, MifareKeyType.KT_KEY_B); - - cmd.AuthenticateKeyNo( - (byte)CustomConverter.GetChipBasedDataBlockNumber(sectorNumber, k), - (byte)1, - MifareKeyType.KT_KEY_B); - - Sector.IsAuthenticated = true; - - try - { - var data = cmd.ReadBinary( - (byte)CustomConverter.GetChipBasedDataBlockNumber(sectorNumber, k), - 48); - - DataBlock.Data = (byte[])data; - - DataBlock.IsAuthenticated = true; - - Sector.DataBlock.Add(DataBlock); - } - catch - { - - DataBlock.IsAuthenticated = false; - - Sector.DataBlock.Add(DataBlock); - - return ERROR.AuthenticationError; - } - } - catch - { - Sector.IsAuthenticated = false; - DataBlock.IsAuthenticated = false; - - Sector.DataBlock.Add(DataBlock); - - return ERROR.AuthenticationError; - } - } - } - - return ERROR.NoError; - } - catch - { - return ERROR.NoError; - } - } - catch (Exception e) - { - LogWriter.CreateLogEntry(e, FacilityName); - } - } - - return ERROR.IOError; - } - - public override ERROR WriteMifareClassicSingleSector(int sectorNumber, string _aKey, string _bKey, byte[] buffer) - { - var keyA = new MifareKey() { Value = CustomConverter.FormatMifareClassicKeyWithSpacesEachByte(_aKey) }; - var keyB = new MifareKey() { Value = CustomConverter.FormatMifareClassicKeyWithSpacesEachByte(_bKey) }; - - var blockCount = 0; - - if (initPCSC() == ERROR.NoError && !string.IsNullOrWhiteSpace(card.ChipIdentifier)) - { - try - { - GenericChip = new GenericChipModel(card.ChipIdentifier, (CARD_TYPE)Enum.Parse(typeof(CARD_TYPE), card.Type)); - - try - { //try to Auth with Keytype A - var cmd = card.Commands as IMifareCommands; - - cmd.LoadKeyNo((byte)0, keyA, MifareKeyType.KT_KEY_A); - cmd.LoadKeyNo((byte)1, keyB, MifareKeyType.KT_KEY_B); - - for (var k = 0; k < blockCount; k++) - { - try - { - cmd.AuthenticateKeyNo( - (byte)CustomConverter.GetChipBasedDataBlockNumber(sectorNumber, k), - (byte)0, - MifareKeyType.KT_KEY_A); - - try - { - cmd.WriteBinary( - (byte)CustomConverter.GetChipBasedDataBlockNumber(sectorNumber, k), - buffer); - } - catch - { - return ERROR.AuthenticationError; - } - } - catch - { // Try Auth with keytype b - - try - { - cmd.AuthenticateKeyNo((byte)CustomConverter.GetChipBasedDataBlockNumber(sectorNumber, k), - (byte)1, - MifareKeyType.KT_KEY_B); - - try - { - cmd.WriteBinary( - (byte)CustomConverter.GetChipBasedDataBlockNumber(sectorNumber, k), - buffer); - } - catch - { - return ERROR.AuthenticationError; - } - } - catch - { - return ERROR.AuthenticationError; - } - } - } - - return ERROR.NoError; - } - catch - { - return ERROR.IOError; - } - } - catch (Exception e) - { - LogWriter.CreateLogEntry(e, FacilityName); - } - } - - return ERROR.IOError; - } - - public override ERROR WriteMifareClassicSingleBlock(int _blockNumber, string _aKey, string _bKey, byte[] buffer) - { - var keyA = new MifareKey() { Value = CustomConverter.FormatMifareClassicKeyWithSpacesEachByte(_aKey) }; - var keyB = new MifareKey() { Value = CustomConverter.FormatMifareClassicKeyWithSpacesEachByte(_bKey) }; - - if (initPCSC() == ERROR.NoError && !string.IsNullOrWhiteSpace(card.ChipIdentifier)) - { - try - { - GenericChip = new GenericChipModel(card.ChipIdentifier, (CARD_TYPE)Enum.Parse(typeof(CARD_TYPE), card.Type)); - - try - { - var cmd = card.Commands as IMifareCommands; - - cmd.LoadKeyNo((byte)0, keyA, MifareKeyType.KT_KEY_A); // FIXME: "sectorNumber" to 0 - - try - { //try to Auth with Keytype A - cmd.AuthenticateKeyNo((byte)(_blockNumber), (byte)0, MifareKeyType.KT_KEY_A); // FIXME: same as '393 - - cmd.WriteBinary((byte)(_blockNumber), buffer); - - } - catch - { // Try Auth with keytype b - - cmd.LoadKeyNo((byte)0, keyB, MifareKeyType.KT_KEY_B); - - try - { - cmd.AuthenticateKeyNo((byte)(_blockNumber), (byte)0, MifareKeyType.KT_KEY_B); // FIXME: same as '393 - - cmd.WriteBinary((byte)(_blockNumber), buffer); - - } - catch - { - return ERROR.AuthenticationError; - } - } - - return ERROR.NoError; - } - catch - { - return ERROR.AuthenticationError; - } - } - catch (Exception e) - { - LogWriter.CreateLogEntry(e, FacilityName); - } - } - - return ERROR.IOError; - } - - public override ERROR WriteMifareClassicWithMAD(int _madApplicationID, int _madStartSector, - string _aKeyToUse, string _bKeyToUse, string _aKeyToWrite, string _bKeyToWrite, - string _madAKeyToUse, string _madBKeyToUse, string _madAKeyToWrite, string _madBKeyToWrite, - byte[] buffer, byte _madGPB, SectorAccessBits _sab, bool _useMADToAuth, bool _keyToWriteUseMAD) - { - Sector = new MifareClassicSectorModel(); - - var mAKeyToUse = new MifareKey() { Value = CustomConverter.KeyFormatQuickCheck(_aKeyToUse) ? _aKeyToUse : CustomConverter.FormatMifareClassicKeyWithSpacesEachByte(_aKeyToUse) }; - var mBKeyToUse = new MifareKey() { Value = CustomConverter.KeyFormatQuickCheck(_bKeyToUse) ? _bKeyToUse : CustomConverter.FormatMifareClassicKeyWithSpacesEachByte(_bKeyToUse) }; - - var mAKeyToWrite = new MifareKey() { Value = CustomConverter.KeyFormatQuickCheck(_aKeyToWrite) ? _aKeyToWrite : CustomConverter.FormatMifareClassicKeyWithSpacesEachByte(_aKeyToWrite) }; - var mBKeyToWrite = new MifareKey() { Value = CustomConverter.KeyFormatQuickCheck(_bKeyToWrite) ? _bKeyToWrite : CustomConverter.FormatMifareClassicKeyWithSpacesEachByte(_bKeyToWrite) }; - - var madAKeyToUse = new MifareKey() { Value = CustomConverter.KeyFormatQuickCheck(_madAKeyToUse) ? _madAKeyToUse : CustomConverter.FormatMifareClassicKeyWithSpacesEachByte(_madAKeyToUse) }; - var madBKeyToUse = new MifareKey() { Value = CustomConverter.KeyFormatQuickCheck(_madBKeyToUse) ? _madBKeyToUse : CustomConverter.FormatMifareClassicKeyWithSpacesEachByte(_madBKeyToUse) }; - - var madAKeyToWrite = new MifareKey() { Value = CustomConverter.KeyFormatQuickCheck(_madAKeyToWrite) ? _madAKeyToWrite : CustomConverter.FormatMifareClassicKeyWithSpacesEachByte(_madAKeyToWrite) }; - var madBKeyToWrite = new MifareKey() { Value = CustomConverter.KeyFormatQuickCheck(_madBKeyToWrite) ? _madBKeyToWrite : CustomConverter.FormatMifareClassicKeyWithSpacesEachByte(_madBKeyToWrite) }; - - if (initPCSC() == ERROR.NoError && !string.IsNullOrWhiteSpace(card.ChipIdentifier)) - { - try - { - GenericChip = new GenericChipModel(card.ChipIdentifier, (CARD_TYPE)Enum.Parse(typeof(CARD_TYPE), card.Type)); - - MifareLocation mlocation = new MifareLocationClass - { - MADApplicationID = (ushort)_madApplicationID, - UseMAD = _keyToWriteUseMAD, - Sector = _madStartSector - }; - - MifareAccessInfo aiToWrite = new MifareAccessInfoClass - { - UseMAD = _keyToWriteUseMAD, - - }; - aiToWrite.MADKeyA.Value = _aKeyToUse == _madAKeyToWrite ? madAKeyToUse.Value : madAKeyToWrite.Value; - aiToWrite.MADKeyB.Value = _bKeyToUse == _madBKeyToWrite ? madBKeyToUse.Value : madBKeyToWrite.Value; - aiToWrite.KeyA.Value = _aKeyToUse == _aKeyToWrite ? mAKeyToUse.Value : mAKeyToWrite.Value; - aiToWrite.KeyB.Value = _bKeyToUse == _bKeyToWrite ? mBKeyToUse.Value : mBKeyToWrite.Value; - aiToWrite.MADGPB = _madGPB; - - var aiToUse = new MifareAccessInfoClass - { - UseMAD = _useMADToAuth, - KeyA = mAKeyToUse, - KeyB = mBKeyToUse - }; - - if (_useMADToAuth) - { - aiToUse.MADKeyA = madAKeyToUse; - aiToUse.MADKeyB = madBKeyToUse; - aiToUse.MADGPB = _madGPB; - } - - try - { - var cardService = card.GetService(CardServiceType.CST_STORAGE) as StorageCardService; - - cardService.WriteData(mlocation, aiToUse, aiToWrite, buffer, buffer.Length, CardBehavior.CB_AUTOSWITCHAREA); - - return ERROR.NoError; - } - catch (Exception e) - { - LogWriter.CreateLogEntry(e, FacilityName); - return ERROR.AuthenticationError; - } - - } - catch (Exception e) - { - LogWriter.CreateLogEntry(e, FacilityName); - } - } - - return ERROR.IOError; - } - - public override ERROR ReadMifareClassicWithMAD(int madApplicationID, - string _aKeyToUse, string _bKeyToUse, string _madAKeyToUse, string _madBKeyToUse, - int _length, byte _madGPB, bool _useMADToAuth, bool _aiToUseIsMAD) - { - Sector = new MifareClassicSectorModel(); - - var mAKeyToUse = new MifareKey() { Value = CustomConverter.KeyFormatQuickCheck(_aKeyToUse) ? _aKeyToUse : CustomConverter.FormatMifareClassicKeyWithSpacesEachByte(_aKeyToUse) }; - var mBKeyToUse = new MifareKey() { Value = CustomConverter.KeyFormatQuickCheck(_bKeyToUse) ? _bKeyToUse : CustomConverter.FormatMifareClassicKeyWithSpacesEachByte(_bKeyToUse) }; - - var madAKeyToUse = new MifareKey() { Value = CustomConverter.KeyFormatQuickCheck(_madAKeyToUse) ? _madAKeyToUse : CustomConverter.FormatMifareClassicKeyWithSpacesEachByte(_madAKeyToUse) }; - var madBKeyToUse = new MifareKey() { Value = CustomConverter.KeyFormatQuickCheck(_madBKeyToUse) ? _madBKeyToUse : CustomConverter.FormatMifareClassicKeyWithSpacesEachByte(_madBKeyToUse) }; - - if (initPCSC() == ERROR.NoError && !string.IsNullOrWhiteSpace(card.ChipIdentifier)) - { - try - { - GenericChip = new GenericChipModel(card.ChipIdentifier, (CARD_TYPE)Enum.Parse(typeof(CARD_TYPE), card.Type)); - - var mlocation = card.CreateLocation() as MifareLocation; - mlocation.MADApplicationID = (ushort)madApplicationID; - mlocation.UseMAD = _useMADToAuth; - - var aiToUse = new MifareAccessInfoClass - { - UseMAD = _aiToUseIsMAD, - KeyA = mAKeyToUse, - KeyB = mBKeyToUse - }; - - if (_useMADToAuth) - { - aiToUse.MADKeyA = madAKeyToUse; - aiToUse.MADKeyB = madBKeyToUse; - aiToUse.MADGPB = _madGPB; - } - - try - { - var cardService = card.GetService(CardServiceType.CST_STORAGE) as StorageCardService; - - MifareClassicData = (byte[])cardService.ReadData(mlocation, aiToUse, _length, CardBehavior.CB_AUTOSWITCHAREA); - - return ERROR.NoError; - - } - catch (Exception e) - { - LogWriter.CreateLogEntry(e, FacilityName); - return ERROR.AuthenticationError; - } - } - catch (Exception e) - { - LogWriter.CreateLogEntry(e, FacilityName); - } - } - - return ERROR.IOError; - } - - #endregion mifare classic - - #region mifare ultralight - - public override ERROR ReadMifareUltralightSinglePage(int _pageNo) - { - try - { - if (readerUnit.ConnectToReader()) - { - if (readerUnit.WaitInsertion(Constants.MAX_WAIT_INSERTION)) - { - if (readerUnit.Connect()) - { - ReaderUnitName = readerUnit.ConnectedName; - - var chip = readerUnit.GetSingleChip() as IMifareUltralightChip; - - if (chip.Type == "MifareUltralight") - { - var cmd = chip.Commands as MifareUltralightCommands; - MifareUltralightPageData = cmd.ReadPages(_pageNo, _pageNo) as byte[]; - } - - return ERROR.NoError; - } - } - } - return ERROR.NoError; - } - catch (Exception e) - { - LogWriter.CreateLogEntry(string.Format("{0}: {1}; {2}", DateTime.Now, e.Message, e.InnerException != null ? e.InnerException.Message : ""), FacilityName); - return ERROR.IOError; - } - } - - #endregion mifare ultralight - - #region mifare desfire - - public override ERROR GetMiFareDESFireChipAppIDs(string _appMasterKey, DESFireKeyType _keyTypeAppMasterKey) - { - try - { - // Keys to use for authentication - IDESFireAccessInfo aiToUse = new DESFireAccessInfo(); - aiToUse.MasterCardKey.Value = _appMasterKey; - aiToUse.MasterCardKey.KeyType = (LibLogicalAccess.DESFireKeyType)_keyTypeAppMasterKey; - - - if (readerUnit.ConnectToReader()) - { - if (readerUnit.WaitInsertion(Constants.MAX_WAIT_INSERTION)) - { - if (readerUnit.Connect()) - { - ReaderUnitName = readerUnit.ConnectedName; - - card = readerUnit.GetSingleChip(); - - //Get AppIDs without Authentication (Free Directory Listing) - try - { - - if (card.Type == "DESFire") - { - var cmd = card.Commands as IDESFireCommands; - - try - { - cmd.SelectApplication((uint)0); - - var appIDsObject = cmd.GetApplicationIDs(); - - if(DesfireChip == null) - { - DesfireChip = new MifareDesfireChipModel(); - } - else - { - DesfireChip.AppList = new System.Collections.Generic.List(); - - foreach (var appid in appIDsObject as UInt32[]) - { - DesfireChip.AppList.Add(new MifareDesfireAppModel(appid)); - } - } - - - return ERROR.NoError; - } - catch - { - //Get AppIDs with Authentication (Directory Listing with PICC MK) - try - { - cmd.SelectApplication((uint)0); - cmd.Authenticate((byte)0, aiToUse.MasterCardKey); - - var appIDsObject = cmd.GetApplicationIDs(); - - if (DesfireChip == null) - { - DesfireChip = new MifareDesfireChipModel(); - } - else - { - DesfireChip.AppList = new System.Collections.Generic.List(); - - foreach (var appid in appIDsObject as UInt32[]) - { - DesfireChip.AppList.Add(new MifareDesfireAppModel(appid)); - } - } - - return ERROR.NoError; - } - catch (Exception e) - { - if (e.Message != "" && e.Message.Contains("same number already exists")) - { - return ERROR.ItemAlreadyExistError; - } - else if (e.Message != "" && e.Message.Contains("status does not allow the requested command")) - { - return ERROR.AuthenticationError; - } - else - { - return ERROR.IOError; - } - } - } - } - - if (card.Type == "DESFireEV1" || - card.Type == "DESFireEV2") - { - - var cmd = card.Commands as IDESFireEV1Commands; - - try - { - DesfireChip.FreeMemory = cmd.GetFreeMemory(); - - var appIDsObject = cmd.GetApplicationIDs(); - - if (DesfireChip == null) - { - DesfireChip = new MifareDesfireChipModel(); - } - else - { - DesfireChip.AppList = new System.Collections.Generic.List(); - - foreach (var appid in appIDsObject as UInt32[]) - { - DesfireChip.AppList.Add(new MifareDesfireAppModel(appid)); - } - } - - return ERROR.NoError; - } - catch - { - //Get AppIDs with Authentication (Directory Listing with PICC MK) - try - { - DesfireChip.FreeMemory = cmd.GetFreeMemory(); - - cmd.SelectApplication((uint)0); - cmd.Authenticate((byte)0, aiToUse.MasterCardKey); - - var appIDsObject = cmd.GetApplicationIDs(); - - if (DesfireChip == null) - { - DesfireChip = new MifareDesfireChipModel(); - } - else - { - DesfireChip.AppList = new System.Collections.Generic.List(); - - foreach (var appid in appIDsObject as UInt32[]) - { - DesfireChip.AppList.Add(new MifareDesfireAppModel(appid)); - } - } - - return ERROR.NoError; - } - catch (Exception e) - { - if (e.Message != "" && e.Message.Contains("same number already exists")) - { - return ERROR.ItemAlreadyExistError; - } - else if (e.Message != "" && e.Message.Contains("status does not allow the requested command")) - { - return ERROR.AuthenticationError; - } - else - { - return ERROR.IOError; - } - } - } - } - else - { - return ERROR.NotReadyError; - } - } - - catch - { - try - { - if (card.Type == "DESFire") - { - var cmd = card.Commands as IDESFireCommands; - - cmd.SelectApplication((uint)0); - cmd.Authenticate((byte)0, aiToUse.MasterCardKey); - - var appIDsObject = cmd.GetApplicationIDs(); - - if (DesfireChip == null) - { - DesfireChip = new MifareDesfireChipModel(); - } - else - { - DesfireChip.AppList = new System.Collections.Generic.List(); - - foreach (var appid in appIDsObject as UInt32[]) - { - DesfireChip.AppList.Add(new MifareDesfireAppModel(appid)); - } - } - - return ERROR.NoError; - } - - if (card.Type == "DESFireEV1" || - card.Type == "DESFireEV2") - { - var cmd = card.Commands as IDESFireEV1Commands; - - } - else - { - return ERROR.NotReadyError; - } - } - - catch - { - - } - } - } - } - } - return ERROR.NotReadyError; - } - - catch (Exception e) - { - if (e.Message != "" && e.Message.Contains("same number already exists")) - { - return ERROR.ItemAlreadyExistError; - } - else if (e.Message != "" && e.Message.Contains("status does not allow the requested command")) - { - return ERROR.AuthenticationError; - } - else - { - return ERROR.IOError; - } - } - } - - public override ERROR CreateMifareDesfireFile(string _appMasterKey, DESFireKeyType _keyTypeAppMasterKey, FileType_MifareDesfireFileType _fileType, DESFireAccessRights _accessRights, EncryptionMode _encMode, - int _appID, int _fileNo, int _fileSize, - int _minValue, int _maxValue, int _initValue, bool _isValueLimited, - int _maxNbOfRecords) - { - try - { - var accessRights = _accessRights; - - // Keys to use for authentication - IDESFireAccessInfo aiToUse = new DESFireAccessInfo(); - CustomConverter.FormatMifareDesfireKeyStringWithSpacesEachByte(_appMasterKey); - aiToUse.MasterCardKey.Value = CustomConverter.DesfireKeyToCheck; - aiToUse.MasterCardKey.KeyType = ((LibLogicalAccess.DESFireKeyType)_keyTypeAppMasterKey); - - if (readerUnit.ConnectToReader()) - { - if (readerUnit.WaitInsertion(Constants.MAX_WAIT_INSERTION)) - { - if (readerUnit.Connect()) - { - ReaderUnitName = readerUnit.ConnectedName; - - card = readerUnit.GetSingleChip(); - - if (card.Type == "DESFire" || - card.Type == "DESFireEV1" || - card.Type == "DESFireEV2") - { - try - { - var cmd = card.Commands as IDESFireEV1Commands; - - try - { - cmd.SelectApplication((uint)_appID); - cmd.Authenticate((byte)0, aiToUse.MasterCardKey); - } - catch - { - switch (_fileType) - { - case FileType_MifareDesfireFileType.StdDataFile: - cmd.CreateStdDataFile((byte)_fileNo, (LibLogicalAccess.EncryptionMode)_encMode, - new LibLogicalAccess.DESFireAccessRights() - { - changeAccess = (LibLogicalAccess.TaskAccessRights)accessRights.changeAccess, - readAccess = (LibLogicalAccess.TaskAccessRights)accessRights.readAccess, - writeAccess = (LibLogicalAccess.TaskAccessRights)accessRights.writeAccess, - readAndWriteAccess = (LibLogicalAccess.TaskAccessRights)accessRights.readAndWriteAccess - }, (uint)_fileSize); - break; - - case FileType_MifareDesfireFileType.BackupFile: - cmd.CreateBackupFile((byte)_fileNo, (LibLogicalAccess.EncryptionMode)_encMode, - new LibLogicalAccess.DESFireAccessRights() - { - changeAccess = (LibLogicalAccess.TaskAccessRights)accessRights.changeAccess, - readAccess = (LibLogicalAccess.TaskAccessRights)accessRights.readAccess, - writeAccess = (LibLogicalAccess.TaskAccessRights)accessRights.writeAccess, - readAndWriteAccess = (LibLogicalAccess.TaskAccessRights)accessRights.readAndWriteAccess - }, (uint)_fileSize); - break; - - case FileType_MifareDesfireFileType.ValueFile: - cmd.CreateValueFile((byte)_fileNo, (LibLogicalAccess.EncryptionMode)_encMode, - new LibLogicalAccess.DESFireAccessRights() - { - changeAccess = (LibLogicalAccess.TaskAccessRights)accessRights.changeAccess, - readAccess = (LibLogicalAccess.TaskAccessRights)accessRights.readAccess, - writeAccess = (LibLogicalAccess.TaskAccessRights)accessRights.writeAccess, - readAndWriteAccess = (LibLogicalAccess.TaskAccessRights)accessRights.readAndWriteAccess - }, (uint)_minValue, (uint)_maxValue, (uint)_initValue, _isValueLimited); - break; - - case FileType_MifareDesfireFileType.CyclicRecordFile: - cmd.CreateCyclicRecordFile((byte)_fileNo, (LibLogicalAccess.EncryptionMode)_encMode, - new LibLogicalAccess.DESFireAccessRights() - { - changeAccess = (LibLogicalAccess.TaskAccessRights)accessRights.changeAccess, - readAccess = (LibLogicalAccess.TaskAccessRights)accessRights.readAccess, - writeAccess = (LibLogicalAccess.TaskAccessRights)accessRights.writeAccess, - readAndWriteAccess = (LibLogicalAccess.TaskAccessRights)accessRights.readAndWriteAccess - }, (uint)_fileSize, (uint)_maxNbOfRecords); - break; - - case FileType_MifareDesfireFileType.LinearRecordFile: - cmd.CreateLinearRecordFile((byte)_fileNo, (LibLogicalAccess.EncryptionMode)_encMode, - new LibLogicalAccess.DESFireAccessRights() - { - changeAccess = (LibLogicalAccess.TaskAccessRights)accessRights.changeAccess, - readAccess = (LibLogicalAccess.TaskAccessRights)accessRights.readAccess, - writeAccess = (LibLogicalAccess.TaskAccessRights)accessRights.writeAccess, - readAndWriteAccess = (LibLogicalAccess.TaskAccessRights)accessRights.readAndWriteAccess - }, (uint)_fileSize, (uint)_maxNbOfRecords); - break; - - default: - break; - } - - return ERROR.NoError; - } - - switch (_fileType) - { - case FileType_MifareDesfireFileType.StdDataFile: - cmd.CreateStdDataFile((byte)_fileNo, (LibLogicalAccess.EncryptionMode)_encMode, - new LibLogicalAccess.DESFireAccessRights() - { - changeAccess = (LibLogicalAccess.TaskAccessRights)accessRights.changeAccess, - readAccess = (LibLogicalAccess.TaskAccessRights)accessRights.readAccess, - writeAccess = (LibLogicalAccess.TaskAccessRights)accessRights.writeAccess, - readAndWriteAccess = (LibLogicalAccess.TaskAccessRights)accessRights.readAndWriteAccess - }, (uint)_fileSize); - break; - - case FileType_MifareDesfireFileType.BackupFile: - cmd.CreateBackupFile((byte)_fileNo, (LibLogicalAccess.EncryptionMode)_encMode, - new LibLogicalAccess.DESFireAccessRights() - { - changeAccess = (LibLogicalAccess.TaskAccessRights)accessRights.changeAccess, - readAccess = (LibLogicalAccess.TaskAccessRights)accessRights.readAccess, - writeAccess = (LibLogicalAccess.TaskAccessRights)accessRights.writeAccess, - readAndWriteAccess = (LibLogicalAccess.TaskAccessRights)accessRights.readAndWriteAccess - }, (uint)_fileSize); - break; - - case FileType_MifareDesfireFileType.ValueFile: - cmd.CreateValueFile((byte)_fileNo, (LibLogicalAccess.EncryptionMode)_encMode, - new LibLogicalAccess.DESFireAccessRights() - { - changeAccess = (LibLogicalAccess.TaskAccessRights)accessRights.changeAccess, - readAccess = (LibLogicalAccess.TaskAccessRights)accessRights.readAccess, - writeAccess = (LibLogicalAccess.TaskAccessRights)accessRights.writeAccess, - readAndWriteAccess = (LibLogicalAccess.TaskAccessRights)accessRights.readAndWriteAccess - }, (uint)_minValue, (uint)_maxValue, (uint)_initValue, _isValueLimited); - break; - - case FileType_MifareDesfireFileType.CyclicRecordFile: - cmd.CreateCyclicRecordFile((byte)_fileNo, (LibLogicalAccess.EncryptionMode)_encMode, - new LibLogicalAccess.DESFireAccessRights() - { - changeAccess = (LibLogicalAccess.TaskAccessRights)accessRights.changeAccess, - readAccess = (LibLogicalAccess.TaskAccessRights)accessRights.readAccess, - writeAccess = (LibLogicalAccess.TaskAccessRights)accessRights.writeAccess, - readAndWriteAccess = (LibLogicalAccess.TaskAccessRights)accessRights.readAndWriteAccess - }, (uint)_fileSize, (uint)_maxNbOfRecords); - break; - - case FileType_MifareDesfireFileType.LinearRecordFile: - cmd.CreateLinearRecordFile((byte)_fileNo, (LibLogicalAccess.EncryptionMode)_encMode, - new LibLogicalAccess.DESFireAccessRights() - { - changeAccess = (LibLogicalAccess.TaskAccessRights)accessRights.changeAccess, - readAccess = (LibLogicalAccess.TaskAccessRights)accessRights.readAccess, - writeAccess = (LibLogicalAccess.TaskAccessRights)accessRights.writeAccess, - readAndWriteAccess = (LibLogicalAccess.TaskAccessRights)accessRights.readAndWriteAccess - }, (uint)_fileSize, (uint)_maxNbOfRecords); - break; - - default: - break; - } - - return ERROR.NoError; - } - catch (Exception e) - { - if (e.Message != "" && e.Message.Contains("same number already exists")) - { - return ERROR.ItemAlreadyExistError; - } - else if (e.Message != "" && e.Message.Contains("status does not allow the requested command")) - { - return ERROR.AuthenticationError; - } - else if (e.Message != "" && e.Message.Contains("Insufficient NV-Memory")) - { - return ERROR.OutOfMemory; - } - else - { - return ERROR.IOError; - } - } - } - else - { - return ERROR.NotReadyError; - } - } - } - } - return ERROR.NotReadyError; - } - catch - { - return ERROR.IOError; - } - } - - public override ERROR ReadMiFareDESFireChipFile(string _appMasterKey, DESFireKeyType _keyTypeAppMasterKey, - string _appReadKey, DESFireKeyType _keyTypeAppReadKey, int _readKeyNo, - string _appWriteKey, DESFireKeyType _keyTypeAppWriteKey, int _writeKeyNo, - EncryptionMode _encMode, - int _fileNo, int _appID, int _fileSize) - { - try - { - // The excepted memory tree - IDESFireLocation location = new DESFireLocation - { - // The Application ID to use - aid = _appID, - // File 0 into this application - File = _fileNo, - // File communication requires encryption - SecurityLevel = (LibLogicalAccess.EncryptionMode)_encMode - }; - - // Keys to use for authentication - - // Get the card storage service - var storage = (IStorageCardService)card.GetService(CardServiceType.CST_STORAGE); - - // Change keys with the following ones - IDESFireAccessInfo aiToWrite = new DESFireAccessInfo(); - CustomConverter.FormatMifareDesfireKeyStringWithSpacesEachByte(_appMasterKey); - aiToWrite.MasterApplicationKey.Value = CustomConverter.DesfireKeyToCheck; - aiToWrite.MasterApplicationKey.KeyType = (LibLogicalAccess.DESFireKeyType)_keyTypeAppMasterKey; - - CustomConverter.FormatMifareDesfireKeyStringWithSpacesEachByte(_appReadKey); - aiToWrite.ReadKey.Value = CustomConverter.DesfireKeyToCheck; - aiToWrite.ReadKey.KeyType = (LibLogicalAccess.DESFireKeyType)_keyTypeAppReadKey; - aiToWrite.ReadKeyNo = (byte)_readKeyNo; - - CustomConverter.FormatMifareDesfireKeyStringWithSpacesEachByte(_appWriteKey); - aiToWrite.WriteKey.Value = CustomConverter.DesfireKeyToCheck; - aiToWrite.WriteKey.KeyType = (LibLogicalAccess.DESFireKeyType)_keyTypeAppWriteKey; - aiToWrite.WriteKeyNo = (byte)_writeKeyNo; - - if (readerUnit.ConnectToReader()) - { - if (readerUnit.WaitInsertion(Constants.MAX_WAIT_INSERTION)) - { - if (readerUnit.Connect()) - { - if (card.Type == "DESFire" || - card.Type == "DESFireEV1" || - card.Type == "DESFireEV2") - { - try - { - var cmd = card.Commands as IDESFireCommands; - - try - { - - cmd.SelectApplication((uint)_appID); - - cmd.Authenticate((byte)_readKeyNo, aiToWrite.ReadKey); - - desfireFileSetting = cmd.GetFileSettings((byte)_fileNo); - DesfireFileSettings = new DESFireFileSettings - { - accessRights = desfireFileSetting.accessRights, - comSett = desfireFileSetting.comSett, - FileType = desfireFileSetting.FileType, - dataFile = new DataFileSetting { fileSize = desfireFileSetting.dataFile.fileSize } - }; - - MifareDESFireData = (byte[])cmd.ReadData((byte)_fileNo, 0, desfireFileSetting.dataFile.fileSize, (LibLogicalAccess.EncryptionMode)EncryptionMode.CM_ENCRYPT); - } - catch - { - cmd.SelectApplication((uint)_appID); - - cmd.Authenticate((byte)_readKeyNo, aiToWrite.ReadKey); - - MifareDESFireData = (byte[])cmd.ReadData((byte)_fileNo, 0, (uint)_fileSize, (LibLogicalAccess.EncryptionMode)EncryptionMode.CM_ENCRYPT); - } - - return ERROR.NoError; - } - - catch (Exception e) - { - if (e.Message != "" && e.Message.Contains("same number already exists")) - { - return ERROR.ItemAlreadyExistError; - } - else if (e.Message != "" && e.Message.Contains("status does not allow the requested command")) - { - return ERROR.AuthenticationError; - } - else - { - return ERROR.IOError; - } - } - } - else - { - return ERROR.NotReadyError; - } - } - } - } - return ERROR.NotReadyError; - } - - catch - { - return ERROR.IOError; - } - } - - public override ERROR WriteMiFareDESFireChipFile(string _cardMasterKey, DESFireKeyType _keyTypeCardMasterKey, - string _appMasterKey, DESFireKeyType _keyTypeAppMasterKey, - string _appReadKey, DESFireKeyType _keyTypeAppReadKey, int _readKeyNo, - string _appWriteKey, DESFireKeyType _keyTypeAppWriteKey, int _writeKeyNo, - EncryptionMode _encMode, - int _fileNo, int _appID, byte[] _data) - { - - try - { - // The excepted memory tree - IDESFireLocation location = new DESFireLocation - { - // The Application ID to use - aid = _appID, - // File 0 into this application - File = _fileNo, - // File communication requires encryption - SecurityLevel = (LibLogicalAccess.EncryptionMode)_encMode - }; - - // Keys to use for authentication - - // Get the card storage service - var storage = (IStorageCardService)card.GetService(CardServiceType.CST_STORAGE); - - // Change keys with the following ones - IDESFireAccessInfo aiToUse = new DESFireAccessInfo(); - CustomConverter.FormatMifareDesfireKeyStringWithSpacesEachByte(_cardMasterKey); - aiToUse.MasterCardKey.Value = CustomConverter.DesfireKeyToCheck; - aiToUse.MasterCardKey.KeyType = (LibLogicalAccess.DESFireKeyType)_keyTypeAppMasterKey; - - IDESFireAccessInfo aiToWrite = new DESFireAccessInfo(); - aiToWrite.MasterCardKey.Value = CustomConverter.DesfireKeyToCheck; - aiToWrite.MasterCardKey.KeyType = (LibLogicalAccess.DESFireKeyType)_keyTypeAppMasterKey; - CustomConverter.FormatMifareDesfireKeyStringWithSpacesEachByte(_appMasterKey); - aiToWrite.MasterApplicationKey.Value = CustomConverter.DesfireKeyToCheck; - aiToWrite.MasterApplicationKey.KeyType = (LibLogicalAccess.DESFireKeyType)_keyTypeAppMasterKey; - - CustomConverter.FormatMifareDesfireKeyStringWithSpacesEachByte(_appReadKey); - aiToWrite.ReadKey.Value = CustomConverter.DesfireKeyToCheck; - aiToWrite.ReadKey.KeyType = (LibLogicalAccess.DESFireKeyType)_keyTypeAppReadKey; - aiToWrite.ReadKeyNo = (byte)_readKeyNo; - - CustomConverter.FormatMifareDesfireKeyStringWithSpacesEachByte(_appWriteKey); - aiToWrite.WriteKey.Value = CustomConverter.DesfireKeyToCheck; - aiToWrite.WriteKey.KeyType = (LibLogicalAccess.DESFireKeyType)_keyTypeAppWriteKey; - aiToWrite.WriteKeyNo = (byte)_writeKeyNo; - - - if (readerUnit.ConnectToReader()) - { - if (readerUnit.WaitInsertion(Constants.MAX_WAIT_INSERTION)) - { - if (readerUnit.Connect()) - { - if (card.Type == "DESFire" || - card.Type == "DESFireEV1" || - card.Type == "DESFireEV2") - { - try - { - var cmd = card.Commands as IDESFireCommands; - - cmd.SelectApplication((uint)_appID); - - cmd.Authenticate((byte)_writeKeyNo, aiToWrite.WriteKey); - - cmd.WriteData((byte)_fileNo, 0, (uint)_data.Length, (LibLogicalAccess.EncryptionMode)EncryptionMode.CM_ENCRYPT, _data); - - try - { - cmd.CommitTransaction(); - } - - //continue if first try fails - catch { - } - - return ERROR.NoError; - } - - catch (Exception e) - { - if (e.Message != "" && e.Message.Contains("same number already exists")) - { - return ERROR.ItemAlreadyExistError; - } - else if (e.Message != "" && e.Message.Contains("status does not allow the requested command")) - { - return ERROR.AuthenticationError; - } - else - { - return ERROR.IOError; - } - } - } - else - { - return ERROR.NotReadyError; - } - } - } - } - return ERROR.NotReadyError; - } - - catch - { - return ERROR.IOError; - } - } - - public override ERROR AuthToMifareDesfireApplication(string _applicationMasterKey, DESFireKeyType _keyType, int _keyNumber, int _appID) - { - try - { - // The excepted memory tree - IDESFireLocation location = new DESFireLocation - { - // The Application ID to use - aid = _appID, - // File communication requires encryption - SecurityLevel = (LibLogicalAccess.EncryptionMode)EncryptionMode.CM_ENCRYPT - }; - - // Keys to use for authentication - IDESFireAccessInfo aiToUse = new DESFireAccessInfo(); - CustomConverter.FormatMifareDesfireKeyStringWithSpacesEachByte(_applicationMasterKey); - aiToUse.MasterCardKey.Value = CustomConverter.DesfireKeyToCheck; - aiToUse.MasterCardKey.KeyType = ((LibLogicalAccess.DESFireKeyType)_keyType); - - if (readerUnit.ConnectToReader()) - { - if (readerUnit.WaitInsertion(Constants.MAX_WAIT_INSERTION)) - { - if (readerUnit.Connect()) - { - ReaderUnitName = readerUnit.ConnectedName; - - card = readerUnit.GetSingleChip(); - - if (card.Type == "DESFire" || - card.Type == "DESFireEV1" || - card.Type == "DESFireEV2") - { - var cmd = card.Commands as IDESFireCommands; - try - { - cmd.SelectApplication((uint)_appID); - if (_appID > 0) - { - cmd.Authenticate((byte)_keyNumber, aiToUse.MasterCardKey); - } - else - { - cmd.Authenticate((byte)0, aiToUse.MasterCardKey); - } - - return ERROR.NoError; - } - - catch (Exception e) - { - if (e.Message != "" && e.Message.Contains("same number already exists")) - { - return ERROR.ItemAlreadyExistError; - } - else if (e.Message != "" && e.Message.Contains("status does not allow the requested command")) - { - return ERROR.AuthenticationError; - } - else - { - return ERROR.IOError; - } - } - } - - else - { - return ERROR.NotReadyError; - } - } - } - } - return ERROR.NotReadyError; - } - catch - { - return ERROR.IOError; - } - } - - public override ERROR GetMifareDesfireAppSettings(string _applicationMasterKey, DESFireKeyType _keyType, int _keyNumberCurrent, int _appID) - { - byte maxNbrOfKeys; - LibLogicalAccess.DESFireKeySettings keySettings; - LibLogicalAccess.DESFireKeyType keyType; - - try - { - // Keys to use for authentication - IDESFireAccessInfo aiToUse = new DESFireAccessInfo(); - CustomConverter.FormatMifareDesfireKeyStringWithSpacesEachByte(_applicationMasterKey); - aiToUse.MasterCardKey.Value = CustomConverter.DesfireKeyToCheck; - aiToUse.MasterCardKey.KeyType = ((LibLogicalAccess.DESFireKeyType)_keyType); - - if (readerUnit.ConnectToReader()) - { - if (readerUnit.WaitInsertion(Constants.MAX_WAIT_INSERTION)) - { - if (readerUnit.Connect()) - { - ReaderUnitName = readerUnit.ConnectedName; - card = readerUnit.GetSingleChip(); - - if (card.Type == "DESFire") - { - var cmd = card.Commands as IDESFireCommands; - ReaderUnitName = readerUnit.ConnectedName; - - try - { - cmd.SelectApplication((uint)_appID); - GenericChip = new GenericChipModel(card.ChipIdentifier, (CARD_TYPE)Enum.Parse(typeof(CARD_TYPE), card.Type)); - - try - { - cmd.Authenticate((byte)_keyNumberCurrent, aiToUse.MasterCardKey); - } - - catch - { - try - { - cmd.GetKeySettings(out keySettings, out maxNbrOfKeys); - MaxNumberOfAppKeys = (byte)(maxNbrOfKeys & 0x0F); - EncryptionType = (DESFireKeyType)(maxNbrOfKeys & 0xF0); - DesfireAppKeySetting = (DESFireKeySettings)keySettings; - - return ERROR.NoError; - } - catch (Exception e) - { - if (e.Message != "" && e.Message.Contains("same number already exists")) - { - return ERROR.ItemAlreadyExistError; - } - else if (e.Message != "" && e.Message.Contains("status does not allow the requested command")) - { - return ERROR.AuthenticationError; - } - else - { - return ERROR.IOError; - } - } - } - cmd.GetKeySettings(out keySettings, out maxNbrOfKeys); - MaxNumberOfAppKeys = (byte)(maxNbrOfKeys & 0x0F); - EncryptionType = (DESFireKeyType)(maxNbrOfKeys & 0xF0); - DesfireAppKeySetting = (DESFireKeySettings)keySettings; - - return ERROR.NoError; - } - catch (Exception e) - { - if (e.Message != "" && e.Message.Contains("same number already exists")) - { - return ERROR.ItemAlreadyExistError; - } - else if (e.Message != "" && e.Message.Contains("status does not allow the requested command")) - { - return ERROR.AuthenticationError; - } - else - { - return ERROR.IOError; - } - } - } - - else if (card.Type == "DESFireEV1" || - card.Type == "DESFireEV2" || card.Type == "GENERIC_T_CL_A") - { - var cmd = card.Commands as IDESFireEV1Commands; - - ReaderUnitName = readerUnit.ConnectedName; - - try - { - cmd.SelectApplication((uint)_appID); - GenericChip = new GenericChipModel(card.ChipIdentifier, (CARD_TYPE)Enum.Parse(typeof(CARD_TYPE), card.Type)); - - try - { - cmd.Authenticate((byte)_keyNumberCurrent, aiToUse.MasterCardKey); - } - - catch - { - try - { - try - { - DesfireChip.FreeMemory = cmd.GetFreeMemory(); - } - - catch { } - - cmd.GetKeySettingsEV1(out keySettings, out maxNbrOfKeys, out keyType); - MaxNumberOfAppKeys = (byte)(maxNbrOfKeys & 0x0F); - EncryptionType = (DESFireKeyType)keyType; - DesfireAppKeySetting = (DESFireKeySettings)keySettings; - - return ERROR.NoError; - } - catch (Exception e) - { - if (e.Message != "" && e.Message.Contains("same number already exists")) - { - return ERROR.ItemAlreadyExistError; - } - else if (e.Message != "" && e.Message.Contains("status does not allow the requested command")) - { - return ERROR.NotAllowed; - } - else - { - return ERROR.IOError; - } - } - } - - try - { - DesfireChip.FreeMemory = cmd.GetFreeMemory(); - } - - catch { } - - cmd.GetKeySettingsEV1(out keySettings, out maxNbrOfKeys, out keyType); - MaxNumberOfAppKeys = (byte)(maxNbrOfKeys & 0x0F); - EncryptionType = (DESFireKeyType)keyType; - DesfireAppKeySetting = (DESFireKeySettings)keySettings; - - return ERROR.NoError; - } - catch (Exception e) - { - if (e.Message != "" && e.Message.Contains("same number already exists")) - { - return ERROR.ItemAlreadyExistError; - } - else if (e.Message != "" && e.Message.Contains("status does not allow the requested command")) - { - return ERROR.AuthenticationError; - } - else - { - return ERROR.IOError; - } - } - } - - else - { - return ERROR.NotReadyError; - } - } - } - } - return ERROR.NotReadyError; - } - catch - { - return ERROR.IOError; - } - } - - public override ERROR CreateMifareDesfireApplication( - string _piccMasterKey, DESFireKeySettings _keySettingsTarget, DESFireKeyType _keyTypePiccMasterKey, - DESFireKeyType _keyTypeTargetApplication, int _maxNbKeys, int _appID, bool authenticateToPICCFirst) - { - try - { - // The excepted memory tree - IDESFireLocation location = new DESFireLocation - { - // The Application ID to use - aid = _appID, - // File communication requires encryption - SecurityLevel = (LibLogicalAccess.EncryptionMode)EncryptionMode.CM_ENCRYPT - }; - - // Keys to use for authentication - IDESFireAccessInfo aiToUse = new DESFireAccessInfo(); - CustomConverter.FormatMifareDesfireKeyStringWithSpacesEachByte(_piccMasterKey); - aiToUse.MasterCardKey.Value = CustomConverter.DesfireKeyToCheck; - aiToUse.MasterCardKey.KeyType = (LibLogicalAccess.DESFireKeyType)_keyTypePiccMasterKey; - - if (readerUnit.ConnectToReader()) - { - if (readerUnit.WaitInsertion(Constants.MAX_WAIT_INSERTION)) - { - if (readerUnit.Connect()) - { - ReaderUnitName = readerUnit.ConnectedName; - - card = readerUnit.GetSingleChip(); - - if (card.Type == "DESFire") - { - var cmd = card.Commands as IDESFireCommands; - try - { - cmd.SelectApplication(0); - - if (authenticateToPICCFirst) - { - cmd.Authenticate(0, aiToUse.MasterCardKey); - } - - cmd.CreateApplication((uint)_appID, (LibLogicalAccess.DESFireKeySettings)_keySettingsTarget, (byte)_maxNbKeys); - - return ERROR.NoError; - } - catch (Exception e) - { - - if (e.Message != "" && e.Message.Contains("same number already exists")) - { - return ERROR.ItemAlreadyExistError; - } - else if (e.Message != "" && e.Message.Contains("status does not allow the requested command")) - { - return ERROR.AuthenticationError; - } - else - { - return ERROR.IOError; - } - } - } - - else if (card.Type == "DESFireEV1" || - card.Type == "DESFireEV2") - { - var cmd = card.Commands as IDESFireEV1Commands; - - try - { - cmd.SelectApplication(0); - - if (authenticateToPICCFirst) - { - cmd.Authenticate((byte)0, aiToUse.MasterCardKey); - } - - cmd.CreateApplicationEV1((uint)_appID, (LibLogicalAccess.DESFireKeySettings)_keySettingsTarget, (byte)_maxNbKeys, false, (LibLogicalAccess.DESFireKeyType)_keyTypeTargetApplication, 0, 0); - - return ERROR.NoError; - } - catch (Exception e) - { - if (e.Message != "" && e.Message.Contains("same number already exists")) - { - return ERROR.ItemAlreadyExistError; - } - else if (e.Message != "" && e.Message.Contains("status does not allow the requested command")) - { - return ERROR.AuthenticationError; - } - else if (e.Message != "" && e.Message.Contains("Insufficient NV-Memory")) - { - return ERROR.OutOfMemory; - } - else - { - return ERROR.IOError; - } - } - } - else - { - return ERROR.NotReadyError; - } - } - } - } - return ERROR.NotReadyError; - } - catch - { - return ERROR.IOError; - } - } - - public override ERROR ChangeMifareDesfireApplicationKey( - string _applicationMasterKeyCurrent, int _keyNumberCurrent, DESFireKeyType _keyTypeCurrent, - string _applicationMasterKeyTarget, int _keyNumberTarget, int selectedDesfireAppKeyVersionTargetAsIntint, - DESFireKeyType _keyTypeTarget, int _appIDCurrent, int _appIDTarget, DESFireKeySettings keySettings, int keyVersion) - { - try - { - DESFireKey masterApplicationKey = new DESFireKeyClass - { - KeyType = (LibLogicalAccess.DESFireKeyType)_keyTypeCurrent - }; - - CustomConverter.FormatMifareDesfireKeyStringWithSpacesEachByte(_applicationMasterKeyCurrent); - masterApplicationKey.Value = CustomConverter.DesfireKeyToCheck; - masterApplicationKey.KeyVersion = (byte)keyVersion; - - DESFireKey applicationMasterKeyTarget = new DESFireKeyClass - { - KeyType = (LibLogicalAccess.DESFireKeyType)_keyTypeCurrent - }; - CustomConverter.FormatMifareDesfireKeyStringWithSpacesEachByte(_applicationMasterKeyTarget); - applicationMasterKeyTarget.Value = CustomConverter.DesfireKeyToCheck; - - if (readerUnit.ConnectToReader()) - { - if (readerUnit.WaitInsertion(Constants.MAX_WAIT_INSERTION)) - { - if (readerUnit.Connect()) - { - ReaderUnitName = readerUnit.ConnectedName; - - card = readerUnit.GetSingleChip(); - - if (card.Type == "DESFire" || - card.Type == "DESFireEV1" || - card.Type == "DESFireEV2") - { - var cmd = card.Commands as IDESFireCommands; - - try - { - if (_appIDCurrent == 0) - { - try - { - applicationMasterKeyTarget.KeyType = (LibLogicalAccess.DESFireKeyType)_keyTypeTarget; - - cmd.SelectApplication((uint)0); - cmd.Authenticate((byte)0, masterApplicationKey); - cmd.ChangeKeySettings((LibLogicalAccess.DESFireKeySettings)keySettings); - cmd.Authenticate((byte)0, masterApplicationKey); - cmd.ChangeKey((byte)0, applicationMasterKeyTarget); - return ERROR.NoError; - } - - catch - { - try - { - cmd.Authenticate((byte)0, masterApplicationKey); - cmd.ChangeKey((byte)0, applicationMasterKeyTarget); - } - catch (Exception e) - { - if (e.Message != "" && e.Message.Contains("same number already exists")) - { - return ERROR.ItemAlreadyExistError; - } - else if (e.Message != "" && e.Message.Contains("status does not allow the requested command")) - { - return ERROR.AuthenticationError; - } - else - { - return ERROR.IOError; - } - } - } - } - else - { - - applicationMasterKeyTarget.KeyType = ((LibLogicalAccess.DESFireKeyType)_keyTypeCurrent); - - cmd.SelectApplication((uint)_appIDCurrent); - - try - { - cmd.Authenticate((byte)_keyNumberCurrent, masterApplicationKey); - cmd.ChangeKey((byte)_keyNumberTarget, applicationMasterKeyTarget); - cmd.Authenticate((byte)_keyNumberCurrent, applicationMasterKeyTarget); - - try - { - cmd.ChangeKeySettings((LibLogicalAccess.DESFireKeySettings)keySettings); - } - catch { } - } +using RFiDGear.Model; - catch (Exception ex) - { - try - { - cmd.Authenticate((byte)_keyNumberCurrent, masterApplicationKey); - cmd.ChangeKeySettings((LibLogicalAccess.DESFireKeySettings)keySettings); - cmd.Authenticate((byte)_keyNumberCurrent, masterApplicationKey); - cmd.ChangeKey((byte)_keyNumberTarget, applicationMasterKeyTarget); - return ERROR.NoError; - } - - catch - { - try - { - cmd.Authenticate((byte)_keyNumberCurrent, masterApplicationKey); - cmd.ChangeKey((byte)_keyNumberTarget, applicationMasterKeyTarget); - } - catch (Exception e) - { - if (e.Message != "" && e.Message.Contains("same number already exists")) - { - return ERROR.ItemAlreadyExistError; - } - else if (e.Message != "" && e.Message.Contains("status does not allow the requested command")) - { - return ERROR.AuthenticationError; - } - else - { - return ERROR.IOError; - } - } - } - } - } +using Log4CSharp; - return ERROR.NoError; - } - catch (Exception e) - { - if (e.Message != "" && e.Message.Contains("same number already exists")) - { - return ERROR.ItemAlreadyExistError; - } - else if (e.Message != "" && e.Message.Contains("status does not allow the requested command")) - { - return ERROR.AuthenticationError; - } - else - { - return ERROR.IOError; - } - } - } - else - { - return ERROR.NotReadyError; - } - } - } - } - return ERROR.NotReadyError; - } - catch - { - return ERROR.IOError; - } - } +using System; +using System.Threading; - public override ERROR DeleteMifareDesfireApplication(string _applicationMasterKey, DESFireKeyType _keyType, int _appID) - { - try - { - // The excepted memory tree - IDESFireLocation location = new DESFireLocation - { - // The Application ID to use - aid = _appID, - // File communication requires encryption - SecurityLevel = (LibLogicalAccess.EncryptionMode)EncryptionMode.CM_ENCRYPT - }; - - // Keys to use for authentication - IDESFireAccessInfo aiToUse = new DESFireAccessInfo(); - CustomConverter.FormatMifareDesfireKeyStringWithSpacesEachByte(_applicationMasterKey); - aiToUse.MasterCardKey.Value = CustomConverter.DesfireKeyToCheck; - aiToUse.MasterCardKey.KeyType = (LibLogicalAccess.DESFireKeyType)_keyType; - - if (readerUnit.ConnectToReader()) - { - if (readerUnit.WaitInsertion(Constants.MAX_WAIT_INSERTION)) - { - if (readerUnit.Connect()) - { - ReaderUnitName = readerUnit.ConnectedName; +namespace RFiDGear.DataAccessLayer.Remote.FromIO +{ + /// + /// Description of RFiDAccess. + /// + /// Initialize Reader + /// + /// + public class LibLogicalAccessProvider : ReaderDevice, IDisposable + { + // global (cross-class) Instances go here -> + private static readonly string FacilityName = "RFiDGear"; + private ReaderProvider readerProvider; + private ReaderUnit readerUnit; + private Chip card; + #region properties + + #endregion properties + + #region contructor + public LibLogicalAccessProvider() + { + } + + public LibLogicalAccessProvider(ReaderTypes readerType) + { + try + { + readerProvider = LibraryManager.getInstance().getReaderProvider(Enum.GetName(typeof(ReaderTypes), readerType)); + readerUnit = readerProvider.createReaderUnit(); + + GenericChip = new GenericChipModel("", CARD_TYPE.Unspecified); + AppIDList = new uint[0]; + } + catch (Exception e) + { + LogWriter.CreateLogEntry(e, FacilityName); + } + } - card = readerUnit.GetSingleChip(); + #endregion contructor - if (card.Type == "DESFire" || - card.Type == "DESFireEV1" || - card.Type == "DESFireEV2") - { - var cmd = card.Commands as IDESFireCommands; - try - { - cmd.SelectApplication(0); - cmd.Authenticate(0, aiToUse.MasterCardKey); + #region common - cmd.DeleteApplication((uint)_appID); - return ERROR.NoError; - } - catch - { - try - { - cmd.SelectApplication((uint)_appID); - cmd.Authenticate(0, aiToUse.MasterCardKey); - cmd.DeleteApplication((uint)_appID); - return ERROR.NoError; - } + public override ERROR Connect() => throw new NotImplementedException(); - catch (Exception e) - { - if (e.Message != "" && e.Message.Contains("same number already exists")) - { - return ERROR.ItemAlreadyExistError; - } - else if (e.Message != "" && e.Message.Contains("status does not allow the requested command")) - { - return ERROR.AuthenticationError; - } - else - { - return ERROR.IOError; - } - } + public override ERROR ReadChipPublic() + { + try + { + if (readerUnit.connectToReader()) + { + if (readerUnit.waitInsertion(Constants.MAX_WAIT_INSERTION)) + { + if (readerUnit.connect()) + { + ReaderUnitName = readerUnit.getConnectedName(); + + card = readerUnit.getSingleChip(); + + if (!string.IsNullOrWhiteSpace(ByteConverter.GetStringFrom(card.getChipIdentifier().ToArray()))) + { + try { + //CardInfo = new CARD_INFO((CARD_TYPE)Enum.Parse(typeof(CARD_TYPE), card.getCardType()), ByteConverter.GetStringFrom(card.getChipIdentifier().ToArray())); + //readerUnit.Disconnect(); + + GenericChip = new GenericChipModel(ByteConverter.GetStringFrom(card.getChipIdentifier().ToArray()), (CARD_TYPE)Enum.Parse(typeof(CARD_TYPE), card.getCardType())); + + if (card.getCardType().Contains("DESFire")) + { + DESFireCommands cmd = card.getCommands() as DESFireCommands; + + DESFireCommands.DESFireCardVersion version = cmd.getVersion(); + + if (version.hardwareMjVersion == 1) + GenericChip.CardType = CARD_TYPE.DESFireEV1; + + else if (version.hardwareMjVersion == 2) + GenericChip.CardType = CARD_TYPE.DESFireEV2; + } + + //ISO15693Commands commands = card.Commands as ISO15693Commands; + //SystemInformation si = commands.GetSystemInformation(); + //var block=commands.ReadBlock(21, 4); + return ERROR.NoError; + } + catch (Exception e) { + LogWriter.CreateLogEntry(e, FacilityName); + + return ERROR.IOError; + } + } + else + return ERROR.NotReadyError; + } + } + } + } + catch (Exception e) + { + if (readerProvider != null) + readerProvider.release(); + + LogWriter.CreateLogEntry(e, FacilityName); + + return ERROR.IOError; + } + + return ERROR.IOError; + } + + #endregion common + + #region mifare classic + + public override ERROR ReadMifareClassicSingleSector(int sectorNumber, string aKey, string bKey) + { + var settings = new SettingsReaderWriter(); + Sector = new MifareClassicSectorModel(); + + settings.ReadSettings(); + + var keyA = new MifareKey(CustomConverter.KeyFormatQuickCheck(aKey) ? aKey : CustomConverter.FormatMifareClassicKeyWithSpacesEachByte(aKey) ); + var keyB = new MifareKey(CustomConverter.KeyFormatQuickCheck(bKey) ? bKey : CustomConverter.FormatMifareClassicKeyWithSpacesEachByte(bKey) ); + + try + { + if (readerUnit.connectToReader()) { + if (readerUnit.waitInsertion(Constants.MAX_WAIT_INSERTION)) { + if (readerUnit.connect()) + { + ReaderUnitName = readerUnit.getConnectedName(); + + card = readerUnit.getSingleChip(); + + if (!string.IsNullOrWhiteSpace(ByteConverter.GetStringFrom(card.getChipIdentifier().ToArray()))) + { + try { + //CardInfo = new CARD_INFO((CARD_TYPE)Enum.Parse(typeof(CARD_TYPE), card.getCardType()), ByteConverter.GetStringFrom(card.getChipIdentifier().ToArray())); + GenericChip = new GenericChipModel(ByteConverter.GetStringFrom(card.getChipIdentifier().ToArray()), (CARD_TYPE)Enum.Parse(typeof(CARD_TYPE), card.getCardType())); } - } - return ERROR.NotReadyError; - } - } - } - return ERROR.NotReadyError; - } - catch - { - return ERROR.IOError; - } - } - - public override ERROR DeleteMifareDesfireFile(string _applicationMasterKey, DESFireKeyType _keyType, int _appID, int _fileID) - { - try - { - // The excepted memory tree - IDESFireLocation location = new DESFireLocation - { - // The Application ID to use - aid = _appID, - // File communication requires encryption - SecurityLevel = (LibLogicalAccess.EncryptionMode)EncryptionMode.CM_ENCRYPT - }; - - // Keys to use for authentication - IDESFireAccessInfo aiToUse = new DESFireAccessInfo(); - CustomConverter.FormatMifareDesfireKeyStringWithSpacesEachByte(_applicationMasterKey); - aiToUse.MasterCardKey.Value = CustomConverter.DesfireKeyToCheck; - aiToUse.MasterCardKey.KeyType = ((LibLogicalAccess.DESFireKeyType)_keyType); - - if (readerUnit.ConnectToReader()) - { - if (readerUnit.WaitInsertion(Constants.MAX_WAIT_INSERTION)) - { - if (readerUnit.Connect()) - { - ReaderUnitName = readerUnit.ConnectedName; + catch (Exception e) { + LogWriter.CreateLogEntry(e, FacilityName); + } + } + + var cmd = card.getCommands() as MifareCommands; + + try + { //try to Auth with Keytype A + for (int k = 0; k < (sectorNumber > 31 ? 16 : 4); k++) // if sector > 31 is 16 blocks each sector i.e. mifare 4k else its 1k or 2k with 4 blocks each sector + { + cmd.loadKey((byte)0, MifareKeyType.KT_KEY_A, keyA); + + DataBlock = new MifareClassicDataBlockModel( + (byte)CustomConverter.GetChipBasedDataBlockNumber(GenericChip.CardType, sectorNumber, k), + k); + + try + { + cmd.authenticate((byte)CustomConverter.GetChipBasedDataBlockNumber(GenericChip.CardType, sectorNumber, k), + (byte)0, + MifareKeyType.KT_KEY_A); + + Sector.IsAuthenticated = true; + + try + { + ByteVector data = cmd.readBinary( + (byte)CustomConverter.GetChipBasedDataBlockNumber(GenericChip.CardType, sectorNumber, k), + 48); + + DataBlock.Data = data.ToArray(); + + DataBlock.IsAuthenticated = true; + + Sector.DataBlock.Add(DataBlock); + } + catch + { + DataBlock.IsAuthenticated = false; + Sector.DataBlock.Add(DataBlock); + } + } + catch + { // Try Auth with keytype b + + try + { + cmd.loadKey((byte)1, MifareKeyType.KT_KEY_B, keyB); + + cmd.authenticate( + (byte)CustomConverter.GetChipBasedDataBlockNumber(GenericChip.CardType, sectorNumber, k), + (byte)1, + MifareKeyType.KT_KEY_B); + + Sector.IsAuthenticated = true; + + try + { + object data = cmd.readBinary( + (byte)CustomConverter.GetChipBasedDataBlockNumber(GenericChip.CardType, sectorNumber, k), + 48); + + DataBlock.Data = (byte[])data; + + DataBlock.IsAuthenticated = true; + + Sector.DataBlock.Add(DataBlock); + } + catch + { + + DataBlock.IsAuthenticated = false; + + Sector.DataBlock.Add(DataBlock); + + return ERROR.AuthenticationError; + } + } + catch + { + Sector.IsAuthenticated = false; + DataBlock.IsAuthenticated = false; + + Sector.DataBlock.Add(DataBlock); + + return ERROR.AuthenticationError; + } + } + } + } + catch + { + return ERROR.NoError; + } + return ERROR.NoError; + } + return ERROR.NotReadyError; + } + return ERROR.NotReadyError; + } + return ERROR.NotReadyError; + } + catch (Exception e) + { + LogWriter.CreateLogEntry(e, FacilityName); + return ERROR.AuthenticationError; + } + } - card = readerUnit.GetSingleChip(); - if (card.Type == "DESFireEV1" || - card.Type == "DESFireEV2" || - card.Type == "DESFire") - { - try - { - var cmd = card.Commands as IDESFireCommands; + public override ERROR WriteMifareClassicSingleSector(int sectorNumber, string _aKey, string _bKey, byte[] buffer) + { + var keyA = new MifareKey(CustomConverter.FormatMifareClassicKeyWithSpacesEachByte(_aKey)); + var keyB = new MifareKey(CustomConverter.FormatMifareClassicKeyWithSpacesEachByte(_bKey)); + + int blockCount = 0; + + try + { + if (readerUnit.connectToReader()) + { + if (readerUnit.waitInsertion(Constants.MAX_WAIT_INSERTION)) + { + if (readerUnit.connect()) + { + ReaderUnitName = readerUnit.getConnectedName(); + //readerSerialNumber = readerUnit.GetReaderSerialNumber(); + + card = readerUnit.getSingleChip(); + + if (!string.IsNullOrWhiteSpace(ByteConverter.GetStringFrom(card.getChipIdentifier().ToArray()))) + { + try { + //CardInfo = new CARD_INFO((CARD_TYPE)Enum.Parse(typeof(CARD_TYPE), card.getCardType()), ByteConverter.GetStringFrom(card.getChipIdentifier().ToArray())); + GenericChip = new GenericChipModel(ByteConverter.GetStringFrom(card.getChipIdentifier().ToArray()), (CARD_TYPE)Enum.Parse(typeof(CARD_TYPE), card.getCardType())); + } + catch (Exception e) { + LogWriter.CreateLogEntry(e, FacilityName); + } + } + + var cmd = card.getCommands() as MifareCommands; + + try + { //try to Auth with Keytype A + cmd.loadKey((byte)0, MifareKeyType.KT_KEY_A, keyA); + cmd.loadKey((byte)1, MifareKeyType.KT_KEY_B, keyB); + + for (int k = 0; k < blockCount; k++) + { + try + { + cmd.authenticate( + (byte)CustomConverter.GetChipBasedDataBlockNumber(GenericChip.CardType, sectorNumber, k), + (byte)0, + MifareKeyType.KT_KEY_A); + + try + { + cmd.updateBinary( + (byte)CustomConverter.GetChipBasedDataBlockNumber(GenericChip.CardType, sectorNumber, k), + new ByteVector(buffer)); + + return ERROR.NoError; + } + catch + { + return ERROR.AuthenticationError; + } + } + catch + { // Try Auth with keytype b + + try + { + cmd.authenticate((byte)CustomConverter.GetChipBasedDataBlockNumber(GenericChip.CardType, sectorNumber, k), + (byte)1, + MifareKeyType.KT_KEY_B); + + try + { + cmd.updateBinary( + (byte)CustomConverter.GetChipBasedDataBlockNumber(GenericChip.CardType, sectorNumber, k), + new ByteVector(buffer)); + + return ERROR.NoError; + + } + catch + { + return ERROR.AuthenticationError; + } + } + catch + { + + } + } + } + } + catch + { + return ERROR.IOError; + } + return ERROR.NotReadyError; + } + } + } + } + catch (Exception e) + { + LogWriter.CreateLogEntry(e, FacilityName); + + return ERROR.IOError; + } + return ERROR.NotReadyError; + } + + public override ERROR WriteMifareClassicSingleBlock(int _blockNumber, string _aKey, string _bKey, byte[] buffer) + { + try + { + var keyA = new MifareKey(CustomConverter.FormatMifareClassicKeyWithSpacesEachByte(_aKey)); + var keyB = new MifareKey(CustomConverter.FormatMifareClassicKeyWithSpacesEachByte(_bKey)); + + if (readerUnit.connectToReader()) + { + if (readerUnit.waitInsertion(Constants.MAX_WAIT_INSERTION)) + { + if (readerUnit.connect()) + { + ReaderUnitName = readerUnit.getConnectedName(); + //readerSerialNumber = readerUnit.GetReaderSerialNumber(); + + card = readerUnit.getSingleChip(); + + if (!string.IsNullOrWhiteSpace(ByteConverter.GetStringFrom(card.getChipIdentifier().ToArray()))) + { + try { + //CardInfo = new CARD_INFO((CARD_TYPE)Enum.Parse(typeof(CARD_TYPE), card.getCardType()), ByteConverter.GetStringFrom(card.getChipIdentifier().ToArray())); + GenericChip = new GenericChipModel(ByteConverter.GetStringFrom(card.getChipIdentifier().ToArray()), (CARD_TYPE)Enum.Parse(typeof(CARD_TYPE), card.getCardType())); + } + catch (Exception e) { + LogWriter.CreateLogEntry(e, FacilityName); + } + } + + var cmd = card.getCommands() as MifareCommands; + + try + { + cmd.loadKey((byte)0, MifareKeyType.KT_KEY_A, keyA); // FIXME "sectorNumber" to 0 + + try + { //try to Auth with Keytype A + cmd.authenticate((byte)(_blockNumber), (byte)0, MifareKeyType.KT_KEY_A); // FIXME same as '303 + + cmd.updateBinary((byte)_blockNumber, new ByteVector(buffer)); + + return ERROR.NoError; + } + catch + { // Try Auth with Keytype b + + cmd.loadKey((byte)0, MifareKeyType.KT_KEY_B, keyB); + + try + { + cmd.authenticate((byte)(_blockNumber), (byte)0, MifareKeyType.KT_KEY_B); // FIXME same as '303 + + cmd.updateBinary((byte)(_blockNumber), new ByteVector(buffer)); + + return ERROR.NoError; + } + catch + { + return ERROR.AuthenticationError; + } + } + } + catch + { + return ERROR.AuthenticationError; + } + } + } + } + } + catch (Exception e) + { + LogWriter.CreateLogEntry(e, FacilityName); + + return ERROR.IOError; + } + return ERROR.IOError; + } + + public override ERROR ReadMifareClassicSingleBlock(int _blockNumber, string _aKey, string _bKey) + { + try + { + var keyA = new MifareKey(CustomConverter.FormatMifareClassicKeyWithSpacesEachByte(_aKey)); + var keyB = new MifareKey(CustomConverter.FormatMifareClassicKeyWithSpacesEachByte(_bKey)); + + if (readerUnit.connectToReader()) + { + if (readerUnit.waitInsertion(Constants.MAX_WAIT_INSERTION)) + { + if (readerUnit.connect()) + { + ReaderUnitName = readerUnit.getConnectedName(); + //readerSerialNumber = readerUnit.GetReaderSerialNumber(); + + card = readerUnit.getSingleChip(); + + if (!string.IsNullOrWhiteSpace(ByteConverter.GetStringFrom(card.getChipIdentifier().ToArray()))) + { + try { + //CardInfo = new CARD_INFO((CARD_TYPE)Enum.Parse(typeof(CARD_TYPE), card.getCardType()), ByteConverter.GetStringFrom(card.getChipIdentifier().ToArray())); + GenericChip = new GenericChipModel(ByteConverter.GetStringFrom(card.getChipIdentifier().ToArray()), (CARD_TYPE)Enum.Parse(typeof(CARD_TYPE), card.getCardType())); + } + catch (Exception e) { + LogWriter.CreateLogEntry(e, FacilityName); + } + } + + var cmd = card.getCommands() as MifareCommands; + + try + { + cmd.loadKey((byte)0, MifareKeyType.KT_KEY_A, keyA); // FIXME "sectorNumber" to 0 + + try + { //try to Auth with Keytype A + cmd.authenticate((byte)(_blockNumber), (byte)0, MifareKeyType.KT_KEY_A); // FIXME same as '303 + + MifareClassicData = cmd.readBinary((byte)(_blockNumber), 48).ToArray(); + + return ERROR.NoError; + } + catch + { // Try Auth with keytype b + + cmd.loadKey((byte)0, MifareKeyType.KT_KEY_B, keyB); + + try + { + cmd.authenticate((byte)(_blockNumber), (byte)0, MifareKeyType.KT_KEY_B); // FIXME same as '303 + + MifareClassicData = cmd.readBinary((byte)(_blockNumber), 48).ToArray(); + + return ERROR.NoError; + } + catch + { + return ERROR.AuthenticationError; + } + } + } + catch + { + return ERROR.AuthenticationError; + } + } + } + } + } + catch (Exception e) + { + LogWriter.CreateLogEntry(e, FacilityName); + + return ERROR.IOError; + } + return ERROR.IOError; + } + + public override ERROR WriteMifareClassicWithMAD(int _madApplicationID, int _madStartSector, + string _aKeyToUse, string _bKeyToUse, string _aKeyToWrite, string _bKeyToWrite, + string _madAKeyToUse, string _madBKeyToUse, string _madAKeyToWrite, string _madBKeyToWrite, + byte[] buffer, byte _madGPB, SectorAccessBits _sab, bool _useMADToAuth = false, bool _keyToWriteUseMAD = false) + { + var settings = new SettingsReaderWriter(); + Sector = new MifareClassicSectorModel(); + + settings.ReadSettings(); + + var mAKeyToUse = new MifareKey(CustomConverter.KeyFormatQuickCheck(_aKeyToUse) ? _aKeyToUse : CustomConverter.FormatMifareClassicKeyWithSpacesEachByte(_aKeyToUse)); + var mBKeyToUse = new MifareKey(CustomConverter.KeyFormatQuickCheck(_bKeyToUse) ? _bKeyToUse : CustomConverter.FormatMifareClassicKeyWithSpacesEachByte(_bKeyToUse)); + + var mAKeyToWrite = new MifareKey(CustomConverter.KeyFormatQuickCheck(_aKeyToWrite) ? _aKeyToWrite : CustomConverter.FormatMifareClassicKeyWithSpacesEachByte(_aKeyToWrite)); + var mBKeyToWrite = new MifareKey(CustomConverter.KeyFormatQuickCheck(_bKeyToWrite) ? _bKeyToWrite : CustomConverter.FormatMifareClassicKeyWithSpacesEachByte(_bKeyToWrite)); + + var madAKeyToUse = new MifareKey(CustomConverter.KeyFormatQuickCheck(_madAKeyToUse) ? _madAKeyToUse : CustomConverter.FormatMifareClassicKeyWithSpacesEachByte(_madAKeyToUse)); + var madBKeyToUse = new MifareKey(CustomConverter.KeyFormatQuickCheck(_madBKeyToUse) ? _madBKeyToUse : CustomConverter.FormatMifareClassicKeyWithSpacesEachByte(_madBKeyToUse)); + + var madAKeyToWrite = new MifareKey(CustomConverter.KeyFormatQuickCheck(_madAKeyToWrite) ? _madAKeyToWrite : CustomConverter.FormatMifareClassicKeyWithSpacesEachByte(_madAKeyToWrite)); + var madBKeyToWrite = new MifareKey(CustomConverter.KeyFormatQuickCheck(_madBKeyToWrite) ? _madBKeyToWrite : CustomConverter.FormatMifareClassicKeyWithSpacesEachByte(_madBKeyToWrite)); + + try + { + if (readerUnit.connectToReader()) + { + if (readerUnit.waitInsertion(Constants.MAX_WAIT_INSERTION)) + { + if (readerUnit.connect()) + { + ReaderUnitName = readerUnit.getConnectedName(); + + card = readerUnit.getSingleChip(); + + if (!string.IsNullOrWhiteSpace(ByteConverter.GetStringFrom(card.getChipIdentifier().ToArray()))) + { + try + { + GenericChip = new GenericChipModel(ByteConverter.GetStringFrom(card.getChipIdentifier().ToArray()), (CARD_TYPE)Enum.Parse(typeof(CARD_TYPE), card.getCardType())); + } + catch (Exception e) + { + LogWriter.CreateLogEntry(e, FacilityName); + } + } + + MifareLocation mlocation = new MifareLocation + { + aid = (ushort)_madApplicationID, + useMAD = _keyToWriteUseMAD, + sector = _madStartSector + }; + + MifareAccessInfo aiToWrite = new MifareAccessInfo + { + useMAD = _keyToWriteUseMAD, + + }; + + aiToWrite.madKeyA.fromString(_madAKeyToUse == _madAKeyToWrite ? madAKeyToUse.getString(true) : madAKeyToWrite.getString(true)); // only set new madkey if mad key has changed + aiToWrite.madKeyB.fromString(_madBKeyToUse == _madBKeyToWrite ? madBKeyToUse.getString(true) : madBKeyToWrite.getString(true)); // only set new madkey if mad key has changed + aiToWrite.keyA.fromString(_aKeyToUse == _aKeyToWrite ? mAKeyToUse.getString(true) : mAKeyToWrite.getString(true)); + aiToWrite.keyB.fromString(_bKeyToUse == _bKeyToWrite ? mBKeyToUse.getString(true) : mBKeyToWrite.getString(true)); + aiToWrite.madGPB = _madGPB; + + var aiToUse = new MifareAccessInfo + { + useMAD = _useMADToAuth, + keyA = mAKeyToUse, + keyB = mBKeyToUse + }; + + if (_useMADToAuth) + { + aiToUse.madKeyA = madAKeyToUse; + aiToUse.madKeyB = madBKeyToUse; + aiToUse.madGPB = _madGPB; + } + + //TODO: report BUG when using SL1 + var cmd = card.getCommands() as MifareCommands; + var cardService = card.getService(LibLogicalAccess.CardServiceType.CST_STORAGE) as StorageCardService; + + try + { + cardService.writeData(mlocation, aiToUse, aiToWrite, new ByteVector(buffer), CardBehavior.CB_AUTOSWITCHAREA); + } + catch (Exception e) + { + LogWriter.CreateLogEntry(e, FacilityName); + return ERROR.AuthenticationError; + } + return ERROR.NoError; + } + } + } + } + catch (Exception e) + { + LogWriter.CreateLogEntry(e, FacilityName); + return ERROR.AuthenticationError; + } + return ERROR.NoError; + } + + public override ERROR ReadMifareClassicWithMAD(int madApplicationID, string _aKeyToUse, string _bKeyToUse, string _madAKeyToUse, string _madBKeyToUse, int _length, byte _madGPB, bool _useMADToAuth = true, bool _aiToUseIsMAD = false) + { + var settings = new SettingsReaderWriter(); + Sector = new MifareClassicSectorModel(); + + settings.ReadSettings(); + + var mAKeyToUse = new MifareKey(CustomConverter.KeyFormatQuickCheck(_aKeyToUse) ? _aKeyToUse : CustomConverter.FormatMifareClassicKeyWithSpacesEachByte(_aKeyToUse)); + var mBKeyToUse = new MifareKey(CustomConverter.KeyFormatQuickCheck(_bKeyToUse) ? _bKeyToUse : CustomConverter.FormatMifareClassicKeyWithSpacesEachByte(_bKeyToUse)); + + var madAKeyToUse = new MifareKey(CustomConverter.KeyFormatQuickCheck(_madAKeyToUse) ? _madAKeyToUse : CustomConverter.FormatMifareClassicKeyWithSpacesEachByte(_madAKeyToUse)); + var madBKeyToUse = new MifareKey(CustomConverter.KeyFormatQuickCheck(_madBKeyToUse) ? _madBKeyToUse : CustomConverter.FormatMifareClassicKeyWithSpacesEachByte(_madBKeyToUse)); + + try + { + if (readerUnit.connectToReader()) { + if (readerUnit.waitInsertion(Constants.MAX_WAIT_INSERTION)) { + if (readerUnit.connect()) + { + ReaderUnitName = readerUnit.getConnectedName(); + //readerSerialNumber = readerUnit.GetReaderSerialNumber(); + + card = readerUnit.getSingleChip(); + + if (!string.IsNullOrWhiteSpace(ByteConverter.GetStringFrom(card.getChipIdentifier().ToArray()))) + { + try { + GenericChip = new GenericChipModel(ByteConverter.GetStringFrom(card.getChipIdentifier().ToArray()), (CARD_TYPE)Enum.Parse(typeof(CARD_TYPE), card.getCardType())); + } + catch (Exception e) { + LogWriter.CreateLogEntry(e, FacilityName); + } + } + + + MifareLocation mlocation = card.createLocation() as MifareLocation; + mlocation.aid = (ushort)madApplicationID; + mlocation.useMAD = _useMADToAuth; + + var aiToUse = new MifareAccessInfo + { + useMAD = true, + keyA = mAKeyToUse, + keyB = mBKeyToUse, + madKeyA = madAKeyToUse, + madKeyB = madBKeyToUse, + madGPB = _madGPB + }; + + var cmd = card.getCommands() as MifareCommands; + var cardService = card.getService(CardServiceType.CST_STORAGE) as StorageCardService; + + try + { + MifareClassicData = cardService.readData(mlocation, aiToUse, (uint)_length, CardBehavior.CB_AUTOSWITCHAREA).ToArray(); + } + catch (Exception e) + { + LogWriter.CreateLogEntry(e, FacilityName); + return ERROR.AuthenticationError; + } + return ERROR.NoError; + } + } + } + } + catch (Exception e) + { + LogWriter.CreateLogEntry(e, FacilityName); + return ERROR.AuthenticationError; + } + return ERROR.NoError; + } + + #endregion mifare classic + + #region mifare ultralight + + public override ERROR ReadMifareUltralightSinglePage(int _pageNo) + { + try + { + if (readerUnit.connectToReader()) + { + if (readerUnit.waitInsertion(Constants.MAX_WAIT_INSERTION)) + { + if (readerUnit.connect()) + { + ReaderUnitName = readerUnit.getConnectedName(); + //readerSerialNumber = readerUnit.GetReaderSerialNumber(); + RawFormat format = new RawFormat(); + + var chip = readerUnit.getSingleChip() as MifareUltralightChip; + + var service = chip.getService(CardServiceType.CST_STORAGE) as StorageCardService; + + Location location = chip.createLocation() as Location; + + if (chip.getCardType() == "MifareUltralight") + { + var cmd = chip.getCommands() as MifareUltralightCommands;// IMifareUltralightCommands; + MifareUltralightPageData = cmd.readPages(_pageNo, _pageNo).ToArray(); + } + + return ERROR.NoError; + } + } + } + return ERROR.NoError; + } + catch (Exception e) + { + LogWriter.CreateLogEntry(e, FacilityName); + return ERROR.IOError; + } + } + + #endregion mifare ultralight + + #region mifare desfire + + public override ERROR GetMiFareDESFireChipAppIDs(string _appMasterKey, DESFireKeyType _keyTypeAppMasterKey) + { + try + { + // The excepted memory tree + DESFireLocation location = new DESFireLocation(); + // File communication requires encryption + location.securityLevel = (LibLogicalAccess.Card.EncryptionMode)EncryptionMode.CM_ENCRYPT; + + // Keys to use for authentication + DESFireAccessInfo aiToUse = new DESFireAccessInfo(); + aiToUse.masterCardKey.fromString(_appMasterKey); + aiToUse.masterCardKey.setKeyType((LibLogicalAccess.Card.DESFireKeyType)_keyTypeAppMasterKey); + + + if (readerUnit.connectToReader()) + { + if (readerUnit.waitInsertion(Constants.MAX_WAIT_INSERTION)) + { + if (readerUnit.connect()) + { + ReaderUnitName = readerUnit.getConnectedName(); + + card = readerUnit.getSingleChip(); + + //Get AppIDs without Authentication (Free Directory Listing) + try + { + + if (card.getCardType() == "DESFire") + { + var cmd = card.getCommands() as DESFireCommands; + + try + { + cmd.selectApplication((uint)0); + + UIntCollection appIDsObject = cmd.getApplicationIDs(); + AppIDList = appIDsObject.ToArray(); + + return ERROR.NoError; + } + catch + { + //Get AppIDs with Authentication (Directory Listing with PICC MK) + try + { + cmd.selectApplication((uint)0); + cmd.authenticate((byte)0, aiToUse.masterCardKey); + + UIntCollection appIDsObject = cmd.getApplicationIDs(); + AppIDList = appIDsObject.ToArray(); + + return ERROR.NoError; + } + catch (Exception e) + { + if (e.Message != "" && e.Message.Contains("same number already exists")) + { + return ERROR.ItemAlreadyExistError; + } + else if (e.Message != "" && e.Message.Contains("status does not allow the requested command")) + { + return ERROR.AuthenticationError; + } + else + return ERROR.IOError; + } + } + } + + if (card.getCardType() == "DESFireEV1" || + card.getCardType() == "DESFireEV2") + { + + var cmd = (card as DESFireChip).getDESFireCommands(); + + try + { + UIntCollection appIDsObject = cmd.getApplicationIDs(); + AppIDList = appIDsObject.ToArray(); + + var ev1Cmd = (card as DESFireEV1Chip).getDESFireEV1Commands(); + GenericChip.FreeMemory = ev1Cmd.getFreeMem(); + + return ERROR.NoError; + } + catch + { + //Get AppIDs with Authentication (Directory Listing with PICC MK) + try + { + cmd.selectApplication((uint)0); + cmd.authenticate((byte)0, aiToUse.masterCardKey); + + UIntCollection appIDsObject = cmd.getApplicationIDs(); + AppIDList = appIDsObject.ToArray(); + + + var ev1Cmd = (card as DESFireEV1Chip).getDESFireEV1Commands(); + GenericChip.FreeMemory = ev1Cmd.getFreeMem(); + + return ERROR.NoError; + } + catch (Exception e) + { + if (e.Message != "" && e.Message.Contains("same number already exists")) + { + return ERROR.ItemAlreadyExistError; + } + else if (e.Message != "" && e.Message.Contains("status does not allow the requested command")) + { + return ERROR.AuthenticationError; + } + else + return ERROR.IOError; + } + } + } + else + return ERROR.NotReadyError; + } + + catch + { + try + { + if (card.getCardType() == "DESFire") + { + var cmd = card.getCommands() as DESFireCommands; + + cmd.selectApplication((uint)0); + cmd.authenticate((byte)0, aiToUse.masterCardKey); + + UIntCollection appIDsObject = cmd.getApplicationIDs(); + AppIDList = appIDsObject.ToArray(); + + return ERROR.NoError; + } + + if (card.getCardType() == "DESFireEV1" || + card.getCardType() == "DESFireEV2") + { + var cmd = (card as DESFireEV1Chip).getDESFireEV1Commands(); + + } + else + return ERROR.NotReadyError; + } + + catch + { + + } + } + } + } + } + return ERROR.NotReadyError; + } + + catch (Exception e) + { + if (e.Message != "" && e.Message.Contains("same number already exists")) + { + return ERROR.ItemAlreadyExistError; + } + else if (e.Message != "" && e.Message.Contains("status does not allow the requested command")) + { + return ERROR.AuthenticationError; + } + else + return ERROR.IOError; + } + } + + public override ERROR CreateMifareDesfireFile(string _appMasterKey, DESFireKeyType _keyTypeAppMasterKey, FileType_MifareDesfireFileType _fileType, DESFireAccessRights _accessRights, EncryptionMode _encMode, + int _appID, int _fileNo, int _fileSize, + int _minValue = 0, int _maxValue = 1000, int _initValue = 0, bool _isValueLimited = false, + int _maxNbOfRecords = 100) + { + try + { + DESFireAccessRights accessRights = _accessRights; + + // Keys to use for authentication + DESFireAccessInfo aiToUse = new DESFireAccessInfo(); + CustomConverter.FormatMifareDesfireKeyStringWithSpacesEachByte(_appMasterKey); + aiToUse.masterCardKey.fromString(CustomConverter.DesfireKeyToCheck); + aiToUse.masterCardKey.setKeyType((LibLogicalAccess.Card.DESFireKeyType)_keyTypeAppMasterKey); + + if (readerUnit.connectToReader()) + { + if (readerUnit.waitInsertion(Constants.MAX_WAIT_INSERTION)) + { + if (readerUnit.connect()) + { + ReaderUnitName = readerUnit.getConnectedName(); + + card = readerUnit.getSingleChip(); + + if (card.getCardType() == "DESFireEV1" || + card.getCardType() == "DESFireEV2") + { + try + { + var cmd = (card as DESFireChip).getDESFireCommands(); try { - cmd.SelectApplication((uint)0); - cmd.Authenticate((byte)0, aiToUse.MasterCardKey); + cmd.selectApplication((uint)_appID); + cmd.authenticate((byte)0, aiToUse.masterCardKey); } - catch { - cmd.DeleteFile((byte)_fileID); - return ERROR.NoError; - } - - cmd.DeleteFile((byte)_fileID); - return ERROR.NoError; - } - catch (Exception e) - { - if (e.Message != "" && e.Message.Contains("same number already exists")) - { - return ERROR.ItemAlreadyExistError; - } - else if (e.Message != "" && e.Message.Contains("status does not allow the requested command")) - { - return ERROR.AuthenticationError; - } - else - { - return ERROR.IOError; - } - } - } - else - { - return ERROR.NotReadyError; - } - } - } - } - return ERROR.NotReadyError; - } - catch - { - return ERROR.IOError; - } - } + switch (_fileType) + { + case FileType_MifareDesfireFileType.StdDataFile: + cmd.createStdDataFile((byte)_fileNo, (LibLogicalAccess.Card.EncryptionMode)_encMode, + new LibLogicalAccess.Card.DESFireAccessRights() + { + changeAccess = (LibLogicalAccess.Card.TaskAccessRights)accessRights.changeAccess, + readAccess = (LibLogicalAccess.Card.TaskAccessRights)accessRights.readAccess, + writeAccess = (LibLogicalAccess.Card.TaskAccessRights)accessRights.writeAccess, + readAndWriteAccess = (LibLogicalAccess.Card.TaskAccessRights)accessRights.readAndWriteAccess + }, (uint)_fileSize) ; + break; - public override ERROR FormatDesfireCard(string _applicationMasterKey, DESFireKeyType _keyType) - { - try - { - // The excepted memory tree - IDESFireLocation location = new DESFireLocation - { - // The Application ID to use - aid = 0, - // File communication requires encryption - SecurityLevel = (LibLogicalAccess.EncryptionMode)EncryptionMode.CM_ENCRYPT - }; - - // Keys to use for authentication - IDESFireAccessInfo aiToUse = new DESFireAccessInfo(); - CustomConverter.FormatMifareDesfireKeyStringWithSpacesEachByte(_applicationMasterKey); - aiToUse.MasterCardKey.Value = CustomConverter.DesfireKeyToCheck; - aiToUse.MasterCardKey.KeyType = ((LibLogicalAccess.DESFireKeyType)_keyType); - - if (readerUnit.ConnectToReader()) - { - if (readerUnit.WaitInsertion(Constants.MAX_WAIT_INSERTION)) - { - if (readerUnit.Connect()) - { - ReaderUnitName = readerUnit.ConnectedName; + case FileType_MifareDesfireFileType.BackupFile: + cmd.createBackupFile((byte)_fileNo, (LibLogicalAccess.Card.EncryptionMode)_encMode, + new LibLogicalAccess.Card.DESFireAccessRights() + { + changeAccess = (LibLogicalAccess.Card.TaskAccessRights)accessRights.changeAccess, + readAccess = (LibLogicalAccess.Card.TaskAccessRights)accessRights.readAccess, + writeAccess = (LibLogicalAccess.Card.TaskAccessRights)accessRights.writeAccess, + readAndWriteAccess = (LibLogicalAccess.Card.TaskAccessRights)accessRights.readAndWriteAccess + }, (uint)_fileSize); + break; - card = readerUnit.GetSingleChip(); + case FileType_MifareDesfireFileType.ValueFile: + cmd.createValueFile((byte)_fileNo, (LibLogicalAccess.Card.EncryptionMode)_encMode, + new LibLogicalAccess.Card.DESFireAccessRights() + { + changeAccess = (LibLogicalAccess.Card.TaskAccessRights)accessRights.changeAccess, + readAccess = (LibLogicalAccess.Card.TaskAccessRights)accessRights.readAccess, + writeAccess = (LibLogicalAccess.Card.TaskAccessRights)accessRights.writeAccess, + readAndWriteAccess = (LibLogicalAccess.Card.TaskAccessRights)accessRights.readAndWriteAccess + }, _minValue, _maxValue, _initValue, _isValueLimited); + break; - if (card.Type == "DESFire" || - card.Type == "DESFireEV1" || - card.Type == "DESFireEV2") - { - var cmd = card.Commands as IDESFireCommands; - try - { - cmd.SelectApplication(0); - cmd.Authenticate(0, aiToUse.MasterCardKey); + case FileType_MifareDesfireFileType.CyclicRecordFile: + cmd.createCyclicRecordFile((byte)_fileNo, (LibLogicalAccess.Card.EncryptionMode)_encMode, + new LibLogicalAccess.Card.DESFireAccessRights() + { + changeAccess = (LibLogicalAccess.Card.TaskAccessRights)accessRights.changeAccess, + readAccess = (LibLogicalAccess.Card.TaskAccessRights)accessRights.readAccess, + writeAccess = (LibLogicalAccess.Card.TaskAccessRights)accessRights.writeAccess, + readAndWriteAccess = (LibLogicalAccess.Card.TaskAccessRights)accessRights.readAndWriteAccess + }, (uint)_fileSize, (uint)_maxNbOfRecords); + break; - cmd.Erase(); + case FileType_MifareDesfireFileType.LinearRecordFile: + cmd.createLinearRecordFile((byte)_fileNo, (LibLogicalAccess.Card.EncryptionMode)_encMode, + new LibLogicalAccess.Card.DESFireAccessRights() + { + changeAccess = (LibLogicalAccess.Card.TaskAccessRights)accessRights.changeAccess, + readAccess = (LibLogicalAccess.Card.TaskAccessRights)accessRights.readAccess, + writeAccess = (LibLogicalAccess.Card.TaskAccessRights)accessRights.writeAccess, + readAndWriteAccess = (LibLogicalAccess.Card.TaskAccessRights)accessRights.readAndWriteAccess + }, (uint)_fileSize, (uint)_maxNbOfRecords); + break; + } - return ERROR.NoError; - } - catch (Exception e) - { - if (e.Message != "" && e.Message.Contains("same number already exists")) - { - return ERROR.ItemAlreadyExistError; - } - else if (e.Message != "" && e.Message.Contains("status does not allow the requested command")) - { - return ERROR.AuthenticationError; - } - else - { - return ERROR.IOError; - } - } - } - else - { - return ERROR.NotReadyError; - } - } - } - } - return ERROR.NotReadyError; - } - catch + return ERROR.NoError; + } + + switch (_fileType) + { + case FileType_MifareDesfireFileType.StdDataFile: + cmd.createStdDataFile((byte)_fileNo, (LibLogicalAccess.Card.EncryptionMode)_encMode, + new LibLogicalAccess.Card.DESFireAccessRights() + { + changeAccess = (LibLogicalAccess.Card.TaskAccessRights)accessRights.changeAccess, + readAccess = (LibLogicalAccess.Card.TaskAccessRights)accessRights.readAccess, + writeAccess = (LibLogicalAccess.Card.TaskAccessRights)accessRights.writeAccess, + readAndWriteAccess = (LibLogicalAccess.Card.TaskAccessRights)accessRights.readAndWriteAccess + }, (uint)_fileSize); + break; + + case FileType_MifareDesfireFileType.BackupFile: + cmd.createBackupFile((byte)_fileNo, (LibLogicalAccess.Card.EncryptionMode)_encMode, + new LibLogicalAccess.Card.DESFireAccessRights() + { + changeAccess = (LibLogicalAccess.Card.TaskAccessRights)accessRights.changeAccess, + readAccess = (LibLogicalAccess.Card.TaskAccessRights)accessRights.readAccess, + writeAccess = (LibLogicalAccess.Card.TaskAccessRights)accessRights.writeAccess, + readAndWriteAccess = (LibLogicalAccess.Card.TaskAccessRights)accessRights.readAndWriteAccess + }, (uint)_fileSize); + break; + + case FileType_MifareDesfireFileType.ValueFile: + cmd.createValueFile((byte)_fileNo, (LibLogicalAccess.Card.EncryptionMode)_encMode, + new LibLogicalAccess.Card.DESFireAccessRights() + { + changeAccess = (LibLogicalAccess.Card.TaskAccessRights)accessRights.changeAccess, + readAccess = (LibLogicalAccess.Card.TaskAccessRights)accessRights.readAccess, + writeAccess = (LibLogicalAccess.Card.TaskAccessRights)accessRights.writeAccess, + readAndWriteAccess = (LibLogicalAccess.Card.TaskAccessRights)accessRights.readAndWriteAccess + }, _minValue, _maxValue, _initValue, _isValueLimited); + break; + + case FileType_MifareDesfireFileType.CyclicRecordFile: + cmd.createCyclicRecordFile((byte)_fileNo, (LibLogicalAccess.Card.EncryptionMode)_encMode, + new LibLogicalAccess.Card.DESFireAccessRights() + { + changeAccess = (LibLogicalAccess.Card.TaskAccessRights)accessRights.changeAccess, + readAccess = (LibLogicalAccess.Card.TaskAccessRights)accessRights.readAccess, + writeAccess = (LibLogicalAccess.Card.TaskAccessRights)accessRights.writeAccess, + readAndWriteAccess = (LibLogicalAccess.Card.TaskAccessRights)accessRights.readAndWriteAccess + }, (uint)_fileSize, (uint)_maxNbOfRecords); + break; + + case FileType_MifareDesfireFileType.LinearRecordFile: + cmd.createLinearRecordFile((byte)_fileNo, (LibLogicalAccess.Card.EncryptionMode)_encMode, + new LibLogicalAccess.Card.DESFireAccessRights() + { + changeAccess = (LibLogicalAccess.Card.TaskAccessRights)accessRights.changeAccess, + readAccess = (LibLogicalAccess.Card.TaskAccessRights)accessRights.readAccess, + writeAccess = (LibLogicalAccess.Card.TaskAccessRights)accessRights.writeAccess, + readAndWriteAccess = (LibLogicalAccess.Card.TaskAccessRights)accessRights.readAndWriteAccess + }, (uint)_fileSize, (uint)_maxNbOfRecords); + break; + } + + return ERROR.NoError; + } + catch (Exception e) + { + if (e.Message != "" && e.Message.Contains("same number already exists")) + { + return ERROR.ItemAlreadyExistError; + } + else if (e.Message != "" && e.Message.Contains("status does not allow the requested command")) + { + return ERROR.AuthenticationError; + } + else if (e.Message != "" && e.Message.Contains("Insufficient NV-Memory")) + { + return ERROR.OutOfMemory; + } + else + return ERROR.IOError; + } + } + else if(card.getCardType() == "DESFire") + { + try + { + var cmd = card.getCommands() as DESFireCommands; + + try + { + cmd.selectApplication((uint)_appID); + cmd.authenticate((byte)0, aiToUse.masterCardKey); + } + catch + { + switch (_fileType) + { + case FileType_MifareDesfireFileType.StdDataFile: + cmd.createStdDataFile((byte)_fileNo, (LibLogicalAccess.Card.EncryptionMode)_encMode, + new LibLogicalAccess.Card.DESFireAccessRights() + { + changeAccess = (LibLogicalAccess.Card.TaskAccessRights)accessRights.changeAccess, + readAccess = (LibLogicalAccess.Card.TaskAccessRights)accessRights.readAccess, + writeAccess = (LibLogicalAccess.Card.TaskAccessRights)accessRights.writeAccess, + readAndWriteAccess = (LibLogicalAccess.Card.TaskAccessRights)accessRights.readAndWriteAccess + }, (uint)_fileSize); + break; + + case FileType_MifareDesfireFileType.BackupFile: + cmd.createBackupFile((byte)_fileNo, (LibLogicalAccess.Card.EncryptionMode)_encMode, + new LibLogicalAccess.Card.DESFireAccessRights() + { + changeAccess = (LibLogicalAccess.Card.TaskAccessRights)accessRights.changeAccess, + readAccess = (LibLogicalAccess.Card.TaskAccessRights)accessRights.readAccess, + writeAccess = (LibLogicalAccess.Card.TaskAccessRights)accessRights.writeAccess, + readAndWriteAccess = (LibLogicalAccess.Card.TaskAccessRights)accessRights.readAndWriteAccess + }, (uint)_fileSize); + break; + + case FileType_MifareDesfireFileType.ValueFile: + cmd.createValueFile((byte)_fileNo, (LibLogicalAccess.Card.EncryptionMode)_encMode, + new LibLogicalAccess.Card.DESFireAccessRights() + { + changeAccess = (LibLogicalAccess.Card.TaskAccessRights)accessRights.changeAccess, + readAccess = (LibLogicalAccess.Card.TaskAccessRights)accessRights.readAccess, + writeAccess = (LibLogicalAccess.Card.TaskAccessRights)accessRights.writeAccess, + readAndWriteAccess = (LibLogicalAccess.Card.TaskAccessRights)accessRights.readAndWriteAccess + }, _minValue, _maxValue, _initValue, _isValueLimited); + break; + + case FileType_MifareDesfireFileType.CyclicRecordFile: + cmd.createCyclicRecordFile((byte)_fileNo, (LibLogicalAccess.Card.EncryptionMode)_encMode, + new LibLogicalAccess.Card.DESFireAccessRights() + { + changeAccess = (LibLogicalAccess.Card.TaskAccessRights)accessRights.changeAccess, + readAccess = (LibLogicalAccess.Card.TaskAccessRights)accessRights.readAccess, + writeAccess = (LibLogicalAccess.Card.TaskAccessRights)accessRights.writeAccess, + readAndWriteAccess = (LibLogicalAccess.Card.TaskAccessRights)accessRights.readAndWriteAccess + },(uint)_fileSize, (uint)_maxNbOfRecords); + break; + + case FileType_MifareDesfireFileType.LinearRecordFile: + cmd.createLinearRecordFile((byte)_fileNo, (LibLogicalAccess.Card.EncryptionMode)_encMode, + new LibLogicalAccess.Card.DESFireAccessRights() + { + changeAccess = (LibLogicalAccess.Card.TaskAccessRights)accessRights.changeAccess, + readAccess = (LibLogicalAccess.Card.TaskAccessRights)accessRights.readAccess, + writeAccess = (LibLogicalAccess.Card.TaskAccessRights)accessRights.writeAccess, + readAndWriteAccess = (LibLogicalAccess.Card.TaskAccessRights)accessRights.readAndWriteAccess + }, (uint)_fileSize, (uint)_maxNbOfRecords); + break; + } + + return ERROR.NoError; + } + + switch (_fileType) + { + case FileType_MifareDesfireFileType.StdDataFile: + cmd.createStdDataFile((byte)_fileNo, (LibLogicalAccess.Card.EncryptionMode)_encMode, + new LibLogicalAccess.Card.DESFireAccessRights() + { + changeAccess = (LibLogicalAccess.Card.TaskAccessRights)accessRights.changeAccess, + readAccess = (LibLogicalAccess.Card.TaskAccessRights)accessRights.readAccess, + writeAccess = (LibLogicalAccess.Card.TaskAccessRights)accessRights.writeAccess, + readAndWriteAccess = (LibLogicalAccess.Card.TaskAccessRights)accessRights.readAndWriteAccess + }, (uint)_fileSize); + break; + + case FileType_MifareDesfireFileType.BackupFile: + cmd.createBackupFile((byte)_fileNo, (LibLogicalAccess.Card.EncryptionMode)_encMode, + new LibLogicalAccess.Card.DESFireAccessRights() + { + changeAccess = (LibLogicalAccess.Card.TaskAccessRights)accessRights.changeAccess, + readAccess = (LibLogicalAccess.Card.TaskAccessRights)accessRights.readAccess, + writeAccess = (LibLogicalAccess.Card.TaskAccessRights)accessRights.writeAccess, + readAndWriteAccess = (LibLogicalAccess.Card.TaskAccessRights)accessRights.readAndWriteAccess + }, (uint)_fileSize); + break; + + case FileType_MifareDesfireFileType.ValueFile: + cmd.createValueFile((byte)_fileNo, (LibLogicalAccess.Card.EncryptionMode)_encMode, + new LibLogicalAccess.Card.DESFireAccessRights() + { + changeAccess = (LibLogicalAccess.Card.TaskAccessRights)accessRights.changeAccess, + readAccess = (LibLogicalAccess.Card.TaskAccessRights)accessRights.readAccess, + writeAccess = (LibLogicalAccess.Card.TaskAccessRights)accessRights.writeAccess, + readAndWriteAccess = (LibLogicalAccess.Card.TaskAccessRights)accessRights.readAndWriteAccess + }, _minValue, _maxValue, _initValue, _isValueLimited); + break; + + case FileType_MifareDesfireFileType.CyclicRecordFile: + cmd.createCyclicRecordFile((byte)_fileNo, (LibLogicalAccess.Card.EncryptionMode)_encMode, + new LibLogicalAccess.Card.DESFireAccessRights() + { + changeAccess = (LibLogicalAccess.Card.TaskAccessRights)accessRights.changeAccess, + readAccess = (LibLogicalAccess.Card.TaskAccessRights)accessRights.readAccess, + writeAccess = (LibLogicalAccess.Card.TaskAccessRights)accessRights.writeAccess, + readAndWriteAccess = (LibLogicalAccess.Card.TaskAccessRights)accessRights.readAndWriteAccess + }, (uint)_fileSize, (uint)_maxNbOfRecords); + break; + + case FileType_MifareDesfireFileType.LinearRecordFile: + cmd.createLinearRecordFile((byte)_fileNo, (LibLogicalAccess.Card.EncryptionMode)_encMode, + new LibLogicalAccess.Card.DESFireAccessRights() + { + changeAccess = (LibLogicalAccess.Card.TaskAccessRights)accessRights.changeAccess, + readAccess = (LibLogicalAccess.Card.TaskAccessRights)accessRights.readAccess, + writeAccess = (LibLogicalAccess.Card.TaskAccessRights)accessRights.writeAccess, + readAndWriteAccess = (LibLogicalAccess.Card.TaskAccessRights)accessRights.readAndWriteAccess + }, (uint)_fileSize, (uint)_maxNbOfRecords); + break; + } + + + return ERROR.NoError; + } + catch (Exception e) + { + if (e.Message != "" && e.Message.Contains("same number already exists")) + { + return ERROR.ItemAlreadyExistError; + } + else if (e.Message != "" && e.Message.Contains("status does not allow the requested command")) + { + return ERROR.AuthenticationError; + } + else if (e.Message != "" && e.Message.Contains("Insufficient NV-Memory")) + { + return ERROR.OutOfMemory; + } + else + return ERROR.IOError; + } + } + else + return ERROR.NotReadyError; + } + } + } + return ERROR.NotReadyError; + } + catch + { + return ERROR.IOError; + } + } + + public override ERROR ReadMiFareDESFireChipFile(string _appMasterKey, DESFireKeyType _keyTypeAppMasterKey, + string _appReadKey, DESFireKeyType _keyTypeAppReadKey, int _readKeyNo, + string _appWriteKey, DESFireKeyType _keyTypeAppWriteKey, int _writeKeyNo, + EncryptionMode _encMode, + int _fileNo, int _appID, int _fileSize) + { + try { - return ERROR.IOError; - } - } + // The excepted memory tree + DESFireLocation location = new DESFireLocation(); + // The Application ID to use + location.aid = (uint)_appID; + // File 0 into this application + location.file = (byte)_fileNo; + // File communication requires encryption + location.securityLevel = (LibLogicalAccess.Card.EncryptionMode)_encMode; + + // Keys to use for authentication + + // Get the card storage service + StorageCardService storage = (StorageCardService)card.getService(CardServiceType.CST_STORAGE); + + // Change keys with the following ones + DESFireAccessInfo aiToWrite = new DESFireAccessInfo(); + CustomConverter.FormatMifareDesfireKeyStringWithSpacesEachByte(_appMasterKey); + aiToWrite.masterApplicationKey.fromString(CustomConverter.DesfireKeyToCheck); + aiToWrite.masterApplicationKey.setKeyType((LibLogicalAccess.Card.DESFireKeyType)_keyTypeAppMasterKey); + + CustomConverter.FormatMifareDesfireKeyStringWithSpacesEachByte(_appReadKey); + aiToWrite.readKey.fromString(CustomConverter.DesfireKeyToCheck); + aiToWrite.readKey.setKeyType((LibLogicalAccess.Card.DESFireKeyType)_keyTypeAppReadKey); + aiToWrite.readKeyno = (byte)_readKeyNo; + + CustomConverter.FormatMifareDesfireKeyStringWithSpacesEachByte(_appWriteKey); + aiToWrite.writeKey.fromString(CustomConverter.DesfireKeyToCheck); + aiToWrite.writeKey.setKeyType((LibLogicalAccess.Card.DESFireKeyType)_keyTypeAppWriteKey); + aiToWrite.writeKeyno = (byte)_writeKeyNo; + + if (readerUnit.connectToReader()) + { + if (readerUnit.waitInsertion(Constants.MAX_WAIT_INSERTION)) + { + if (readerUnit.connect()) + { + if (card.getCardType() == "DESFire" || + card.getCardType() == "DESFireEV1" || + card.getCardType() == "DESFireEV2") + { + try + { + var cmd = card.getCommands() as DESFireCommands; + + try + { + cmd.selectApplication((uint)_appID); + + cmd.authenticate((byte)_readKeyNo, aiToWrite.readKey); + + MifareDESFireData = cmd.readData((byte)_fileNo, 0, (uint)_fileSize, LibLogicalAccess.Card.EncryptionMode.CM_ENCRYPT).ToArray(); + } + catch + { + cmd.selectApplication((uint)_appID); + + MifareDESFireData = cmd.readData((byte)_fileNo, 0, (uint)_fileSize, LibLogicalAccess.Card.EncryptionMode.CM_ENCRYPT).ToArray(); + } + + return ERROR.NoError; + } + + catch (Exception e) + { + if (e.Message != "" && e.Message.Contains("same number already exists")) + { + return ERROR.ItemAlreadyExistError; + } + else if (e.Message != "" && e.Message.Contains("status does not allow the requested command")) + { + return ERROR.AuthenticationError; + } + else + return ERROR.IOError; + } + } + else + return ERROR.NotReadyError; + } + } + } + return ERROR.NotReadyError; + } + + catch + { + return ERROR.IOError; + } + } + + public override ERROR WriteMiFareDESFireChipFile(string _cardMasterKey, DESFireKeyType _keyTypeCardMasterKey, + string _appMasterKey, DESFireKeyType _keyTypeAppMasterKey, + string _appReadKey, DESFireKeyType _keyTypeAppReadKey, int _readKeyNo, + string _appWriteKey, DESFireKeyType _keyTypeAppWriteKey, int _writeKeyNo, + EncryptionMode _encMode, + int _fileNo, int _appID, byte[] _data) + { - public override ERROR GetMifareDesfireFileList(string _applicationMasterKey, DESFireKeyType _keyType, int _keyNumberCurrent, int _appID) - { try { - IDESFireLocation location = new DESFireLocation - { - // The Application ID to use - aid = _appID, - // File communication requires encryption - SecurityLevel = (LibLogicalAccess.EncryptionMode)EncryptionMode.CM_ENCRYPT - }; - - // Keys to use for authentication - IDESFireAccessInfo aiToUse = new DESFireAccessInfo(); - CustomConverter.FormatMifareDesfireKeyStringWithSpacesEachByte(_applicationMasterKey); - aiToUse.MasterCardKey.Value = CustomConverter.DesfireKeyToCheck; - aiToUse.MasterCardKey.KeyType = ((LibLogicalAccess.DESFireKeyType)_keyType); - - object fileIDsObject; - - if (readerUnit.ConnectToReader()) - { - if (readerUnit.WaitInsertion(Constants.MAX_WAIT_INSERTION)) - { - if (readerUnit.Connect()) - { - ReaderUnitName = readerUnit.ConnectedName; - - card = readerUnit.GetSingleChip(); - - if (card.Type == "DESFire" || - card.Type == "DESFireEV1" || - card.Type == "DESFireEV2") - { - var cmd = card.Commands as IDESFireCommands; + // The excepted memory tree + DESFireLocation location = new DESFireLocation(); + // The Application ID to use + location.aid = (uint)_appID; + // File 0 into this application + location.file = (byte)_fileNo; + // File communication requires encryption + location.securityLevel = (LibLogicalAccess.Card.EncryptionMode)_encMode; + + // Keys to use for authentication + + // Get the card storage service + StorageCardService storage = (StorageCardService)card.getService(CardServiceType.CST_STORAGE); + + // Change keys with the following ones + DESFireAccessInfo aiToUse = new DESFireAccessInfo(); + CustomConverter.FormatMifareDesfireKeyStringWithSpacesEachByte(_cardMasterKey); + aiToUse.masterCardKey.fromString(CustomConverter.DesfireKeyToCheck); + aiToUse.masterCardKey.setKeyType((LibLogicalAccess.Card.DESFireKeyType)_keyTypeAppMasterKey); + + DESFireAccessInfo aiToWrite = new DESFireAccessInfo(); + aiToWrite.masterCardKey.fromString(CustomConverter.DesfireKeyToCheck); + aiToWrite.masterCardKey.setKeyType((LibLogicalAccess.Card.DESFireKeyType)_keyTypeAppMasterKey); + + CustomConverter.FormatMifareDesfireKeyStringWithSpacesEachByte(_appMasterKey); + aiToWrite.masterApplicationKey.fromString(CustomConverter.DesfireKeyToCheck); + aiToWrite.masterApplicationKey.setKeyType((LibLogicalAccess.Card.DESFireKeyType)_keyTypeAppMasterKey); + + CustomConverter.FormatMifareDesfireKeyStringWithSpacesEachByte(_appReadKey); + aiToWrite.readKey.fromString(CustomConverter.DesfireKeyToCheck); + aiToWrite.readKey.setKeyType((LibLogicalAccess.Card.DESFireKeyType)_keyTypeAppReadKey); + aiToWrite.readKeyno = (byte)_readKeyNo; + + CustomConverter.FormatMifareDesfireKeyStringWithSpacesEachByte(_appWriteKey); + aiToWrite.writeKey.fromString(CustomConverter.DesfireKeyToCheck); + aiToWrite.writeKey.setKeyType((LibLogicalAccess.Card.DESFireKeyType)_keyTypeAppWriteKey); + aiToWrite.writeKeyno = (byte)_writeKeyNo; + + if (readerUnit.connectToReader()) + { + if (readerUnit.waitInsertion(Constants.MAX_WAIT_INSERTION)) + { + if (readerUnit.connect()) + { + if (card.getCardType() == "DESFire" || + card.getCardType() == "DESFireEV1" || + card.getCardType() == "DESFireEV2") + { + try + { + var cmd = card.getCommands() as DESFireCommands; + + cmd.selectApplication((uint)_appID); + + cmd.authenticate((byte)_writeKeyNo, aiToWrite.writeKey); + + cmd.writeData((byte)_fileNo, 0, new ByteVector(_data), LibLogicalAccess.Card.EncryptionMode.CM_ENCRYPT); + + return ERROR.NoError; + } + + catch (Exception e) + { + if (e.Message != "" && e.Message.Contains("same number already exists")) + { + return ERROR.ItemAlreadyExistError; + } + else if (e.Message != "" && e.Message.Contains("status does not allow the requested command")) + { + return ERROR.AuthenticationError; + } + else + return ERROR.IOError; + } + } + else + return ERROR.NotReadyError; + } + } + } + return ERROR.NotReadyError; + } + + catch + { + return ERROR.IOError; + } + } + + public override ERROR AuthToMifareDesfireApplication(string _applicationMasterKey, DESFireKeyType _keyType, int _keyNumber, int _appID = 0) + { + try + { + // The excepted memory tree + DESFireLocation location = new DESFireLocation(); + // The Application ID to use + location.aid = (uint)_appID; + // File communication requires encryption + //location.securityLevel = EncryptionMode.CM_ENCRYPT; + + // Keys to use for authentication + DESFireAccessInfo aiToUse = new DESFireAccessInfo(); + CustomConverter.FormatMifareDesfireKeyStringWithSpacesEachByte(_applicationMasterKey); + aiToUse.masterCardKey.fromString(CustomConverter.DesfireKeyToCheck); + aiToUse.masterCardKey.setKeyType((LibLogicalAccess.Card.DESFireKeyType)_keyType); + + if (readerUnit.connectToReader()) + { + if (readerUnit.waitInsertion(Constants.MAX_WAIT_INSERTION)) + { + if (readerUnit.connect()) + { + ReaderUnitName = readerUnit.getConnectedName(); + + card = readerUnit.getSingleChip(); + + if (card.getCardType() == "DESFire" || + card.getCardType() == "DESFireEV1" || + card.getCardType() == "DESFireEV2") + { + var cmd = card.getCommands() as DESFireCommands; + try + { + cmd.selectApplication((uint)_appID); + if (_appID > 0) + cmd.authenticate((byte)_keyNumber, aiToUse.masterCardKey); + else + cmd.authenticate((byte)0, aiToUse.masterCardKey); + return ERROR.NoError; + } + + catch (Exception e) + { + if (e.Message != "" && e.Message.Contains("same number already exists")) + { + return ERROR.ItemAlreadyExistError; + } + else if (e.Message != "" && e.Message.Contains("status does not allow the requested command")) + { + return ERROR.AuthenticationError; + } + else + return ERROR.IOError; + } + } + + else + return ERROR.NotReadyError; + } + } + } + return ERROR.NotReadyError; + } + catch + { + return ERROR.IOError; + } + } + + public override ERROR GetMifareDesfireAppSettings(string _applicationMasterKey, DESFireKeyType _keyType, int _keyNumberCurrent = 0, int _appID = 0) + { + byte maxNbrOfKeys; + LibLogicalAccess.Card.DESFireKeySettings keySettings; + + try + { + // Keys to use for authentication + DESFireAccessInfo aiToUse = new DESFireAccessInfo(); + CustomConverter.FormatMifareDesfireKeyStringWithSpacesEachByte(_applicationMasterKey); + aiToUse.masterCardKey.fromString(CustomConverter.DesfireKeyToCheck); + aiToUse.masterCardKey.setKeyType((LibLogicalAccess.Card.DESFireKeyType)_keyType); + + if (readerUnit.connectToReader()) + { + if (readerUnit.waitInsertion(Constants.MAX_WAIT_INSERTION)) + { + if (readerUnit.connect()) + { + ReaderUnitName = readerUnit.getConnectedName(); + card = readerUnit.getSingleChip(); + + if (card.getCardType() == "DESFire") + { + var cmd = card.getCommands() as DESFireCommands; + ReaderUnitName = readerUnit.getConnectedName(); + try - { - cmd.SelectApplication((uint)_appID); - try - { - cmd.Authenticate((byte)_keyNumberCurrent, aiToUse.MasterCardKey); - } - catch - { - try - { - fileIDsObject = cmd.GetFileIDs(); - FileIDList = (fileIDsObject as byte[]); - return ERROR.NoError; - } - catch (Exception e) - { - if (e.Message != "" && e.Message.Contains("same number already exists")) - { - return ERROR.ItemAlreadyExistError; - } - else if (e.Message != "" && e.Message.Contains("status does not allow the requested command")) - { - return ERROR.AuthenticationError; - } - else - { - return ERROR.IOError; - } - } - } - - fileIDsObject = cmd.GetFileIDs(); - FileIDList = (fileIDsObject as byte[]); + { + cmd.selectApplication((uint)_appID); + GenericChip = new GenericChipModel(ByteConverter.GetStringFrom(card.getChipIdentifier().ToArray()), (CARD_TYPE)Enum.Parse(typeof(CARD_TYPE), card.getCardType())); - return ERROR.NoError; - } - catch (Exception e) - { - if (e.Message != "" && e.Message.Contains("same number already exists")) - { - return ERROR.ItemAlreadyExistError; - } - else if (e.Message != "" && e.Message.Contains("status does not allow the requested command")) - { - return ERROR.AuthenticationError; - } - else - { - return ERROR.IOError; - } - } - } - else + try + { + cmd.authenticate((byte)_keyNumberCurrent, aiToUse.masterCardKey); + } + + catch + { + try + { + cmd.getKeySettings(out keySettings, out maxNbrOfKeys); + MaxNumberOfAppKeys = (byte)(maxNbrOfKeys & 0x0F); + EncryptionType = (byte)(maxNbrOfKeys & 0xF0); + DesfireAppKeySetting = (DESFireKeySettings)keySettings; + + return ERROR.NoError; + } + catch (Exception e) + { + if (e.Message != "" && e.Message.Contains("same number already exists")) + { + return ERROR.ItemAlreadyExistError; + } + else if (e.Message != "" && e.Message.Contains("status does not allow the requested command")) + { + return ERROR.AuthenticationError; + } + else + return ERROR.IOError; + } + } + cmd.getKeySettings(out keySettings, out maxNbrOfKeys); + MaxNumberOfAppKeys = (byte)(maxNbrOfKeys & 0x0F); + EncryptionType = (byte)(maxNbrOfKeys & 0xF0); + DesfireAppKeySetting = (DESFireKeySettings)keySettings; + + return ERROR.NoError; + } + catch (Exception e) + { + if (e.Message != "" && e.Message.Contains("same number already exists")) + { + return ERROR.ItemAlreadyExistError; + } + else if (e.Message != "" && e.Message.Contains("status does not allow the requested command")) + { + return ERROR.AuthenticationError; + } + else + return ERROR.IOError; + } + } + + else if (card.getCardType() == "DESFireEV1" || + card.getCardType() == "DESFireEV2" || card.getCardType() == "GENERIC_T_CL_A") + { + var cmd = (card as DESFireChip).getDESFireCommands(); + var ev1Cmd = (card as DESFireEV1Chip).getDESFireEV1Commands(); + + ReaderUnitName = readerUnit.getConnectedName(); + + try + { + cmd.selectApplication((uint)_appID); + GenericChip = new GenericChipModel(ByteConverter.GetStringFrom(card.getChipIdentifier().ToArray()), (CARD_TYPE)Enum.Parse(typeof(CARD_TYPE), card.getCardType())); + + try + { + cmd.authenticate((byte)_keyNumberCurrent, aiToUse.masterCardKey); + } + + catch + { + try + { + try + { + GenericChip.FreeMemory = ev1Cmd.getFreeMem(); + } + + catch { } + + cmd.getKeySettings(out keySettings, out maxNbrOfKeys); + MaxNumberOfAppKeys = (byte)(maxNbrOfKeys & 0x0F); + EncryptionType = (byte)(maxNbrOfKeys & 0xF0); + DesfireAppKeySetting = (DESFireKeySettings)keySettings; + + return ERROR.NoError; + } + catch (Exception e) + { + if (e.Message != "" && e.Message.Contains("same number already exists")) + { + return ERROR.ItemAlreadyExistError; + } + else if (e.Message != "" && e.Message.Contains("status does not allow the requested command")) + { + return ERROR.NotAllowed; + } + else + return ERROR.IOError; + } + } + + try + { + GenericChip.FreeMemory = ev1Cmd.getFreeMem(); + } + + catch { } + + cmd.getKeySettings(out keySettings, out maxNbrOfKeys); + MaxNumberOfAppKeys = (byte)(maxNbrOfKeys & 0x0F); + EncryptionType = (byte)(maxNbrOfKeys & 0xF0); + DesfireAppKeySetting = (DESFireKeySettings)keySettings; + + return ERROR.NoError; + } + catch (Exception e) + { + if (e.Message != "" && e.Message.Contains("same number already exists")) + { + return ERROR.ItemAlreadyExistError; + } + else if (e.Message != "" && e.Message.Contains("status does not allow the requested command")) + { + return ERROR.AuthenticationError; + } + else + return ERROR.IOError; + } + } + + else + return ERROR.NotReadyError; + } + } + } + return ERROR.NotReadyError; + } + catch + { + return ERROR.IOError; + } + } + + public override ERROR CreateMifareDesfireApplication( + string _piccMasterKey, DESFireKeySettings _keySettingsTarget, DESFireKeyType _keyTypePiccMasterKey, + DESFireKeyType _keyTypeTargetApplication, int _maxNbKeys, int _appID, bool authenticateToPICCFirst = true) + { + try + { + // The excepted memory tree + DESFireLocation location = new DESFireLocation(); + // The Application ID to use + location.aid = (uint)_appID; + + // File communication requires encryption + location.securityLevel = LibLogicalAccess.Card.EncryptionMode.CM_ENCRYPT; + + // IDESFireEV1Commands cmd; + // Keys to use for authentication + DESFireAccessInfo aiToUse = new DESFireAccessInfo(); + CustomConverter.FormatMifareDesfireKeyStringWithSpacesEachByte(_piccMasterKey); + aiToUse.masterCardKey.fromString(CustomConverter.DesfireKeyToCheck); + aiToUse.masterCardKey.setKeyType((LibLogicalAccess.Card.DESFireKeyType)_keyTypePiccMasterKey); + + if (readerUnit.connectToReader()) + { + if (readerUnit.waitInsertion(Constants.MAX_WAIT_INSERTION)) + { + if (readerUnit.connect()) + { + ReaderUnitName = readerUnit.getConnectedName(); + + card = readerUnit.getSingleChip(); + + if (card.getCardType() == "DESFire") + { + var cmd = card.getCommands() as DESFireCommands; + try + { + cmd.selectApplication(0); + + if(authenticateToPICCFirst) + cmd.authenticate((byte)0, aiToUse.masterCardKey); + + cmd.createApplication((uint)_appID, (LibLogicalAccess.Card.DESFireKeySettings)_keySettingsTarget, (byte)_maxNbKeys); + + return ERROR.NoError; + } + catch (Exception e) + { + + if (e.Message != "" && e.Message.Contains("same number already exists")) + { + return ERROR.ItemAlreadyExistError; + } + else if (e.Message != "" && e.Message.Contains("status does not allow the requested command")) + { + return ERROR.AuthenticationError; + } + else + return ERROR.IOError; + } + } + + else if(card.getCardType() == "DESFireEV1" || + card.getCardType() == "DESFireEV2") { - return ERROR.NotReadyError; - } - } - } - } - return ERROR.NotReadyError; - } - catch - { - return ERROR.IOError; - } - } - - public override ERROR GetMifareDesfireFileSettings(string _applicationMasterKey, DESFireKeyType _keyType, int _keyNumberCurrent, int _appID, int _fileNo) - { - try - { - // Keys to use for authentication - IDESFireAccessInfo aiToUse = new DESFireAccessInfo(); - CustomConverter.FormatMifareDesfireKeyStringWithSpacesEachByte(_applicationMasterKey); - aiToUse.MasterCardKey.Value = CustomConverter.DesfireKeyToCheck; - aiToUse.MasterCardKey.KeyType = (LibLogicalAccess.DESFireKeyType)_keyType; + var cmd = card.getCommands() as DESFireCommands; + var ev1Cmd = (card as DESFireEV1Chip).getDESFireEV1Commands(); + try + { + cmd.selectApplication(0); + + if (authenticateToPICCFirst) + cmd.authenticate((byte)0, aiToUse.masterCardKey); + + ev1Cmd.createApplication((uint)_appID, (LibLogicalAccess.Card.DESFireKeySettings)_keySettingsTarget, (byte)_maxNbKeys, (LibLogicalAccess.Card.DESFireKeyType)_keyTypeTargetApplication); + + return ERROR.NoError; + } + catch (Exception e) + { + if (e.Message != "" && e.Message.Contains("same number already exists")) + { + return ERROR.ItemAlreadyExistError; + } + else if (e.Message != "" && e.Message.Contains("status does not allow the requested command")) + { + return ERROR.AuthenticationError; + } + else if (e.Message != "" && e.Message.Contains("Insufficient NV-Memory")) + { + return ERROR.OutOfMemory; + } + else + return ERROR.IOError; + } + } + else + return ERROR.NotReadyError; + } + } + } + return ERROR.NotReadyError; + } + catch + { + return ERROR.IOError; + } + } - if (readerUnit.ConnectToReader()) - { - if (readerUnit.WaitInsertion(Constants.MAX_WAIT_INSERTION)) - { - if (readerUnit.Connect()) - { - ReaderUnitName = readerUnit.ConnectedName; - card = readerUnit.GetSingleChip(); + public override ERROR ChangeMifareDesfireApplicationKey( + string _applicationMasterKeyCurrent, int _keyNumberCurrent, DESFireKeyType _keyTypeCurrent, + string _applicationMasterKeyTarget, int _keyNumberTarget, int selectedDesfireAppKeyVersionTargetAsIntint, + DESFireKeyType _keyTypeTarget, int _appIDCurrent, int _appIDTarget, DESFireKeySettings keySettings, int _) + { + try + { + DESFireKey masterApplicationKey = new DESFireKey(); + masterApplicationKey.setKeyType((LibLogicalAccess.Card.DESFireKeyType)_keyTypeCurrent); + CustomConverter.FormatMifareDesfireKeyStringWithSpacesEachByte(_applicationMasterKeyCurrent); + masterApplicationKey.fromString(CustomConverter.DesfireKeyToCheck); + + DESFireKey applicationMasterKeyTarget = new DESFireKey(); + applicationMasterKeyTarget.setKeyType((LibLogicalAccess.Card.DESFireKeyType)_keyTypeTarget); + CustomConverter.FormatMifareDesfireKeyStringWithSpacesEachByte(_applicationMasterKeyTarget); + applicationMasterKeyTarget.fromString(CustomConverter.DesfireKeyToCheck); + //applicationMasterKeyTarget.setKeyVersion((byte)selectedDesfireAppKeyVersionTargetAsIntint); + + readerUnit.disconnectFromReader(); + + if (readerUnit.connectToReader()) + { + if (readerUnit.waitInsertion(Constants.MAX_WAIT_INSERTION)) + { + if (readerUnit.connect()) + { + ReaderUnitName = readerUnit.getConnectedName(); + //readerSerialNumber = readerUnit.GetReaderSerialNumber(); + + card = readerUnit.getSingleChip(); + + if (card.getCardType() == "DESFire" || + card.getCardType() == "DESFireEV1" || + card.getCardType() == "DESFireEV2") + { + var cmd = card.getCommands() as DESFireCommands; + var ev1Cmd = (card as DESFireEV1Chip).getCommands() as DESFireEV1ISO7816Commands; + + //var kv = ev1Cmd?.getKeyVersion((byte)_keyNumberCurrent); + + //if (ev1Cmd != null) + //{ + // masterApplicationKey.setKeyVersion((byte)kv); + //} + + try + { + if (_appIDCurrent == 0) + { + try + { + cmd.selectApplication((uint)_appIDCurrent); + cmd.authenticate((byte)_keyNumberCurrent, masterApplicationKey); + cmd.changeKeySettings((LibLogicalAccess.Card.DESFireKeySettings)keySettings); + cmd.authenticate((byte)_keyNumberCurrent, masterApplicationKey); + cmd.changeKey((byte)_keyNumberCurrent, applicationMasterKeyTarget); + return ERROR.NoError; + } + + catch + { + try + { + cmd.authenticate((byte)_keyNumberCurrent, masterApplicationKey); + cmd.changeKey((byte)_keyNumberCurrent, applicationMasterKeyTarget); + } + catch (Exception e) + { + if (e.Message != "" && e.Message.Contains("same number already exists")) + { + return ERROR.ItemAlreadyExistError; + } + else if (e.Message != "" && e.Message.Contains("status does not allow the requested command")) + { + return ERROR.AuthenticationError; + } + else + { + return ERROR.IOError; + } + } + } + } + else + { + + applicationMasterKeyTarget.setKeyType((LibLogicalAccess.Card.DESFireKeyType)_keyTypeCurrent); + + cmd.selectApplication((uint)_appIDCurrent); + + try + { + cmd.authenticate((byte)_keyNumberCurrent, masterApplicationKey); + cmd.changeKey((byte)_keyNumberTarget, applicationMasterKeyTarget); + cmd.authenticate((byte)_keyNumberCurrent, applicationMasterKeyTarget); + + try + { + cmd.changeKeySettings((LibLogicalAccess.Card.DESFireKeySettings)keySettings); + } + catch { } + } + + catch (Exception ex) + { + try + { + cmd.authenticate((byte)_keyNumberCurrent, masterApplicationKey); + cmd.changeKeySettings((LibLogicalAccess.Card.DESFireKeySettings)keySettings); + cmd.authenticate((byte)_keyNumberCurrent, masterApplicationKey); + cmd.changeKey((byte)_keyNumberTarget, applicationMasterKeyTarget); + return ERROR.NoError; + } + + catch + { + try + { + cmd.authenticate((byte)_keyNumberCurrent, masterApplicationKey); + cmd.changeKey((byte)_keyNumberTarget, applicationMasterKeyTarget); + } + catch (Exception e) + { + if (e.Message != "" && e.Message.Contains("same number already exists")) + { + return ERROR.ItemAlreadyExistError; + } + else if (e.Message != "" && e.Message.Contains("status does not allow the requested command")) + { + return ERROR.AuthenticationError; + } + else + return ERROR.IOError; + } + } + } + } + + return ERROR.NoError; + } + catch (Exception e) + { + if (e.Message != "" && e.Message.Contains("same number already exists")) + { + return ERROR.ItemAlreadyExistError; + } + else if (e.Message != "" && e.Message.Contains("status does not allow the requested command")) + { + return ERROR.AuthenticationError; + } + else + return ERROR.IOError; + } + } + else + return ERROR.NotReadyError; + } + } + } + return ERROR.NotReadyError; + } + catch + { + return ERROR.IOError; + } + } + + public override ERROR DeleteMifareDesfireApplication(string _applicationMasterKey, DESFireKeyType _keyType, int _appID = 0) + { + try + { + // The excepted memory tree + DESFireLocation location = new DESFireLocation(); + // The Application ID to use + location.aid = (uint)_appID; + // File communication requires encryption + location.securityLevel = LibLogicalAccess.Card.EncryptionMode.CM_ENCRYPT; + + // IDESFireEV1Commands cmd; + // Keys to use for authentication + DESFireAccessInfo aiToUse = new DESFireAccessInfo(); + CustomConverter.FormatMifareDesfireKeyStringWithSpacesEachByte(_applicationMasterKey); + aiToUse.masterCardKey.fromString(CustomConverter.DesfireKeyToCheck); + aiToUse.masterCardKey.setKeyType((LibLogicalAccess.Card.DESFireKeyType)_keyType); + + if (readerUnit.connectToReader()) + { + if (readerUnit.waitInsertion(Constants.MAX_WAIT_INSERTION)) + { + if (readerUnit.connect()) + { + ReaderUnitName = readerUnit.getConnectedName(); + //readerSerialNumber = readerUnit.GetReaderSerialNumber(); + + card = readerUnit.getSingleChip(); + + if (card.getCardType() == "DESFire" || + card.getCardType() == "DESFireEV1" || + card.getCardType() == "DESFireEV2") + { + var cmd = card.getCommands() as DESFireCommands; + try + { + cmd.selectApplication(0); + cmd.authenticate((byte)0, aiToUse.masterCardKey); + + cmd.deleteApplication((uint)_appID); + return ERROR.NoError; + } + catch + { + try + { + cmd.selectApplication((uint)_appID); + cmd.authenticate((byte)0, aiToUse.masterCardKey); + cmd.deleteApplication((uint)_appID); + return ERROR.NoError; + } + + catch (Exception e) + { + if (e.Message != "" && e.Message.Contains("same number already exists")) + { + return ERROR.ItemAlreadyExistError; + } + else if (e.Message != "" && e.Message.Contains("status does not allow the requested command")) + { + return ERROR.AuthenticationError; + } + else + return ERROR.IOError; + } + } + } + return ERROR.NotReadyError; + } + } + } + return ERROR.NotReadyError; + } + catch + { + return ERROR.IOError; + } + } + + public override ERROR DeleteMifareDesfireFile(string _applicationMasterKey, DESFireKeyType _keyType, int _appID = 0, int _fileID = 0) + { + try + { + // The excepted memory tree + DESFireLocation location = new DESFireLocation(); + // The Application ID to use + location.aid = (uint)_appID; + // File communication requires encryption + location.securityLevel = LibLogicalAccess.Card.EncryptionMode.CM_ENCRYPT; + + // Keys to use for authentication + DESFireAccessInfo aiToUse = new DESFireAccessInfo(); + CustomConverter.FormatMifareDesfireKeyStringWithSpacesEachByte(_applicationMasterKey); + aiToUse.masterCardKey.fromString(CustomConverter.DesfireKeyToCheck); + aiToUse.masterCardKey.setKeyType((LibLogicalAccess.Card.DESFireKeyType)_keyType); + + if (readerUnit.connectToReader()) + { + if (readerUnit.waitInsertion(Constants.MAX_WAIT_INSERTION)) + { + if (readerUnit.connect()) + { + ReaderUnitName = readerUnit.getConnectedName(); + //readerSerialNumber = readerUnit.GetReaderSerialNumber(); + + card = readerUnit.getSingleChip(); + + if (card.getCardType() == "DESFireEV1" || + card.getCardType() == "DESFireEV2" || + card.getCardType() == "DESFire") + { + try + { + var cmd = card.getCommands() as DESFireCommands; - if (card.Type == "DESFire" || - card.Type == "DESFireEV1" || - card.Type == "DESFireEV2") - { - var cmd = card.Commands as IDESFireCommands; - try - { - cmd.SelectApplication((uint)_appID); try { - cmd.Authenticate((byte)_keyNumberCurrent, aiToUse.MasterCardKey); + cmd.selectApplication((uint)_appID); + cmd.authenticate((byte)0, aiToUse.masterCardKey); } + catch { - try - { - desfireFileSetting = cmd.GetFileSettings((byte)_fileNo); - DesfireFileSettings = new DESFireFileSettings - { - accessRights = desfireFileSetting.accessRights, - comSett = desfireFileSetting.comSett, - FileType = desfireFileSetting.FileType, - dataFile = new DataFileSetting { fileSize = desfireFileSetting.dataFile.fileSize } - }; - - return ERROR.NoError; - } - catch (Exception e) - { - if (e.Message != "" && e.Message.Contains("same number already exists")) - { - return ERROR.ItemAlreadyExistError; - } - else if (e.Message != "" && e.Message.Contains("status does not allow the requested command")) - { - return ERROR.AuthenticationError; - } - else - { - return ERROR.IOError; - } - } + cmd.deleteFile((byte)_fileID); + return ERROR.NoError; } - desfireFileSetting = cmd.GetFileSettings((byte)_fileNo); - DesfireFileSettings = new DESFireFileSettings - { - accessRights = desfireFileSetting.accessRights, - comSett = desfireFileSetting.comSett, - FileType = desfireFileSetting.FileType, - dataFile = new DataFileSetting { fileSize = desfireFileSetting.dataFile.fileSize } - }; - + cmd.deleteFile((byte)_fileID); return ERROR.NoError; - } - catch (Exception e) - { - if (e.Message != "" && e.Message.Contains("same number already exists")) - { - return ERROR.ItemAlreadyExistError; - } - else if (e.Message != "" && e.Message.Contains("status does not allow the requested command")) - { - return ERROR.AuthenticationError; - } - else - { - return ERROR.IOError; - } - } - } - else - { - return ERROR.NotReadyError; - } - } - } - } - return ERROR.NotReadyError; - } - catch - { - return ERROR.IOError; - } - } - - #endregion mifare desfire - - #region mifare plus - - #endregion - - #region ISO15693 - - public ERROR ReadISO15693Chip() - { - try - { - if (readerUnit.ConnectToReader()) - { - if (readerUnit.WaitInsertion(Constants.MAX_WAIT_INSERTION)) - { - if (readerUnit.Connect()) - { - ReaderUnitName = readerUnit.ConnectedName; - - card = readerUnit.GetSingleChip(); - - - if (card.Type == "ISO15693") - { - var cmd = card.Commands as ISO15693Commands; - - object t = cmd.GetSystemInformation(); - - } - - return ERROR.NoError; - } - } - } - return ERROR.NoError; - } - catch (Exception e) - { - LogWriter.CreateLogEntry(string.Format("{0}: {1}; {2}", DateTime.Now, e.Message, e.InnerException != null ? e.InnerException.Message : ""), FacilityName); - return ERROR.IOError; - } - } + } + catch (Exception e) + { + if (e.Message != "" && e.Message.Contains("same number already exists")) + { + return ERROR.ItemAlreadyExistError; + } + else if (e.Message != "" && e.Message.Contains("status does not allow the requested command")) + { + return ERROR.AuthenticationError; + } + else + return ERROR.IOError; + } + } + else + return ERROR.NotReadyError; + } + } + } + return ERROR.NotReadyError; + } + catch + { + return ERROR.IOError; + } + } + + public override ERROR FormatDesfireCard(string _applicationMasterKey, DESFireKeyType _keyType, int _appID = 0) + { + try + { + // The excepted memory tree + DESFireLocation location = new DESFireLocation(); + // The Application ID to use + location.aid = (uint)_appID; + // File communication requires encryption + location.securityLevel = LibLogicalAccess.Card.EncryptionMode.CM_ENCRYPT; + + // Keys to use for authentication + DESFireAccessInfo aiToUse = new DESFireAccessInfo(); + CustomConverter.FormatMifareDesfireKeyStringWithSpacesEachByte(_applicationMasterKey); + aiToUse.masterCardKey.fromString(CustomConverter.DesfireKeyToCheck); + aiToUse.masterCardKey.setKeyType((LibLogicalAccess.Card.DESFireKeyType)_keyType); + + if (readerUnit.connectToReader()) + { + if (readerUnit.waitInsertion(Constants.MAX_WAIT_INSERTION)) + { + if (readerUnit.connect()) + { + ReaderUnitName = readerUnit.getConnectedName(); + //readerSerialNumber = readerUnit.GetReaderSerialNumber(); + + card = readerUnit.getSingleChip(); + + if(card.getCardType() == "DESFire" || + card.getCardType() == "DESFireEV1" || + card.getCardType() == "DESFireEV2") + { + var cmd = card.getCommands() as DESFireCommands; + try + { + cmd.selectApplication(0); + cmd.authenticate((byte)0, aiToUse.masterCardKey); + + cmd.erase(); + //cmd.commitTransaction(); + return ERROR.NoError; + } + catch (Exception e) + { + if (e.Message != "" && e.Message.Contains("same number already exists")) + { + return ERROR.ItemAlreadyExistError; + } + else if (e.Message != "" && e.Message.Contains("status does not allow the requested command")) + { + return ERROR.AuthenticationError; + } + else + return ERROR.IOError; + } + } + else + return ERROR.NotReadyError; + } + } + } + return ERROR.NotReadyError; + } + catch + { + return ERROR.IOError; + } + } + + public override ERROR GetMifareDesfireFileList(string _applicationMasterKey, DESFireKeyType _keyType, int _keyNumberCurrent = 0, int _appID = 0) + { + try + { + // The excepted memory tree + DESFireLocation location = new DESFireLocation(); + // The Application ID to use + location.aid = (uint)_appID; + // File communication requires encryption + location.securityLevel = LibLogicalAccess.Card.EncryptionMode.CM_ENCRYPT; + + //IDESFireEV1Commands cmd; + // Keys to use for authentication + DESFireAccessInfo aiToUse = new DESFireAccessInfo(); + CustomConverter.FormatMifareDesfireKeyStringWithSpacesEachByte(_applicationMasterKey); + aiToUse.masterCardKey.fromString(CustomConverter.DesfireKeyToCheck); + aiToUse.masterCardKey.setKeyType((LibLogicalAccess.Card.DESFireKeyType)_keyType); + + ByteVector fileIDsObject; + + if (readerUnit.connectToReader()) + { + if (readerUnit.waitInsertion(Constants.MAX_WAIT_INSERTION)) + { + if (readerUnit.connect()) + { + ReaderUnitName = readerUnit.getConnectedName(); + //readerSerialNumber = readerUnit.GetReaderSerialNumber(); + + card = readerUnit.getSingleChip(); + + if(card.getCardType() == "DESFire" || + card.getCardType() == "DESFireEV1" || + card.getCardType() == "DESFireEV2") + { + var cmd = card.getCommands() as DESFireCommands; + try + { + cmd.selectApplication((uint)_appID); + try + { + cmd.authenticate((byte)_keyNumberCurrent, aiToUse.masterCardKey); + } + catch + { + try + { + fileIDsObject = cmd.getFileIDs(); + FileIDList = fileIDsObject.ToArray(); + return ERROR.NoError; + } + catch (Exception e) + { + if (e.Message != "" && e.Message.Contains("same number already exists")) + { + return ERROR.ItemAlreadyExistError; + } + else if (e.Message != "" && e.Message.Contains("status does not allow the requested command")) + { + return ERROR.AuthenticationError; + } + else + return ERROR.IOError; + } + } + + fileIDsObject = cmd.getFileIDs(); + FileIDList = fileIDsObject.ToArray(); + + return ERROR.NoError; + } + catch (Exception e) + { + if (e.Message != "" && e.Message.Contains("same number already exists")) + { + return ERROR.ItemAlreadyExistError; + } + else if (e.Message != "" && e.Message.Contains("status does not allow the requested command")) + { + return ERROR.AuthenticationError; + } + else + return ERROR.IOError; + } + } + else + return ERROR.NotReadyError; + } + } + } + return ERROR.NotReadyError; + } + catch + { + return ERROR.IOError; + } + } + + public override ERROR GetMifareDesfireFileSettings(string _applicationMasterKey, DESFireKeyType _keyType, int _keyNumberCurrent = 0, int _appID = 0, int _fileNo = 0) + { + try + { + // IDESFireEV1Commands cmd; + // Keys to use for authentication + DESFireAccessInfo aiToUse = new DESFireAccessInfo(); + CustomConverter.FormatMifareDesfireKeyStringWithSpacesEachByte(_applicationMasterKey); + aiToUse.masterCardKey.fromString(CustomConverter.DesfireKeyToCheck); + aiToUse.masterCardKey.setKeyType((LibLogicalAccess.Card.DESFireKeyType)_keyType); + + if (readerUnit.connectToReader()) + { + if (readerUnit.waitInsertion(Constants.MAX_WAIT_INSERTION)) + { + if (readerUnit.connect()) + { + ReaderUnitName = readerUnit.getConnectedName(); + card = readerUnit.getSingleChip(); + + if (card.getCardType() == "DESFire" || + card.getCardType() == "DESFireEV1" || + card.getCardType() == "DESFireEV2") + { + var cmd = card.getCommands() as DESFireCommands; + try + { + cmd.selectApplication((uint)_appID); + try + { + cmd.authenticate((byte)_keyNumberCurrent, aiToUse.masterCardKey); + } + catch + { + try + { + /* + var fs = cmd.getFileSettings((byte)_fileNo); + DesfireFileSettings = new DESFireFileSettings({ + accessRights = fs.accessRights, + comSett = fs.comSett, + //dataFile = fs.getDataFile(), + FileType = fs.fileType + }); + */ + return ERROR.NoError; + } + catch (Exception e) + { + if (e.Message != "" && e.Message.Contains("same number already exists")) + { + return ERROR.ItemAlreadyExistError; + } + else if (e.Message != "" && e.Message.Contains("status does not allow the requested command")) + { + return ERROR.AuthenticationError; + } + else + return ERROR.IOError; + } + } + /* + var fs = cmd.getFileSettings((byte)_fileNo); + DesfireFileSettings = new DESFireFileSettings({ + accessRights = fs.accessRights, + comSett = fs.comSett, + //dataFile = fs.getDataFile(), + FileType = fs.fileType + }); + */ + return ERROR.NoError; + } + catch (Exception e) + { + if (e.Message != "" && e.Message.Contains("same number already exists")) + { + return ERROR.ItemAlreadyExistError; + } + else if (e.Message != "" && e.Message.Contains("status does not allow the requested command")) + { + return ERROR.AuthenticationError; + } + else + return ERROR.IOError; + } + } + else + return ERROR.NotReadyError; + } + } + } + return ERROR.NotReadyError; + } + catch + { + return ERROR.IOError; + } + } + + #endregion mifare desfire + + #region mifare plus + + #endregion + + #region ISO15693 + + public ERROR ReadISO15693Chip() + { + try + { + if (readerUnit.connectToReader()) + { + if (readerUnit.waitInsertion(Constants.MAX_WAIT_INSERTION)) + { + if (readerUnit.connect()) + { + ReaderUnitName = readerUnit.getConnectedName(); + //readerSerialNumber = readerUnit.GetReaderSerialNumber(); + + card = readerUnit.getSingleChip(); + + + if (card.getCardType() == "ISO15693") + { + var cmd = card.getCommands() as ISO15693Commands;// IMifareUltralightCommands; + + object t = cmd.getSystemInformation(); + //object res = cmd.ReadPage(4); + + //appIDs = (appIDsObject as UInt32[]); + } + + return ERROR.NoError; + } + } + } + return ERROR.NoError; + } + catch (Exception e) + { + LogWriter.CreateLogEntry(e, FacilityName); + return ERROR.IOError; + } + } #endregion @@ -2390,21 +2473,24 @@ public ERROR ReadEM4135ChipPublic() { try { - if (readerUnit.ConnectToReader()) + if (readerUnit.connectToReader()) { - if (readerUnit.WaitInsertion(Constants.MAX_WAIT_INSERTION)) + if (readerUnit.waitInsertion(Constants.MAX_WAIT_INSERTION)) { - if (readerUnit.Connect()) + if (readerUnit.connect()) { - ReaderUnitName = readerUnit.ConnectedName; + ReaderUnitName = readerUnit.getConnectedName(); + //readerSerialNumber = readerUnit.GetReaderSerialNumber(); - card = readerUnit.GetSingleChip(); + card = readerUnit.getSingleChip(); - if (true) + if (true) //card.getCardType() == "ISO15693" { - var cmd = (card as EM4135Chip).ChipIdentifier; + var cmd = (card as EM4135Chip).getChipIdentifier();// IMifareUltralightCommands; + //object res = cmd.ReadPage(4); + //appIDs = (appIDsObject as UInt32[]); } return ERROR.NoError; @@ -2428,6 +2514,7 @@ protected override void Dispose(bool disposing) { if (disposing) { + } _disposed = true; @@ -2440,5 +2527,6 @@ public override void Dispose() Dispose(true); GC.SuppressFinalize(this); } + private bool _disposed; } } \ No newline at end of file diff --git a/RFiDGear/DataAccessLayer/Remote/FromIO/___LibLogicalAccessProvider.cs b/RFiDGear/DataAccessLayer/Remote/FromIO/___LibLogicalAccessProvider.cs new file mode 100644 index 0000000..46d024c --- /dev/null +++ b/RFiDGear/DataAccessLayer/Remote/FromIO/___LibLogicalAccessProvider.cs @@ -0,0 +1,2444 @@ +using LibLogicalAccess; + +using ByteArrayHelper.Extensions; +using RFiDGear.Model; + +using Log4CSharp; + +using System; +using System.Threading; + +namespace RFiDGear.DataAccessLayer.Remote.FromIO +{ + /// + /// Description of LibLogicalAccessProvider. + /// + /// Initialize Reader + /// + /// + public class LibLogicalAccessProvider : ReaderDevice, IDisposable + { + // global (cross-class) Instances go here -> + private static readonly string FacilityName = "RFiDGear"; + private readonly IReaderProvider readerProvider; + private readonly IReaderUnit readerUnit; + private chip card; + private bool _disposed; + + private FileSetting desfireFileSetting { get; set; } + + #region contructor + public LibLogicalAccessProvider() + { + } + + public LibLogicalAccessProvider(ReaderTypes readerType) + { + try + { + readerProvider = new LibraryManagerClass().GetReaderProvider(Enum.GetName(typeof(ReaderTypes), readerType)); + readerUnit = readerProvider.CreateReaderUnit(); + + GenericChip = new GenericChipModel("", CARD_TYPE.Unspecified); + } + catch (Exception e) + { + LogWriter.CreateLogEntry(e, FacilityName); + } + } + + #endregion contructor + + #region common + + public override ERROR Connect() + { + return initPCSC(); + } + + private ERROR initPCSC() + { + try + { + if (readerUnit.ConnectToReader()) + { + if (readerUnit.WaitInsertion(Constants.MAX_WAIT_INSERTION)) + { + if (readerUnit.Connect()) + { + ReaderUnitName = readerUnit.ConnectedName; + + card = readerUnit.GetSingleChip(); + + return ERROR.NoError; + } + } + } + + return ERROR.IOError; + } + catch (Exception e) + { + LogWriter.CreateLogEntry(e, FacilityName); + + return ERROR.IOError; + } + } + + public override ERROR ReadChipPublic() + { + if (initPCSC() == ERROR.NoError && !string.IsNullOrWhiteSpace(card.ChipIdentifier)) + { + try + { + GenericChip = new GenericChipModel(card.ChipIdentifier, (CARD_TYPE)Enum.Parse(typeof(CARD_TYPE), card.Type)); + + if (Enum.GetName(typeof(CARD_TYPE), GenericChip.CardType).Contains("DESFire")) + { + var cmd = card.Commands as DESFireCommands; + + var version = cmd.GetVersion(); + + switch (version.hardwareMjVersion & 0x0F) // Desfire(Sub)Type by lower Nibble of Major Version + { + case 0: //DESFIRE EV0 + GenericChip.CardType = CARD_TYPE.DESFire; + + switch (version.hardwareStorageSize) + { + case 0x10: + GenericChip.CardType = CARD_TYPE.DESFire_256; // DESFIRE 256B + break; + case 0x16: + GenericChip.CardType = CARD_TYPE.DESFire_2K; // DESFIRE 2K + break; + case 0x18: + GenericChip.CardType = CARD_TYPE.DESFire_4K; // 4K + break; + default: + break; + } // Size ? + break; + + case 1: // DESFIRE EV1 + GenericChip.CardType = CARD_TYPE.DESFireEV1; + + switch (version.hardwareStorageSize) + { + case 0x10: + GenericChip.CardType = CARD_TYPE.DESFireEV1_256; //DESFIRE 256B + break; + case 0x16: + GenericChip.CardType = CARD_TYPE.DESFireEV1_2K; // DESFIRE 2K + break; + case 0x18: + GenericChip.CardType = CARD_TYPE.DESFireEV1_4K; // 4K + break; + case 0x1A: + GenericChip.CardType = CARD_TYPE.DESFireEV1_8K; // 8K + break; + default: + break; + } // Size ? + break; + + case 2: // EV2 + GenericChip.CardType = CARD_TYPE.DESFireEV2; + + switch (version.hardwareStorageSize) + { + case 0x16: + GenericChip.CardType = CARD_TYPE.DESFireEV2_2K; // DESFIRE 2K + break; + case 0x18: + GenericChip.CardType = CARD_TYPE.DESFireEV2_4K; // 4K + break; + case 0x1A: + GenericChip.CardType = CARD_TYPE.DESFireEV2_8K; // 8K + break; + case 0x1C: + GenericChip.CardType = CARD_TYPE.DESFireEV2_16K; // 16K + break; + case 0x1E: + GenericChip.CardType = CARD_TYPE.DESFireEV2_32K; // 32K + break; + default: + break; + } // SIZE ? + break; + + case 3: // EV3 + GenericChip.CardType = CARD_TYPE.DESFireEV3; + + switch (version.hardwareStorageSize) + { + case 0x16: + GenericChip.CardType = CARD_TYPE.DESFireEV3_2K; // DESFIRE 2K + break; + case 0x18: + GenericChip.CardType = CARD_TYPE.DESFireEV3_4K; // 4K + break; + case 0x1A: + GenericChip.CardType = CARD_TYPE.DESFireEV3_8K; // 8K + break; + case 0x1C: + GenericChip.CardType = CARD_TYPE.DESFireEV3_16K; // 16K + break; + case 0x1E: + GenericChip.CardType = CARD_TYPE.DESFireEV3_32K; // 32K + break; + default: + break; + } // SIZE ? + break; + + default: + GenericChip.CardType = CARD_TYPE.Unspecified; + + break; + } + + + } + + DesfireChip = DesfireChip ?? new MifareDesfireChipModel(GenericChip); + + return ERROR.NoError; + } + catch (Exception e) + { + LogWriter.CreateLogEntry(e, FacilityName); + + return ERROR.IOError; + } + } + else + { + return ERROR.NotReadyError; + } + } + + #endregion common + + #region mifare classic + public override ERROR ReadMifareClassicSingleSector(int sectorNumber, string aKey, string bKey) + { + Sector = new MifareClassicSectorModel(); + + var keyA = new MifareKey() { Value = CustomConverter.KeyFormatQuickCheck(aKey) ? aKey : CustomConverter.FormatMifareClassicKeyWithSpacesEachByte(aKey) }; + var keyB = new MifareKey() { Value = CustomConverter.KeyFormatQuickCheck(bKey) ? bKey : CustomConverter.FormatMifareClassicKeyWithSpacesEachByte(bKey) }; + + if (initPCSC() == ERROR.NoError && !string.IsNullOrWhiteSpace(card.ChipIdentifier)) + { + try + { + GenericChip = new GenericChipModel(card.ChipIdentifier, (CARD_TYPE)Enum.Parse(typeof(CARD_TYPE), card.Type)); + + try + { //try to Auth with Keytype A + + var cmd = card.Commands as IMifareCommands; + + for (var k = 0; k < (sectorNumber > 31 ? 16 : 4); k++) // if sector > 31 is 16 blocks each sector i.e. mifare 4k else its 1k or 2k with 4 blocks each sector + { + cmd.LoadKeyNo((byte)0, keyA, MifareKeyType.KT_KEY_A); + + DataBlock = new MifareClassicDataBlockModel( + (byte)CustomConverter.GetChipBasedDataBlockNumber(sectorNumber, k), + k); + + try + { + cmd.AuthenticateKeyNo((byte)CustomConverter.GetChipBasedDataBlockNumber(sectorNumber, k), + (byte)0, + MifareKeyType.KT_KEY_A); + + Sector.IsAuthenticated = true; + + try + { + var data = cmd.ReadBinary( + (byte)CustomConverter.GetChipBasedDataBlockNumber(sectorNumber, k), + 48); + + DataBlock.Data = (byte[])data; + + DataBlock.IsAuthenticated = true; + + Sector.DataBlock.Add(DataBlock); + } + catch + { + DataBlock.IsAuthenticated = false; + Sector.DataBlock.Add(DataBlock); + } + } + catch + { // Try Auth with keytype b + + try + { + cmd.LoadKeyNo((byte)1, keyB, MifareKeyType.KT_KEY_B); + + cmd.AuthenticateKeyNo( + (byte)CustomConverter.GetChipBasedDataBlockNumber(sectorNumber, k), + (byte)1, + MifareKeyType.KT_KEY_B); + + Sector.IsAuthenticated = true; + + try + { + var data = cmd.ReadBinary( + (byte)CustomConverter.GetChipBasedDataBlockNumber(sectorNumber, k), + 48); + + DataBlock.Data = (byte[])data; + + DataBlock.IsAuthenticated = true; + + Sector.DataBlock.Add(DataBlock); + } + catch + { + + DataBlock.IsAuthenticated = false; + + Sector.DataBlock.Add(DataBlock); + + return ERROR.AuthenticationError; + } + } + catch + { + Sector.IsAuthenticated = false; + DataBlock.IsAuthenticated = false; + + Sector.DataBlock.Add(DataBlock); + + return ERROR.AuthenticationError; + } + } + } + + return ERROR.NoError; + } + catch + { + return ERROR.NoError; + } + } + catch (Exception e) + { + LogWriter.CreateLogEntry(e, FacilityName); + } + } + + return ERROR.IOError; + } + + public override ERROR WriteMifareClassicSingleSector(int sectorNumber, string _aKey, string _bKey, byte[] buffer) + { + var keyA = new MifareKey() { Value = CustomConverter.FormatMifareClassicKeyWithSpacesEachByte(_aKey) }; + var keyB = new MifareKey() { Value = CustomConverter.FormatMifareClassicKeyWithSpacesEachByte(_bKey) }; + + var blockCount = 0; + + if (initPCSC() == ERROR.NoError && !string.IsNullOrWhiteSpace(card.ChipIdentifier)) + { + try + { + GenericChip = new GenericChipModel(card.ChipIdentifier, (CARD_TYPE)Enum.Parse(typeof(CARD_TYPE), card.Type)); + + try + { //try to Auth with Keytype A + var cmd = card.Commands as IMifareCommands; + + cmd.LoadKeyNo((byte)0, keyA, MifareKeyType.KT_KEY_A); + cmd.LoadKeyNo((byte)1, keyB, MifareKeyType.KT_KEY_B); + + for (var k = 0; k < blockCount; k++) + { + try + { + cmd.AuthenticateKeyNo( + (byte)CustomConverter.GetChipBasedDataBlockNumber(sectorNumber, k), + (byte)0, + MifareKeyType.KT_KEY_A); + + try + { + cmd.WriteBinary( + (byte)CustomConverter.GetChipBasedDataBlockNumber(sectorNumber, k), + buffer); + } + catch + { + return ERROR.AuthenticationError; + } + } + catch + { // Try Auth with keytype b + + try + { + cmd.AuthenticateKeyNo((byte)CustomConverter.GetChipBasedDataBlockNumber(sectorNumber, k), + (byte)1, + MifareKeyType.KT_KEY_B); + + try + { + cmd.WriteBinary( + (byte)CustomConverter.GetChipBasedDataBlockNumber(sectorNumber, k), + buffer); + } + catch + { + return ERROR.AuthenticationError; + } + } + catch + { + return ERROR.AuthenticationError; + } + } + } + + return ERROR.NoError; + } + catch + { + return ERROR.IOError; + } + } + catch (Exception e) + { + LogWriter.CreateLogEntry(e, FacilityName); + } + } + + return ERROR.IOError; + } + + public override ERROR WriteMifareClassicSingleBlock(int _blockNumber, string _aKey, string _bKey, byte[] buffer) + { + var keyA = new MifareKey() { Value = CustomConverter.FormatMifareClassicKeyWithSpacesEachByte(_aKey) }; + var keyB = new MifareKey() { Value = CustomConverter.FormatMifareClassicKeyWithSpacesEachByte(_bKey) }; + + if (initPCSC() == ERROR.NoError && !string.IsNullOrWhiteSpace(card.ChipIdentifier)) + { + try + { + GenericChip = new GenericChipModel(card.ChipIdentifier, (CARD_TYPE)Enum.Parse(typeof(CARD_TYPE), card.Type)); + + try + { + var cmd = card.Commands as IMifareCommands; + + cmd.LoadKeyNo((byte)0, keyA, MifareKeyType.KT_KEY_A); // FIXME: "sectorNumber" to 0 + + try + { //try to Auth with Keytype A + cmd.AuthenticateKeyNo((byte)(_blockNumber), (byte)0, MifareKeyType.KT_KEY_A); // FIXME: same as '393 + + cmd.WriteBinary((byte)(_blockNumber), buffer); + + } + catch + { // Try Auth with keytype b + + cmd.LoadKeyNo((byte)0, keyB, MifareKeyType.KT_KEY_B); + + try + { + cmd.AuthenticateKeyNo((byte)(_blockNumber), (byte)0, MifareKeyType.KT_KEY_B); // FIXME: same as '393 + + cmd.WriteBinary((byte)(_blockNumber), buffer); + + } + catch + { + return ERROR.AuthenticationError; + } + } + + return ERROR.NoError; + } + catch + { + return ERROR.AuthenticationError; + } + } + catch (Exception e) + { + LogWriter.CreateLogEntry(e, FacilityName); + } + } + + return ERROR.IOError; + } + + public override ERROR WriteMifareClassicWithMAD(int _madApplicationID, int _madStartSector, + string _aKeyToUse, string _bKeyToUse, string _aKeyToWrite, string _bKeyToWrite, + string _madAKeyToUse, string _madBKeyToUse, string _madAKeyToWrite, string _madBKeyToWrite, + byte[] buffer, byte _madGPB, SectorAccessBits _sab, bool _useMADToAuth, bool _keyToWriteUseMAD) + { + Sector = new MifareClassicSectorModel(); + + var mAKeyToUse = new MifareKey() { Value = CustomConverter.KeyFormatQuickCheck(_aKeyToUse) ? _aKeyToUse : CustomConverter.FormatMifareClassicKeyWithSpacesEachByte(_aKeyToUse) }; + var mBKeyToUse = new MifareKey() { Value = CustomConverter.KeyFormatQuickCheck(_bKeyToUse) ? _bKeyToUse : CustomConverter.FormatMifareClassicKeyWithSpacesEachByte(_bKeyToUse) }; + + var mAKeyToWrite = new MifareKey() { Value = CustomConverter.KeyFormatQuickCheck(_aKeyToWrite) ? _aKeyToWrite : CustomConverter.FormatMifareClassicKeyWithSpacesEachByte(_aKeyToWrite) }; + var mBKeyToWrite = new MifareKey() { Value = CustomConverter.KeyFormatQuickCheck(_bKeyToWrite) ? _bKeyToWrite : CustomConverter.FormatMifareClassicKeyWithSpacesEachByte(_bKeyToWrite) }; + + var madAKeyToUse = new MifareKey() { Value = CustomConverter.KeyFormatQuickCheck(_madAKeyToUse) ? _madAKeyToUse : CustomConverter.FormatMifareClassicKeyWithSpacesEachByte(_madAKeyToUse) }; + var madBKeyToUse = new MifareKey() { Value = CustomConverter.KeyFormatQuickCheck(_madBKeyToUse) ? _madBKeyToUse : CustomConverter.FormatMifareClassicKeyWithSpacesEachByte(_madBKeyToUse) }; + + var madAKeyToWrite = new MifareKey() { Value = CustomConverter.KeyFormatQuickCheck(_madAKeyToWrite) ? _madAKeyToWrite : CustomConverter.FormatMifareClassicKeyWithSpacesEachByte(_madAKeyToWrite) }; + var madBKeyToWrite = new MifareKey() { Value = CustomConverter.KeyFormatQuickCheck(_madBKeyToWrite) ? _madBKeyToWrite : CustomConverter.FormatMifareClassicKeyWithSpacesEachByte(_madBKeyToWrite) }; + + if (initPCSC() == ERROR.NoError && !string.IsNullOrWhiteSpace(card.ChipIdentifier)) + { + try + { + GenericChip = new GenericChipModel(card.ChipIdentifier, (CARD_TYPE)Enum.Parse(typeof(CARD_TYPE), card.Type)); + + MifareLocation mlocation = new MifareLocationClass + { + MADApplicationID = (ushort)_madApplicationID, + UseMAD = _keyToWriteUseMAD, + Sector = _madStartSector + }; + + MifareAccessInfo aiToWrite = new MifareAccessInfoClass + { + UseMAD = _keyToWriteUseMAD, + + }; + aiToWrite.MADKeyA.Value = _aKeyToUse == _madAKeyToWrite ? madAKeyToUse.Value : madAKeyToWrite.Value; + aiToWrite.MADKeyB.Value = _bKeyToUse == _madBKeyToWrite ? madBKeyToUse.Value : madBKeyToWrite.Value; + aiToWrite.KeyA.Value = _aKeyToUse == _aKeyToWrite ? mAKeyToUse.Value : mAKeyToWrite.Value; + aiToWrite.KeyB.Value = _bKeyToUse == _bKeyToWrite ? mBKeyToUse.Value : mBKeyToWrite.Value; + aiToWrite.MADGPB = _madGPB; + + var aiToUse = new MifareAccessInfoClass + { + UseMAD = _useMADToAuth, + KeyA = mAKeyToUse, + KeyB = mBKeyToUse + }; + + if (_useMADToAuth) + { + aiToUse.MADKeyA = madAKeyToUse; + aiToUse.MADKeyB = madBKeyToUse; + aiToUse.MADGPB = _madGPB; + } + + try + { + var cardService = card.GetService(CardServiceType.CST_STORAGE) as StorageCardService; + + cardService.WriteData(mlocation, aiToUse, aiToWrite, buffer, buffer.Length, CardBehavior.CB_AUTOSWITCHAREA); + + return ERROR.NoError; + } + catch (Exception e) + { + LogWriter.CreateLogEntry(e, FacilityName); + return ERROR.AuthenticationError; + } + + } + catch (Exception e) + { + LogWriter.CreateLogEntry(e, FacilityName); + } + } + + return ERROR.IOError; + } + + public override ERROR ReadMifareClassicWithMAD(int madApplicationID, + string _aKeyToUse, string _bKeyToUse, string _madAKeyToUse, string _madBKeyToUse, + int _length, byte _madGPB, bool _useMADToAuth, bool _aiToUseIsMAD) + { + Sector = new MifareClassicSectorModel(); + + var mAKeyToUse = new MifareKey() { Value = CustomConverter.KeyFormatQuickCheck(_aKeyToUse) ? _aKeyToUse : CustomConverter.FormatMifareClassicKeyWithSpacesEachByte(_aKeyToUse) }; + var mBKeyToUse = new MifareKey() { Value = CustomConverter.KeyFormatQuickCheck(_bKeyToUse) ? _bKeyToUse : CustomConverter.FormatMifareClassicKeyWithSpacesEachByte(_bKeyToUse) }; + + var madAKeyToUse = new MifareKey() { Value = CustomConverter.KeyFormatQuickCheck(_madAKeyToUse) ? _madAKeyToUse : CustomConverter.FormatMifareClassicKeyWithSpacesEachByte(_madAKeyToUse) }; + var madBKeyToUse = new MifareKey() { Value = CustomConverter.KeyFormatQuickCheck(_madBKeyToUse) ? _madBKeyToUse : CustomConverter.FormatMifareClassicKeyWithSpacesEachByte(_madBKeyToUse) }; + + if (initPCSC() == ERROR.NoError && !string.IsNullOrWhiteSpace(card.ChipIdentifier)) + { + try + { + GenericChip = new GenericChipModel(card.ChipIdentifier, (CARD_TYPE)Enum.Parse(typeof(CARD_TYPE), card.Type)); + + var mlocation = card.CreateLocation() as MifareLocation; + mlocation.MADApplicationID = (ushort)madApplicationID; + mlocation.UseMAD = _useMADToAuth; + + var aiToUse = new MifareAccessInfoClass + { + UseMAD = _aiToUseIsMAD, + KeyA = mAKeyToUse, + KeyB = mBKeyToUse + }; + + if (_useMADToAuth) + { + aiToUse.MADKeyA = madAKeyToUse; + aiToUse.MADKeyB = madBKeyToUse; + aiToUse.MADGPB = _madGPB; + } + + try + { + var cardService = card.GetService(CardServiceType.CST_STORAGE) as StorageCardService; + + MifareClassicData = (byte[])cardService.ReadData(mlocation, aiToUse, _length, CardBehavior.CB_AUTOSWITCHAREA); + + return ERROR.NoError; + + } + catch (Exception e) + { + LogWriter.CreateLogEntry(e, FacilityName); + return ERROR.AuthenticationError; + } + } + catch (Exception e) + { + LogWriter.CreateLogEntry(e, FacilityName); + } + } + + return ERROR.IOError; + } + + #endregion mifare classic + + #region mifare ultralight + + public override ERROR ReadMifareUltralightSinglePage(int _pageNo) + { + try + { + if (readerUnit.ConnectToReader()) + { + if (readerUnit.WaitInsertion(Constants.MAX_WAIT_INSERTION)) + { + if (readerUnit.Connect()) + { + ReaderUnitName = readerUnit.ConnectedName; + + var chip = readerUnit.GetSingleChip() as IMifareUltralightChip; + + if (chip.Type == "MifareUltralight") + { + var cmd = chip.Commands as MifareUltralightCommands; + MifareUltralightPageData = cmd.ReadPages(_pageNo, _pageNo) as byte[]; + } + + return ERROR.NoError; + } + } + } + return ERROR.NoError; + } + catch (Exception e) + { + LogWriter.CreateLogEntry(string.Format("{0}: {1}; {2}", DateTime.Now, e.Message, e.InnerException != null ? e.InnerException.Message : ""), FacilityName); + return ERROR.IOError; + } + } + + #endregion mifare ultralight + + #region mifare desfire + + public override ERROR GetMiFareDESFireChipAppIDs(string _appMasterKey, DESFireKeyType _keyTypeAppMasterKey) + { + try + { + // Keys to use for authentication + IDESFireAccessInfo aiToUse = new DESFireAccessInfo(); + aiToUse.MasterCardKey.Value = _appMasterKey; + aiToUse.MasterCardKey.KeyType = (LibLogicalAccess.DESFireKeyType)_keyTypeAppMasterKey; + + + if (readerUnit.ConnectToReader()) + { + if (readerUnit.WaitInsertion(Constants.MAX_WAIT_INSERTION)) + { + if (readerUnit.Connect()) + { + ReaderUnitName = readerUnit.ConnectedName; + + card = readerUnit.GetSingleChip(); + + //Get AppIDs without Authentication (Free Directory Listing) + try + { + + if (card.Type == "DESFire") + { + var cmd = card.Commands as IDESFireCommands; + + try + { + cmd.SelectApplication((uint)0); + + var appIDsObject = cmd.GetApplicationIDs(); + + if(DesfireChip == null) + { + DesfireChip = new MifareDesfireChipModel(); + } + else + { + DesfireChip.AppList = new System.Collections.Generic.List(); + + foreach (var appid in appIDsObject as UInt32[]) + { + DesfireChip.AppList.Add(new MifareDesfireAppModel(appid)); + } + } + + + return ERROR.NoError; + } + catch + { + //Get AppIDs with Authentication (Directory Listing with PICC MK) + try + { + cmd.SelectApplication((uint)0); + cmd.Authenticate((byte)0, aiToUse.MasterCardKey); + + var appIDsObject = cmd.GetApplicationIDs(); + + if (DesfireChip == null) + { + DesfireChip = new MifareDesfireChipModel(); + } + else + { + DesfireChip.AppList = new System.Collections.Generic.List(); + + foreach (var appid in appIDsObject as UInt32[]) + { + DesfireChip.AppList.Add(new MifareDesfireAppModel(appid)); + } + } + + return ERROR.NoError; + } + catch (Exception e) + { + if (e.Message != "" && e.Message.Contains("same number already exists")) + { + return ERROR.ItemAlreadyExistError; + } + else if (e.Message != "" && e.Message.Contains("status does not allow the requested command")) + { + return ERROR.AuthenticationError; + } + else + { + return ERROR.IOError; + } + } + } + } + + if (card.Type == "DESFireEV1" || + card.Type == "DESFireEV2") + { + + var cmd = card.Commands as IDESFireEV1Commands; + + try + { + DesfireChip.FreeMemory = cmd.GetFreeMemory(); + + var appIDsObject = cmd.GetApplicationIDs(); + + if (DesfireChip == null) + { + DesfireChip = new MifareDesfireChipModel(); + } + else + { + DesfireChip.AppList = new System.Collections.Generic.List(); + + foreach (var appid in appIDsObject as UInt32[]) + { + DesfireChip.AppList.Add(new MifareDesfireAppModel(appid)); + } + } + + return ERROR.NoError; + } + catch + { + //Get AppIDs with Authentication (Directory Listing with PICC MK) + try + { + DesfireChip.FreeMemory = cmd.GetFreeMemory(); + + cmd.SelectApplication((uint)0); + cmd.Authenticate((byte)0, aiToUse.MasterCardKey); + + var appIDsObject = cmd.GetApplicationIDs(); + + if (DesfireChip == null) + { + DesfireChip = new MifareDesfireChipModel(); + } + else + { + DesfireChip.AppList = new System.Collections.Generic.List(); + + foreach (var appid in appIDsObject as UInt32[]) + { + DesfireChip.AppList.Add(new MifareDesfireAppModel(appid)); + } + } + + return ERROR.NoError; + } + catch (Exception e) + { + if (e.Message != "" && e.Message.Contains("same number already exists")) + { + return ERROR.ItemAlreadyExistError; + } + else if (e.Message != "" && e.Message.Contains("status does not allow the requested command")) + { + return ERROR.AuthenticationError; + } + else + { + return ERROR.IOError; + } + } + } + } + else + { + return ERROR.NotReadyError; + } + } + + catch + { + try + { + if (card.Type == "DESFire") + { + var cmd = card.Commands as IDESFireCommands; + + cmd.SelectApplication((uint)0); + cmd.Authenticate((byte)0, aiToUse.MasterCardKey); + + var appIDsObject = cmd.GetApplicationIDs(); + + if (DesfireChip == null) + { + DesfireChip = new MifareDesfireChipModel(); + } + else + { + DesfireChip.AppList = new System.Collections.Generic.List(); + + foreach (var appid in appIDsObject as UInt32[]) + { + DesfireChip.AppList.Add(new MifareDesfireAppModel(appid)); + } + } + + return ERROR.NoError; + } + + if (card.Type == "DESFireEV1" || + card.Type == "DESFireEV2") + { + var cmd = card.Commands as IDESFireEV1Commands; + + } + else + { + return ERROR.NotReadyError; + } + } + + catch + { + + } + } + } + } + } + return ERROR.NotReadyError; + } + + catch (Exception e) + { + if (e.Message != "" && e.Message.Contains("same number already exists")) + { + return ERROR.ItemAlreadyExistError; + } + else if (e.Message != "" && e.Message.Contains("status does not allow the requested command")) + { + return ERROR.AuthenticationError; + } + else + { + return ERROR.IOError; + } + } + } + + public override ERROR CreateMifareDesfireFile(string _appMasterKey, DESFireKeyType _keyTypeAppMasterKey, FileType_MifareDesfireFileType _fileType, DESFireAccessRights _accessRights, EncryptionMode _encMode, + int _appID, int _fileNo, int _fileSize, + int _minValue, int _maxValue, int _initValue, bool _isValueLimited, + int _maxNbOfRecords) + { + try + { + var accessRights = _accessRights; + + // Keys to use for authentication + IDESFireAccessInfo aiToUse = new DESFireAccessInfo(); + CustomConverter.FormatMifareDesfireKeyStringWithSpacesEachByte(_appMasterKey); + aiToUse.MasterCardKey.Value = CustomConverter.DesfireKeyToCheck; + aiToUse.MasterCardKey.KeyType = ((LibLogicalAccess.DESFireKeyType)_keyTypeAppMasterKey); + + if (readerUnit.ConnectToReader()) + { + if (readerUnit.WaitInsertion(Constants.MAX_WAIT_INSERTION)) + { + if (readerUnit.Connect()) + { + ReaderUnitName = readerUnit.ConnectedName; + + card = readerUnit.GetSingleChip(); + + if (card.Type == "DESFire" || + card.Type == "DESFireEV1" || + card.Type == "DESFireEV2") + { + try + { + var cmd = card.Commands as IDESFireEV1Commands; + + try + { + cmd.SelectApplication((uint)_appID); + cmd.Authenticate((byte)0, aiToUse.MasterCardKey); + } + catch + { + switch (_fileType) + { + case FileType_MifareDesfireFileType.StdDataFile: + cmd.CreateStdDataFile((byte)_fileNo, (LibLogicalAccess.EncryptionMode)_encMode, + new LibLogicalAccess.DESFireAccessRights() + { + changeAccess = (LibLogicalAccess.TaskAccessRights)accessRights.changeAccess, + readAccess = (LibLogicalAccess.TaskAccessRights)accessRights.readAccess, + writeAccess = (LibLogicalAccess.TaskAccessRights)accessRights.writeAccess, + readAndWriteAccess = (LibLogicalAccess.TaskAccessRights)accessRights.readAndWriteAccess + }, (uint)_fileSize); + break; + + case FileType_MifareDesfireFileType.BackupFile: + cmd.CreateBackupFile((byte)_fileNo, (LibLogicalAccess.EncryptionMode)_encMode, + new LibLogicalAccess.DESFireAccessRights() + { + changeAccess = (LibLogicalAccess.TaskAccessRights)accessRights.changeAccess, + readAccess = (LibLogicalAccess.TaskAccessRights)accessRights.readAccess, + writeAccess = (LibLogicalAccess.TaskAccessRights)accessRights.writeAccess, + readAndWriteAccess = (LibLogicalAccess.TaskAccessRights)accessRights.readAndWriteAccess + }, (uint)_fileSize); + break; + + case FileType_MifareDesfireFileType.ValueFile: + cmd.CreateValueFile((byte)_fileNo, (LibLogicalAccess.EncryptionMode)_encMode, + new LibLogicalAccess.DESFireAccessRights() + { + changeAccess = (LibLogicalAccess.TaskAccessRights)accessRights.changeAccess, + readAccess = (LibLogicalAccess.TaskAccessRights)accessRights.readAccess, + writeAccess = (LibLogicalAccess.TaskAccessRights)accessRights.writeAccess, + readAndWriteAccess = (LibLogicalAccess.TaskAccessRights)accessRights.readAndWriteAccess + }, (uint)_minValue, (uint)_maxValue, (uint)_initValue, _isValueLimited); + break; + + case FileType_MifareDesfireFileType.CyclicRecordFile: + cmd.CreateCyclicRecordFile((byte)_fileNo, (LibLogicalAccess.EncryptionMode)_encMode, + new LibLogicalAccess.DESFireAccessRights() + { + changeAccess = (LibLogicalAccess.TaskAccessRights)accessRights.changeAccess, + readAccess = (LibLogicalAccess.TaskAccessRights)accessRights.readAccess, + writeAccess = (LibLogicalAccess.TaskAccessRights)accessRights.writeAccess, + readAndWriteAccess = (LibLogicalAccess.TaskAccessRights)accessRights.readAndWriteAccess + }, (uint)_fileSize, (uint)_maxNbOfRecords); + break; + + case FileType_MifareDesfireFileType.LinearRecordFile: + cmd.CreateLinearRecordFile((byte)_fileNo, (LibLogicalAccess.EncryptionMode)_encMode, + new LibLogicalAccess.DESFireAccessRights() + { + changeAccess = (LibLogicalAccess.TaskAccessRights)accessRights.changeAccess, + readAccess = (LibLogicalAccess.TaskAccessRights)accessRights.readAccess, + writeAccess = (LibLogicalAccess.TaskAccessRights)accessRights.writeAccess, + readAndWriteAccess = (LibLogicalAccess.TaskAccessRights)accessRights.readAndWriteAccess + }, (uint)_fileSize, (uint)_maxNbOfRecords); + break; + + default: + break; + } + + return ERROR.NoError; + } + + switch (_fileType) + { + case FileType_MifareDesfireFileType.StdDataFile: + cmd.CreateStdDataFile((byte)_fileNo, (LibLogicalAccess.EncryptionMode)_encMode, + new LibLogicalAccess.DESFireAccessRights() + { + changeAccess = (LibLogicalAccess.TaskAccessRights)accessRights.changeAccess, + readAccess = (LibLogicalAccess.TaskAccessRights)accessRights.readAccess, + writeAccess = (LibLogicalAccess.TaskAccessRights)accessRights.writeAccess, + readAndWriteAccess = (LibLogicalAccess.TaskAccessRights)accessRights.readAndWriteAccess + }, (uint)_fileSize); + break; + + case FileType_MifareDesfireFileType.BackupFile: + cmd.CreateBackupFile((byte)_fileNo, (LibLogicalAccess.EncryptionMode)_encMode, + new LibLogicalAccess.DESFireAccessRights() + { + changeAccess = (LibLogicalAccess.TaskAccessRights)accessRights.changeAccess, + readAccess = (LibLogicalAccess.TaskAccessRights)accessRights.readAccess, + writeAccess = (LibLogicalAccess.TaskAccessRights)accessRights.writeAccess, + readAndWriteAccess = (LibLogicalAccess.TaskAccessRights)accessRights.readAndWriteAccess + }, (uint)_fileSize); + break; + + case FileType_MifareDesfireFileType.ValueFile: + cmd.CreateValueFile((byte)_fileNo, (LibLogicalAccess.EncryptionMode)_encMode, + new LibLogicalAccess.DESFireAccessRights() + { + changeAccess = (LibLogicalAccess.TaskAccessRights)accessRights.changeAccess, + readAccess = (LibLogicalAccess.TaskAccessRights)accessRights.readAccess, + writeAccess = (LibLogicalAccess.TaskAccessRights)accessRights.writeAccess, + readAndWriteAccess = (LibLogicalAccess.TaskAccessRights)accessRights.readAndWriteAccess + }, (uint)_minValue, (uint)_maxValue, (uint)_initValue, _isValueLimited); + break; + + case FileType_MifareDesfireFileType.CyclicRecordFile: + cmd.CreateCyclicRecordFile((byte)_fileNo, (LibLogicalAccess.EncryptionMode)_encMode, + new LibLogicalAccess.DESFireAccessRights() + { + changeAccess = (LibLogicalAccess.TaskAccessRights)accessRights.changeAccess, + readAccess = (LibLogicalAccess.TaskAccessRights)accessRights.readAccess, + writeAccess = (LibLogicalAccess.TaskAccessRights)accessRights.writeAccess, + readAndWriteAccess = (LibLogicalAccess.TaskAccessRights)accessRights.readAndWriteAccess + }, (uint)_fileSize, (uint)_maxNbOfRecords); + break; + + case FileType_MifareDesfireFileType.LinearRecordFile: + cmd.CreateLinearRecordFile((byte)_fileNo, (LibLogicalAccess.EncryptionMode)_encMode, + new LibLogicalAccess.DESFireAccessRights() + { + changeAccess = (LibLogicalAccess.TaskAccessRights)accessRights.changeAccess, + readAccess = (LibLogicalAccess.TaskAccessRights)accessRights.readAccess, + writeAccess = (LibLogicalAccess.TaskAccessRights)accessRights.writeAccess, + readAndWriteAccess = (LibLogicalAccess.TaskAccessRights)accessRights.readAndWriteAccess + }, (uint)_fileSize, (uint)_maxNbOfRecords); + break; + + default: + break; + } + + return ERROR.NoError; + } + catch (Exception e) + { + if (e.Message != "" && e.Message.Contains("same number already exists")) + { + return ERROR.ItemAlreadyExistError; + } + else if (e.Message != "" && e.Message.Contains("status does not allow the requested command")) + { + return ERROR.AuthenticationError; + } + else if (e.Message != "" && e.Message.Contains("Insufficient NV-Memory")) + { + return ERROR.OutOfMemory; + } + else + { + return ERROR.IOError; + } + } + } + else + { + return ERROR.NotReadyError; + } + } + } + } + return ERROR.NotReadyError; + } + catch + { + return ERROR.IOError; + } + } + + public override ERROR ReadMiFareDESFireChipFile(string _appMasterKey, DESFireKeyType _keyTypeAppMasterKey, + string _appReadKey, DESFireKeyType _keyTypeAppReadKey, int _readKeyNo, + string _appWriteKey, DESFireKeyType _keyTypeAppWriteKey, int _writeKeyNo, + EncryptionMode _encMode, + int _fileNo, int _appID, int _fileSize) + { + try + { + // The excepted memory tree + IDESFireLocation location = new DESFireLocation + { + // The Application ID to use + aid = _appID, + // File 0 into this application + File = _fileNo, + // File communication requires encryption + SecurityLevel = (LibLogicalAccess.EncryptionMode)_encMode + }; + + // Keys to use for authentication + + // Get the card storage service + var storage = (IStorageCardService)card.GetService(CardServiceType.CST_STORAGE); + + // Change keys with the following ones + IDESFireAccessInfo aiToWrite = new DESFireAccessInfo(); + CustomConverter.FormatMifareDesfireKeyStringWithSpacesEachByte(_appMasterKey); + aiToWrite.MasterApplicationKey.Value = CustomConverter.DesfireKeyToCheck; + aiToWrite.MasterApplicationKey.KeyType = (LibLogicalAccess.DESFireKeyType)_keyTypeAppMasterKey; + + CustomConverter.FormatMifareDesfireKeyStringWithSpacesEachByte(_appReadKey); + aiToWrite.ReadKey.Value = CustomConverter.DesfireKeyToCheck; + aiToWrite.ReadKey.KeyType = (LibLogicalAccess.DESFireKeyType)_keyTypeAppReadKey; + aiToWrite.ReadKeyNo = (byte)_readKeyNo; + + CustomConverter.FormatMifareDesfireKeyStringWithSpacesEachByte(_appWriteKey); + aiToWrite.WriteKey.Value = CustomConverter.DesfireKeyToCheck; + aiToWrite.WriteKey.KeyType = (LibLogicalAccess.DESFireKeyType)_keyTypeAppWriteKey; + aiToWrite.WriteKeyNo = (byte)_writeKeyNo; + + if (readerUnit.ConnectToReader()) + { + if (readerUnit.WaitInsertion(Constants.MAX_WAIT_INSERTION)) + { + if (readerUnit.Connect()) + { + if (card.Type == "DESFire" || + card.Type == "DESFireEV1" || + card.Type == "DESFireEV2") + { + try + { + var cmd = card.Commands as IDESFireCommands; + + try + { + + cmd.SelectApplication((uint)_appID); + + cmd.Authenticate((byte)_readKeyNo, aiToWrite.ReadKey); + + desfireFileSetting = cmd.GetFileSettings((byte)_fileNo); + DesfireFileSettings = new DESFireFileSettings + { + accessRights = desfireFileSetting.accessRights, + comSett = desfireFileSetting.comSett, + FileType = desfireFileSetting.FileType, + dataFile = new DataFileSetting { fileSize = desfireFileSetting.dataFile.fileSize } + }; + + MifareDESFireData = (byte[])cmd.ReadData((byte)_fileNo, 0, desfireFileSetting.dataFile.fileSize, (LibLogicalAccess.EncryptionMode)EncryptionMode.CM_ENCRYPT); + } + catch + { + cmd.SelectApplication((uint)_appID); + + cmd.Authenticate((byte)_readKeyNo, aiToWrite.ReadKey); + + MifareDESFireData = (byte[])cmd.ReadData((byte)_fileNo, 0, (uint)_fileSize, (LibLogicalAccess.EncryptionMode)EncryptionMode.CM_ENCRYPT); + } + + return ERROR.NoError; + } + + catch (Exception e) + { + if (e.Message != "" && e.Message.Contains("same number already exists")) + { + return ERROR.ItemAlreadyExistError; + } + else if (e.Message != "" && e.Message.Contains("status does not allow the requested command")) + { + return ERROR.AuthenticationError; + } + else + { + return ERROR.IOError; + } + } + } + else + { + return ERROR.NotReadyError; + } + } + } + } + return ERROR.NotReadyError; + } + + catch + { + return ERROR.IOError; + } + } + + public override ERROR WriteMiFareDESFireChipFile(string _cardMasterKey, DESFireKeyType _keyTypeCardMasterKey, + string _appMasterKey, DESFireKeyType _keyTypeAppMasterKey, + string _appReadKey, DESFireKeyType _keyTypeAppReadKey, int _readKeyNo, + string _appWriteKey, DESFireKeyType _keyTypeAppWriteKey, int _writeKeyNo, + EncryptionMode _encMode, + int _fileNo, int _appID, byte[] _data) + { + + try + { + // The excepted memory tree + IDESFireLocation location = new DESFireLocation + { + // The Application ID to use + aid = _appID, + // File 0 into this application + File = _fileNo, + // File communication requires encryption + SecurityLevel = (LibLogicalAccess.EncryptionMode)_encMode + }; + + // Keys to use for authentication + + // Get the card storage service + var storage = (IStorageCardService)card.GetService(CardServiceType.CST_STORAGE); + + // Change keys with the following ones + IDESFireAccessInfo aiToUse = new DESFireAccessInfo(); + CustomConverter.FormatMifareDesfireKeyStringWithSpacesEachByte(_cardMasterKey); + aiToUse.MasterCardKey.Value = CustomConverter.DesfireKeyToCheck; + aiToUse.MasterCardKey.KeyType = (LibLogicalAccess.DESFireKeyType)_keyTypeAppMasterKey; + + IDESFireAccessInfo aiToWrite = new DESFireAccessInfo(); + aiToWrite.MasterCardKey.Value = CustomConverter.DesfireKeyToCheck; + aiToWrite.MasterCardKey.KeyType = (LibLogicalAccess.DESFireKeyType)_keyTypeAppMasterKey; + + CustomConverter.FormatMifareDesfireKeyStringWithSpacesEachByte(_appMasterKey); + aiToWrite.MasterApplicationKey.Value = CustomConverter.DesfireKeyToCheck; + aiToWrite.MasterApplicationKey.KeyType = (LibLogicalAccess.DESFireKeyType)_keyTypeAppMasterKey; + + CustomConverter.FormatMifareDesfireKeyStringWithSpacesEachByte(_appReadKey); + aiToWrite.ReadKey.Value = CustomConverter.DesfireKeyToCheck; + aiToWrite.ReadKey.KeyType = (LibLogicalAccess.DESFireKeyType)_keyTypeAppReadKey; + aiToWrite.ReadKeyNo = (byte)_readKeyNo; + + CustomConverter.FormatMifareDesfireKeyStringWithSpacesEachByte(_appWriteKey); + aiToWrite.WriteKey.Value = CustomConverter.DesfireKeyToCheck; + aiToWrite.WriteKey.KeyType = (LibLogicalAccess.DESFireKeyType)_keyTypeAppWriteKey; + aiToWrite.WriteKeyNo = (byte)_writeKeyNo; + + + if (readerUnit.ConnectToReader()) + { + if (readerUnit.WaitInsertion(Constants.MAX_WAIT_INSERTION)) + { + if (readerUnit.Connect()) + { + if (card.Type == "DESFire" || + card.Type == "DESFireEV1" || + card.Type == "DESFireEV2") + { + try + { + var cmd = card.Commands as IDESFireCommands; + + cmd.SelectApplication((uint)_appID); + + cmd.Authenticate((byte)_writeKeyNo, aiToWrite.WriteKey); + + cmd.WriteData((byte)_fileNo, 0, (uint)_data.Length, (LibLogicalAccess.EncryptionMode)EncryptionMode.CM_ENCRYPT, _data); + + try + { + cmd.CommitTransaction(); + } + + //continue if first try fails + catch { + } + + return ERROR.NoError; + } + + catch (Exception e) + { + if (e.Message != "" && e.Message.Contains("same number already exists")) + { + return ERROR.ItemAlreadyExistError; + } + else if (e.Message != "" && e.Message.Contains("status does not allow the requested command")) + { + return ERROR.AuthenticationError; + } + else + { + return ERROR.IOError; + } + } + } + else + { + return ERROR.NotReadyError; + } + } + } + } + return ERROR.NotReadyError; + } + + catch + { + return ERROR.IOError; + } + } + + public override ERROR AuthToMifareDesfireApplication(string _applicationMasterKey, DESFireKeyType _keyType, int _keyNumber, int _appID) + { + try + { + // The excepted memory tree + IDESFireLocation location = new DESFireLocation + { + // The Application ID to use + aid = _appID, + // File communication requires encryption + SecurityLevel = (LibLogicalAccess.EncryptionMode)EncryptionMode.CM_ENCRYPT + }; + + // Keys to use for authentication + IDESFireAccessInfo aiToUse = new DESFireAccessInfo(); + CustomConverter.FormatMifareDesfireKeyStringWithSpacesEachByte(_applicationMasterKey); + aiToUse.MasterCardKey.Value = CustomConverter.DesfireKeyToCheck; + aiToUse.MasterCardKey.KeyType = ((LibLogicalAccess.DESFireKeyType)_keyType); + + if (readerUnit.ConnectToReader()) + { + if (readerUnit.WaitInsertion(Constants.MAX_WAIT_INSERTION)) + { + if (readerUnit.Connect()) + { + ReaderUnitName = readerUnit.ConnectedName; + + card = readerUnit.GetSingleChip(); + + if (card.Type == "DESFire" || + card.Type == "DESFireEV1" || + card.Type == "DESFireEV2") + { + var cmd = card.Commands as IDESFireCommands; + try + { + cmd.SelectApplication((uint)_appID); + if (_appID > 0) + { + cmd.Authenticate((byte)_keyNumber, aiToUse.MasterCardKey); + } + else + { + cmd.Authenticate((byte)0, aiToUse.MasterCardKey); + } + + return ERROR.NoError; + } + + catch (Exception e) + { + if (e.Message != "" && e.Message.Contains("same number already exists")) + { + return ERROR.ItemAlreadyExistError; + } + else if (e.Message != "" && e.Message.Contains("status does not allow the requested command")) + { + return ERROR.AuthenticationError; + } + else + { + return ERROR.IOError; + } + } + } + + else + { + return ERROR.NotReadyError; + } + } + } + } + return ERROR.NotReadyError; + } + catch + { + return ERROR.IOError; + } + } + + public override ERROR GetMifareDesfireAppSettings(string _applicationMasterKey, DESFireKeyType _keyType, int _keyNumberCurrent, int _appID) + { + byte maxNbrOfKeys; + LibLogicalAccess.DESFireKeySettings keySettings; + LibLogicalAccess.DESFireKeyType keyType; + + try + { + // Keys to use for authentication + IDESFireAccessInfo aiToUse = new DESFireAccessInfo(); + CustomConverter.FormatMifareDesfireKeyStringWithSpacesEachByte(_applicationMasterKey); + aiToUse.MasterCardKey.Value = CustomConverter.DesfireKeyToCheck; + aiToUse.MasterCardKey.KeyType = ((LibLogicalAccess.DESFireKeyType)_keyType); + + if (readerUnit.ConnectToReader()) + { + if (readerUnit.WaitInsertion(Constants.MAX_WAIT_INSERTION)) + { + if (readerUnit.Connect()) + { + ReaderUnitName = readerUnit.ConnectedName; + card = readerUnit.GetSingleChip(); + + if (card.Type == "DESFire") + { + var cmd = card.Commands as IDESFireCommands; + ReaderUnitName = readerUnit.ConnectedName; + + try + { + cmd.SelectApplication((uint)_appID); + GenericChip = new GenericChipModel(card.ChipIdentifier, (CARD_TYPE)Enum.Parse(typeof(CARD_TYPE), card.Type)); + + try + { + cmd.Authenticate((byte)_keyNumberCurrent, aiToUse.MasterCardKey); + } + + catch + { + try + { + cmd.GetKeySettings(out keySettings, out maxNbrOfKeys); + MaxNumberOfAppKeys = (byte)(maxNbrOfKeys & 0x0F); + EncryptionType = (DESFireKeyType)(maxNbrOfKeys & 0xF0); + DesfireAppKeySetting = (DESFireKeySettings)keySettings; + + return ERROR.NoError; + } + catch (Exception e) + { + if (e.Message != "" && e.Message.Contains("same number already exists")) + { + return ERROR.ItemAlreadyExistError; + } + else if (e.Message != "" && e.Message.Contains("status does not allow the requested command")) + { + return ERROR.AuthenticationError; + } + else + { + return ERROR.IOError; + } + } + } + cmd.GetKeySettings(out keySettings, out maxNbrOfKeys); + MaxNumberOfAppKeys = (byte)(maxNbrOfKeys & 0x0F); + EncryptionType = (DESFireKeyType)(maxNbrOfKeys & 0xF0); + DesfireAppKeySetting = (DESFireKeySettings)keySettings; + + return ERROR.NoError; + } + catch (Exception e) + { + if (e.Message != "" && e.Message.Contains("same number already exists")) + { + return ERROR.ItemAlreadyExistError; + } + else if (e.Message != "" && e.Message.Contains("status does not allow the requested command")) + { + return ERROR.AuthenticationError; + } + else + { + return ERROR.IOError; + } + } + } + + else if (card.Type == "DESFireEV1" || + card.Type == "DESFireEV2" || card.Type == "GENERIC_T_CL_A") + { + var cmd = card.Commands as IDESFireEV1Commands; + + ReaderUnitName = readerUnit.ConnectedName; + + try + { + cmd.SelectApplication((uint)_appID); + GenericChip = new GenericChipModel(card.ChipIdentifier, (CARD_TYPE)Enum.Parse(typeof(CARD_TYPE), card.Type)); + + try + { + cmd.Authenticate((byte)_keyNumberCurrent, aiToUse.MasterCardKey); + } + + catch + { + try + { + try + { + DesfireChip.FreeMemory = cmd.GetFreeMemory(); + } + + catch { } + + cmd.GetKeySettingsEV1(out keySettings, out maxNbrOfKeys, out keyType); + MaxNumberOfAppKeys = (byte)(maxNbrOfKeys & 0x0F); + EncryptionType = (DESFireKeyType)keyType; + DesfireAppKeySetting = (DESFireKeySettings)keySettings; + + return ERROR.NoError; + } + catch (Exception e) + { + if (e.Message != "" && e.Message.Contains("same number already exists")) + { + return ERROR.ItemAlreadyExistError; + } + else if (e.Message != "" && e.Message.Contains("status does not allow the requested command")) + { + return ERROR.NotAllowed; + } + else + { + return ERROR.IOError; + } + } + } + + try + { + DesfireChip.FreeMemory = cmd.GetFreeMemory(); + } + + catch { } + + cmd.GetKeySettingsEV1(out keySettings, out maxNbrOfKeys, out keyType); + MaxNumberOfAppKeys = (byte)(maxNbrOfKeys & 0x0F); + EncryptionType = (DESFireKeyType)keyType; + DesfireAppKeySetting = (DESFireKeySettings)keySettings; + + return ERROR.NoError; + } + catch (Exception e) + { + if (e.Message != "" && e.Message.Contains("same number already exists")) + { + return ERROR.ItemAlreadyExistError; + } + else if (e.Message != "" && e.Message.Contains("status does not allow the requested command")) + { + return ERROR.AuthenticationError; + } + else + { + return ERROR.IOError; + } + } + } + + else + { + return ERROR.NotReadyError; + } + } + } + } + return ERROR.NotReadyError; + } + catch + { + return ERROR.IOError; + } + } + + public override ERROR CreateMifareDesfireApplication( + string _piccMasterKey, DESFireKeySettings _keySettingsTarget, DESFireKeyType _keyTypePiccMasterKey, + DESFireKeyType _keyTypeTargetApplication, int _maxNbKeys, int _appID, bool authenticateToPICCFirst) + { + try + { + // The excepted memory tree + IDESFireLocation location = new DESFireLocation + { + // The Application ID to use + aid = _appID, + // File communication requires encryption + SecurityLevel = (LibLogicalAccess.EncryptionMode)EncryptionMode.CM_ENCRYPT + }; + + // Keys to use for authentication + IDESFireAccessInfo aiToUse = new DESFireAccessInfo(); + CustomConverter.FormatMifareDesfireKeyStringWithSpacesEachByte(_piccMasterKey); + aiToUse.MasterCardKey.Value = CustomConverter.DesfireKeyToCheck; + aiToUse.MasterCardKey.KeyType = (LibLogicalAccess.DESFireKeyType)_keyTypePiccMasterKey; + + if (readerUnit.ConnectToReader()) + { + if (readerUnit.WaitInsertion(Constants.MAX_WAIT_INSERTION)) + { + if (readerUnit.Connect()) + { + ReaderUnitName = readerUnit.ConnectedName; + + card = readerUnit.GetSingleChip(); + + if (card.Type == "DESFire") + { + var cmd = card.Commands as IDESFireCommands; + try + { + cmd.SelectApplication(0); + + if (authenticateToPICCFirst) + { + cmd.Authenticate(0, aiToUse.MasterCardKey); + } + + cmd.CreateApplication((uint)_appID, (LibLogicalAccess.DESFireKeySettings)_keySettingsTarget, (byte)_maxNbKeys); + + return ERROR.NoError; + } + catch (Exception e) + { + + if (e.Message != "" && e.Message.Contains("same number already exists")) + { + return ERROR.ItemAlreadyExistError; + } + else if (e.Message != "" && e.Message.Contains("status does not allow the requested command")) + { + return ERROR.AuthenticationError; + } + else + { + return ERROR.IOError; + } + } + } + + else if (card.Type == "DESFireEV1" || + card.Type == "DESFireEV2") + { + var cmd = card.Commands as IDESFireEV1Commands; + + try + { + cmd.SelectApplication(0); + + if (authenticateToPICCFirst) + { + cmd.Authenticate((byte)0, aiToUse.MasterCardKey); + } + + cmd.CreateApplicationEV1((uint)_appID, (LibLogicalAccess.DESFireKeySettings)_keySettingsTarget, (byte)_maxNbKeys, false, (LibLogicalAccess.DESFireKeyType)_keyTypeTargetApplication, 0, 0); + + return ERROR.NoError; + } + catch (Exception e) + { + if (e.Message != "" && e.Message.Contains("same number already exists")) + { + return ERROR.ItemAlreadyExistError; + } + else if (e.Message != "" && e.Message.Contains("status does not allow the requested command")) + { + return ERROR.AuthenticationError; + } + else if (e.Message != "" && e.Message.Contains("Insufficient NV-Memory")) + { + return ERROR.OutOfMemory; + } + else + { + return ERROR.IOError; + } + } + } + else + { + return ERROR.NotReadyError; + } + } + } + } + return ERROR.NotReadyError; + } + catch + { + return ERROR.IOError; + } + } + + public override ERROR ChangeMifareDesfireApplicationKey( + string _applicationMasterKeyCurrent, int _keyNumberCurrent, DESFireKeyType _keyTypeCurrent, + string _applicationMasterKeyTarget, int _keyNumberTarget, int selectedDesfireAppKeyVersionTargetAsIntint, + DESFireKeyType _keyTypeTarget, int _appIDCurrent, int _appIDTarget, DESFireKeySettings keySettings, int keyVersion) + { + try + { + DESFireKey masterApplicationKey = new DESFireKeyClass + { + KeyType = (LibLogicalAccess.DESFireKeyType)_keyTypeCurrent + }; + + CustomConverter.FormatMifareDesfireKeyStringWithSpacesEachByte(_applicationMasterKeyCurrent); + masterApplicationKey.Value = CustomConverter.DesfireKeyToCheck; + masterApplicationKey.KeyVersion = (byte)keyVersion; + + DESFireKey applicationMasterKeyTarget = new DESFireKeyClass + { + KeyType = (LibLogicalAccess.DESFireKeyType)_keyTypeCurrent + }; + CustomConverter.FormatMifareDesfireKeyStringWithSpacesEachByte(_applicationMasterKeyTarget); + applicationMasterKeyTarget.Value = CustomConverter.DesfireKeyToCheck; + + if (readerUnit.ConnectToReader()) + { + if (readerUnit.WaitInsertion(Constants.MAX_WAIT_INSERTION)) + { + if (readerUnit.Connect()) + { + ReaderUnitName = readerUnit.ConnectedName; + + card = readerUnit.GetSingleChip(); + + if (card.Type == "DESFire" || + card.Type == "DESFireEV1" || + card.Type == "DESFireEV2") + { + var cmd = card.Commands as IDESFireCommands; + + try + { + if (_appIDCurrent == 0) + { + try + { + applicationMasterKeyTarget.KeyType = (LibLogicalAccess.DESFireKeyType)_keyTypeTarget; + + cmd.SelectApplication((uint)0); + cmd.Authenticate((byte)0, masterApplicationKey); + cmd.ChangeKeySettings((LibLogicalAccess.DESFireKeySettings)keySettings); + cmd.Authenticate((byte)0, masterApplicationKey); + cmd.ChangeKey((byte)0, applicationMasterKeyTarget); + return ERROR.NoError; + } + + catch + { + try + { + cmd.Authenticate((byte)0, masterApplicationKey); + cmd.ChangeKey((byte)0, applicationMasterKeyTarget); + } + catch (Exception e) + { + if (e.Message != "" && e.Message.Contains("same number already exists")) + { + return ERROR.ItemAlreadyExistError; + } + else if (e.Message != "" && e.Message.Contains("status does not allow the requested command")) + { + return ERROR.AuthenticationError; + } + else + { + return ERROR.IOError; + } + } + } + } + else + { + + applicationMasterKeyTarget.KeyType = ((LibLogicalAccess.DESFireKeyType)_keyTypeCurrent); + + cmd.SelectApplication((uint)_appIDCurrent); + + try + { + cmd.Authenticate((byte)_keyNumberCurrent, masterApplicationKey); + cmd.ChangeKey((byte)_keyNumberTarget, applicationMasterKeyTarget); + cmd.Authenticate((byte)_keyNumberCurrent, applicationMasterKeyTarget); + + try + { + cmd.ChangeKeySettings((LibLogicalAccess.DESFireKeySettings)keySettings); + } + catch { } + } + + catch (Exception ex) + { + try + { + cmd.Authenticate((byte)_keyNumberCurrent, masterApplicationKey); + cmd.ChangeKeySettings((LibLogicalAccess.DESFireKeySettings)keySettings); + cmd.Authenticate((byte)_keyNumberCurrent, masterApplicationKey); + cmd.ChangeKey((byte)_keyNumberTarget, applicationMasterKeyTarget); + return ERROR.NoError; + } + + catch + { + try + { + cmd.Authenticate((byte)_keyNumberCurrent, masterApplicationKey); + cmd.ChangeKey((byte)_keyNumberTarget, applicationMasterKeyTarget); + } + catch (Exception e) + { + if (e.Message != "" && e.Message.Contains("same number already exists")) + { + return ERROR.ItemAlreadyExistError; + } + else if (e.Message != "" && e.Message.Contains("status does not allow the requested command")) + { + return ERROR.AuthenticationError; + } + else + { + return ERROR.IOError; + } + } + } + } + } + + return ERROR.NoError; + } + catch (Exception e) + { + if (e.Message != "" && e.Message.Contains("same number already exists")) + { + return ERROR.ItemAlreadyExistError; + } + else if (e.Message != "" && e.Message.Contains("status does not allow the requested command")) + { + return ERROR.AuthenticationError; + } + else + { + return ERROR.IOError; + } + } + } + else + { + return ERROR.NotReadyError; + } + } + } + } + return ERROR.NotReadyError; + } + catch + { + return ERROR.IOError; + } + } + + public override ERROR DeleteMifareDesfireApplication(string _applicationMasterKey, DESFireKeyType _keyType, int _appID) + { + try + { + // The excepted memory tree + IDESFireLocation location = new DESFireLocation + { + // The Application ID to use + aid = _appID, + // File communication requires encryption + SecurityLevel = (LibLogicalAccess.EncryptionMode)EncryptionMode.CM_ENCRYPT + }; + + // Keys to use for authentication + IDESFireAccessInfo aiToUse = new DESFireAccessInfo(); + CustomConverter.FormatMifareDesfireKeyStringWithSpacesEachByte(_applicationMasterKey); + aiToUse.MasterCardKey.Value = CustomConverter.DesfireKeyToCheck; + aiToUse.MasterCardKey.KeyType = (LibLogicalAccess.DESFireKeyType)_keyType; + + if (readerUnit.ConnectToReader()) + { + if (readerUnit.WaitInsertion(Constants.MAX_WAIT_INSERTION)) + { + if (readerUnit.Connect()) + { + ReaderUnitName = readerUnit.ConnectedName; + + card = readerUnit.GetSingleChip(); + + if (card.Type == "DESFire" || + card.Type == "DESFireEV1" || + card.Type == "DESFireEV2") + { + var cmd = card.Commands as IDESFireCommands; + try + { + cmd.SelectApplication(0); + cmd.Authenticate(0, aiToUse.MasterCardKey); + + cmd.DeleteApplication((uint)_appID); + return ERROR.NoError; + } + catch + { + try + { + cmd.SelectApplication((uint)_appID); + cmd.Authenticate(0, aiToUse.MasterCardKey); + cmd.DeleteApplication((uint)_appID); + return ERROR.NoError; + } + + catch (Exception e) + { + if (e.Message != "" && e.Message.Contains("same number already exists")) + { + return ERROR.ItemAlreadyExistError; + } + else if (e.Message != "" && e.Message.Contains("status does not allow the requested command")) + { + return ERROR.AuthenticationError; + } + else + { + return ERROR.IOError; + } + } + } + } + return ERROR.NotReadyError; + } + } + } + return ERROR.NotReadyError; + } + catch + { + return ERROR.IOError; + } + } + + public override ERROR DeleteMifareDesfireFile(string _applicationMasterKey, DESFireKeyType _keyType, int _appID, int _fileID) + { + try + { + // The excepted memory tree + IDESFireLocation location = new DESFireLocation + { + // The Application ID to use + aid = _appID, + // File communication requires encryption + SecurityLevel = (LibLogicalAccess.EncryptionMode)EncryptionMode.CM_ENCRYPT + }; + + // Keys to use for authentication + IDESFireAccessInfo aiToUse = new DESFireAccessInfo(); + CustomConverter.FormatMifareDesfireKeyStringWithSpacesEachByte(_applicationMasterKey); + aiToUse.MasterCardKey.Value = CustomConverter.DesfireKeyToCheck; + aiToUse.MasterCardKey.KeyType = ((LibLogicalAccess.DESFireKeyType)_keyType); + + if (readerUnit.ConnectToReader()) + { + if (readerUnit.WaitInsertion(Constants.MAX_WAIT_INSERTION)) + { + if (readerUnit.Connect()) + { + ReaderUnitName = readerUnit.ConnectedName; + + card = readerUnit.GetSingleChip(); + + if (card.Type == "DESFireEV1" || + card.Type == "DESFireEV2" || + card.Type == "DESFire") + { + try + { + var cmd = card.Commands as IDESFireCommands; + + try + { + cmd.SelectApplication((uint)0); + cmd.Authenticate((byte)0, aiToUse.MasterCardKey); + } + + catch + { + cmd.DeleteFile((byte)_fileID); + return ERROR.NoError; + } + + cmd.DeleteFile((byte)_fileID); + return ERROR.NoError; + } + catch (Exception e) + { + if (e.Message != "" && e.Message.Contains("same number already exists")) + { + return ERROR.ItemAlreadyExistError; + } + else if (e.Message != "" && e.Message.Contains("status does not allow the requested command")) + { + return ERROR.AuthenticationError; + } + else + { + return ERROR.IOError; + } + } + } + else + { + return ERROR.NotReadyError; + } + } + } + } + return ERROR.NotReadyError; + } + catch + { + return ERROR.IOError; + } + } + + public override ERROR FormatDesfireCard(string _applicationMasterKey, DESFireKeyType _keyType) + { + try + { + // The excepted memory tree + IDESFireLocation location = new DESFireLocation + { + // The Application ID to use + aid = 0, + // File communication requires encryption + SecurityLevel = (LibLogicalAccess.EncryptionMode)EncryptionMode.CM_ENCRYPT + }; + + // Keys to use for authentication + IDESFireAccessInfo aiToUse = new DESFireAccessInfo(); + CustomConverter.FormatMifareDesfireKeyStringWithSpacesEachByte(_applicationMasterKey); + aiToUse.MasterCardKey.Value = CustomConverter.DesfireKeyToCheck; + aiToUse.MasterCardKey.KeyType = ((LibLogicalAccess.DESFireKeyType)_keyType); + + if (readerUnit.ConnectToReader()) + { + if (readerUnit.WaitInsertion(Constants.MAX_WAIT_INSERTION)) + { + if (readerUnit.Connect()) + { + ReaderUnitName = readerUnit.ConnectedName; + + card = readerUnit.GetSingleChip(); + + if (card.Type == "DESFire" || + card.Type == "DESFireEV1" || + card.Type == "DESFireEV2") + { + var cmd = card.Commands as IDESFireCommands; + try + { + cmd.SelectApplication(0); + cmd.Authenticate(0, aiToUse.MasterCardKey); + + cmd.Erase(); + + return ERROR.NoError; + } + catch (Exception e) + { + if (e.Message != "" && e.Message.Contains("same number already exists")) + { + return ERROR.ItemAlreadyExistError; + } + else if (e.Message != "" && e.Message.Contains("status does not allow the requested command")) + { + return ERROR.AuthenticationError; + } + else + { + return ERROR.IOError; + } + } + } + else + { + return ERROR.NotReadyError; + } + } + } + } + return ERROR.NotReadyError; + } + catch + { + return ERROR.IOError; + } + } + + public override ERROR GetMifareDesfireFileList(string _applicationMasterKey, DESFireKeyType _keyType, int _keyNumberCurrent, int _appID) + { + try + { + IDESFireLocation location = new DESFireLocation + { + // The Application ID to use + aid = _appID, + // File communication requires encryption + SecurityLevel = (LibLogicalAccess.EncryptionMode)EncryptionMode.CM_ENCRYPT + }; + + // Keys to use for authentication + IDESFireAccessInfo aiToUse = new DESFireAccessInfo(); + CustomConverter.FormatMifareDesfireKeyStringWithSpacesEachByte(_applicationMasterKey); + aiToUse.MasterCardKey.Value = CustomConverter.DesfireKeyToCheck; + aiToUse.MasterCardKey.KeyType = ((LibLogicalAccess.DESFireKeyType)_keyType); + + object fileIDsObject; + + if (readerUnit.ConnectToReader()) + { + if (readerUnit.WaitInsertion(Constants.MAX_WAIT_INSERTION)) + { + if (readerUnit.Connect()) + { + ReaderUnitName = readerUnit.ConnectedName; + + card = readerUnit.GetSingleChip(); + + if (card.Type == "DESFire" || + card.Type == "DESFireEV1" || + card.Type == "DESFireEV2") + { + var cmd = card.Commands as IDESFireCommands; + try + { + cmd.SelectApplication((uint)_appID); + try + { + cmd.Authenticate((byte)_keyNumberCurrent, aiToUse.MasterCardKey); + } + catch + { + try + { + fileIDsObject = cmd.GetFileIDs(); + FileIDList = (fileIDsObject as byte[]); + return ERROR.NoError; + } + catch (Exception e) + { + if (e.Message != "" && e.Message.Contains("same number already exists")) + { + return ERROR.ItemAlreadyExistError; + } + else if (e.Message != "" && e.Message.Contains("status does not allow the requested command")) + { + return ERROR.AuthenticationError; + } + else + { + return ERROR.IOError; + } + } + } + + fileIDsObject = cmd.GetFileIDs(); + FileIDList = (fileIDsObject as byte[]); + + return ERROR.NoError; + } + catch (Exception e) + { + if (e.Message != "" && e.Message.Contains("same number already exists")) + { + return ERROR.ItemAlreadyExistError; + } + else if (e.Message != "" && e.Message.Contains("status does not allow the requested command")) + { + return ERROR.AuthenticationError; + } + else + { + return ERROR.IOError; + } + } + } + else + { + return ERROR.NotReadyError; + } + } + } + } + return ERROR.NotReadyError; + } + catch + { + return ERROR.IOError; + } + } + + public override ERROR GetMifareDesfireFileSettings(string _applicationMasterKey, DESFireKeyType _keyType, int _keyNumberCurrent, int _appID, int _fileNo) + { + try + { + // Keys to use for authentication + IDESFireAccessInfo aiToUse = new DESFireAccessInfo(); + CustomConverter.FormatMifareDesfireKeyStringWithSpacesEachByte(_applicationMasterKey); + aiToUse.MasterCardKey.Value = CustomConverter.DesfireKeyToCheck; + aiToUse.MasterCardKey.KeyType = (LibLogicalAccess.DESFireKeyType)_keyType; + + if (readerUnit.ConnectToReader()) + { + if (readerUnit.WaitInsertion(Constants.MAX_WAIT_INSERTION)) + { + if (readerUnit.Connect()) + { + ReaderUnitName = readerUnit.ConnectedName; + card = readerUnit.GetSingleChip(); + + if (card.Type == "DESFire" || + card.Type == "DESFireEV1" || + card.Type == "DESFireEV2") + { + var cmd = card.Commands as IDESFireCommands; + try + { + cmd.SelectApplication((uint)_appID); + try + { + cmd.Authenticate((byte)_keyNumberCurrent, aiToUse.MasterCardKey); + } + catch + { + try + { + desfireFileSetting = cmd.GetFileSettings((byte)_fileNo); + DesfireFileSettings = new DESFireFileSettings + { + accessRights = desfireFileSetting.accessRights, + comSett = desfireFileSetting.comSett, + FileType = desfireFileSetting.FileType, + dataFile = new DataFileSetting { fileSize = desfireFileSetting.dataFile.fileSize } + }; + + return ERROR.NoError; + } + catch (Exception e) + { + if (e.Message != "" && e.Message.Contains("same number already exists")) + { + return ERROR.ItemAlreadyExistError; + } + else if (e.Message != "" && e.Message.Contains("status does not allow the requested command")) + { + return ERROR.AuthenticationError; + } + else + { + return ERROR.IOError; + } + } + } + + desfireFileSetting = cmd.GetFileSettings((byte)_fileNo); + DesfireFileSettings = new DESFireFileSettings + { + accessRights = desfireFileSetting.accessRights, + comSett = desfireFileSetting.comSett, + FileType = desfireFileSetting.FileType, + dataFile = new DataFileSetting { fileSize = desfireFileSetting.dataFile.fileSize } + }; + + return ERROR.NoError; + } + catch (Exception e) + { + if (e.Message != "" && e.Message.Contains("same number already exists")) + { + return ERROR.ItemAlreadyExistError; + } + else if (e.Message != "" && e.Message.Contains("status does not allow the requested command")) + { + return ERROR.AuthenticationError; + } + else + { + return ERROR.IOError; + } + } + } + else + { + return ERROR.NotReadyError; + } + } + } + } + return ERROR.NotReadyError; + } + catch + { + return ERROR.IOError; + } + } + + #endregion mifare desfire + + #region mifare plus + + #endregion + + #region ISO15693 + + public ERROR ReadISO15693Chip() + { + try + { + if (readerUnit.ConnectToReader()) + { + if (readerUnit.WaitInsertion(Constants.MAX_WAIT_INSERTION)) + { + if (readerUnit.Connect()) + { + ReaderUnitName = readerUnit.ConnectedName; + + card = readerUnit.GetSingleChip(); + + + if (card.Type == "ISO15693") + { + var cmd = card.Commands as ISO15693Commands; + + object t = cmd.GetSystemInformation(); + + } + + return ERROR.NoError; + } + } + } + return ERROR.NoError; + } + catch (Exception e) + { + LogWriter.CreateLogEntry(string.Format("{0}: {1}; {2}", DateTime.Now, e.Message, e.InnerException != null ? e.InnerException.Message : ""), FacilityName); + return ERROR.IOError; + } + } + + #endregion + + #region EM4135 + + public ERROR ReadEM4135ChipPublic() + { + try + { + if (readerUnit.ConnectToReader()) + { + if (readerUnit.WaitInsertion(Constants.MAX_WAIT_INSERTION)) + { + if (readerUnit.Connect()) + { + ReaderUnitName = readerUnit.ConnectedName; + + card = readerUnit.GetSingleChip(); + + + if (true) + { + var cmd = (card as EM4135Chip).ChipIdentifier; + + } + + return ERROR.NoError; + } + } + } + return ERROR.NoError; + } + catch (Exception e) + { + LogWriter.CreateLogEntry(e, FacilityName); + return ERROR.IOError; + } + } + + #endregion + + protected override void Dispose(bool disposing) + { + if (!_disposed) + { + if (disposing) + { + } + + _disposed = true; + } + } + + public override void Dispose() + { + _disposed = false; + Dispose(true); + GC.SuppressFinalize(this); + } + } +} \ No newline at end of file diff --git a/RFiDGear/Properties/AssemblyInfo.cs b/RFiDGear/Properties/AssemblyInfo.cs index d66fd6c..cb93720 100644 --- a/RFiDGear/Properties/AssemblyInfo.cs +++ b/RFiDGear/Properties/AssemblyInfo.cs @@ -25,6 +25,6 @@ // // You can specify all the values or you can use the default the Revision and // Build Numbers by using the '*' as shown below: -[assembly: AssemblyVersion("1.6.*")] +[assembly: AssemblyVersion("1.7.*")] [assembly: Guid("a34bc413-e349-4fd1-8b90-2eb95a333436")] [assembly: NeutralResourcesLanguage("")] diff --git a/RFiDGear/RFiDGear.csproj b/RFiDGear/RFiDGear.csproj index 36f5c5c..2697a68 100644 --- a/RFiDGear/RFiDGear.csproj +++ b/RFiDGear/RFiDGear.csproj @@ -406,6 +406,9 @@ 1.9.1.8 + + 2.5.0 + 7.0.0 @@ -467,5 +470,8 @@ 4.5.0 + + + \ No newline at end of file diff --git a/RFiDGear/RFiDGear.csproj.user b/RFiDGear/RFiDGear.csproj.user index f90e435..d9b23aa 100644 --- a/RFiDGear/RFiDGear.csproj.user +++ b/RFiDGear/RFiDGear.csproj.user @@ -1,8 +1,8 @@  - REPORTTARGETPATH="C:\temp\test file_final.pdf" REPORTTEMPLATEFILE="C:\temp\test file.pdf" CUSTOMPROJECTFILE="D:\CardCheck_Data\KPruefung_Vorlagen\00_RFID_Gear_Vorlage\CardCheckAssistant.rfPrj" AUTORUN=0 %24JobNumber=1234 - D:\Seafile\Dokumente Privat\Steven\Projekte\Software\Windows\RFIDGear\RFiDGear\bin\Debug\ + REPORTTARGETPATH="D:\CardCheck_data\KP-000005-5_final.pdf" REPORTTEMPLATEFILE="D:\CardCheck_data\KP-000005-5_.pdf" CUSTOMPROJECTFILE="D:\CardCheck_data\KPruefung_Vorlagen\00_RFID_Gear_Vorlage\CardCheckAssistant_FreeMem.rfPrj" %24JOBNUMBER="KP-000005" %24CHIPNUMBER="5" AUTORUN=1 + D:\CardCheck_Data publish\ @@ -18,4 +18,8 @@ D:\Seafile\Dokumente Privat\Steven\Projekte\Software\Windows\RFIDGear\RFiDGear\bin\Debug\ "D:\Seafile\Dokumente Privat\Steven\Projekte\Software\Windows\RFIDGear\zipped.rfPrj" + + REPORTTARGETPATH="D:\CardCheck_data\KP-000005-5_final.pdf" REPORTTEMPLATEFILE="D:\CardCheck_data\KP-000005-5_.pdf" CUSTOMPROJECTFILE="D:\CardCheck_data\KPruefung_Vorlagen\00_RFID_Gear_Vorlage\CardCheckAssistant_FreeMem.rfPrj" %24JOBNUMBER="KP-000005" %24CHIPNUMBER="5" AUTORUN=1 + D:\CardCheck_Data + \ No newline at end of file diff --git a/RFiDGear/View/MainWindow.xaml b/RFiDGear/View/MainWindow.xaml index 5b1665b..1b0d0be 100644 --- a/RFiDGear/View/MainWindow.xaml +++ b/RFiDGear/View/MainWindow.xaml @@ -22,7 +22,7 @@ FontFamily="Segoe UI" FontWeight="Normal" MouseLeftButtonDown="WindowMouseLeftButtonDown" - SizeToContent="Manual" + SizeToContent="Width" WindowStartupLocation="CenterScreen" mc:Ignorable="d">