From 0643549884e8bf3be3ad5ca05c65d88a0fe90772 Mon Sep 17 00:00:00 2001 From: Steven Date: Wed, 12 Jun 2024 12:39:06 +0200 Subject: [PATCH] Version 1.9.8843 Version 1.8.8843 ----------------------------------------------------------------- Backend related changes: - ReaderDevice Improvement: Upgraded Elatec.NET to v0.4 - Reimplementation of Leosac's LibLogicalAccess Library to support PCSC Readers - Installer: Create a new EventSource "CardCheckAssistant" --- .gitignore | 1 + RFiDGear.sln | 12 +- .../RedCell.Diagnostics.Update/Updater.cs | 57 +- .../Remote/FromFile/ReportReaderWriter.cs | 24 +- .../Remote/FromFile/SettingsReaderWriter.cs | 3 +- .../Remote/FromIO/ElatecNetProvider.cs | 56 +- .../Remote/FromIO/LibLogicalAccessProvider.cs | 4073 +++++++---------- .../Remote/FromIO/ReaderDevice.cs | 12 +- .../MifareDesfire/MifareDesfireChipModel.cs | 9 + RFiDGear/Properties/AssemblyInfo.cs | 2 +- RFiDGear/RFiDGear.csproj | 10 +- RFiDGear/RFiDGear.csproj.user | 8 +- RFiDGear/Resources/Manifest.en.resx | 3 + RFiDGear/View/MainWindow.xaml.cs | 2 +- .../RFiDChipParentLayerViewModel.cs | 4 +- RFiDGear/ViewModel/MainWindowViewModel.cs | 411 +- RFiDGear/ViewModel/SetupViewModel.cs | 17 +- .../CommonTaskViewModel.cs | 7 +- .../GenericChipTaskViewModel.cs | 32 +- RFiDGearBundleSetup/Bundle.wxs | 50 +- .../RFiDGearBundleSetup.wixproj | 1 + Setup/Product.wxs | 33 +- debugParam.txt | 4 +- 23 files changed, 2165 insertions(+), 2666 deletions(-) diff --git a/.gitignore b/.gitignore index a416e0c..b545da6 100644 --- a/.gitignore +++ b/.gitignore @@ -29,3 +29,4 @@ *.zip *.htm RFiDGear/RFiDGear.SDKStyle.csproj +*.txt diff --git a/RFiDGear.sln b/RFiDGear.sln index 8d10ff7..e845673 100644 --- a/RFiDGear.sln +++ b/RFiDGear.sln @@ -40,8 +40,8 @@ Global {D49B605A-7B08-4B82-B4D2-7DA7D0236B13}.Debug|x86.Build.0 = Debug|Any CPU {D49B605A-7B08-4B82-B4D2-7DA7D0236B13}.Release|Any CPU.ActiveCfg = Release|Any CPU {D49B605A-7B08-4B82-B4D2-7DA7D0236B13}.Release|Any CPU.Build.0 = Release|Any CPU - {D49B605A-7B08-4B82-B4D2-7DA7D0236B13}.Release|x64.ActiveCfg = Release|Any CPU - {D49B605A-7B08-4B82-B4D2-7DA7D0236B13}.Release|x64.Build.0 = Release|Any CPU + {D49B605A-7B08-4B82-B4D2-7DA7D0236B13}.Release|x64.ActiveCfg = Release|x64 + {D49B605A-7B08-4B82-B4D2-7DA7D0236B13}.Release|x64.Build.0 = Release|x64 {D49B605A-7B08-4B82-B4D2-7DA7D0236B13}.Release|x86.ActiveCfg = Release|Any CPU {D49B605A-7B08-4B82-B4D2-7DA7D0236B13}.Release|x86.Build.0 = Release|Any CPU {856CA06C-0B4C-46C6-AD71-873317F1C763}.Debug|Any CPU.ActiveCfg = Debug|x86 @@ -98,14 +98,14 @@ Global {EF56252E-257F-41D1-974B-C9015071CE7E}.Release|x86.Build.0 = Release|Any CPU {360F9AF9-6717-45B6-9707-5974575FE96A}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {360F9AF9-6717-45B6-9707-5974575FE96A}.Debug|Any CPU.Build.0 = Debug|Any CPU - {360F9AF9-6717-45B6-9707-5974575FE96A}.Debug|x64.ActiveCfg = Debug|x64 - {360F9AF9-6717-45B6-9707-5974575FE96A}.Debug|x64.Build.0 = Debug|x64 + {360F9AF9-6717-45B6-9707-5974575FE96A}.Debug|x64.ActiveCfg = Debug|Any CPU + {360F9AF9-6717-45B6-9707-5974575FE96A}.Debug|x64.Build.0 = Debug|Any CPU {360F9AF9-6717-45B6-9707-5974575FE96A}.Debug|x86.ActiveCfg = Debug|x86 {360F9AF9-6717-45B6-9707-5974575FE96A}.Debug|x86.Build.0 = Debug|x86 {360F9AF9-6717-45B6-9707-5974575FE96A}.Release|Any CPU.ActiveCfg = Release|Any CPU {360F9AF9-6717-45B6-9707-5974575FE96A}.Release|Any CPU.Build.0 = Release|Any CPU - {360F9AF9-6717-45B6-9707-5974575FE96A}.Release|x64.ActiveCfg = Release|x64 - {360F9AF9-6717-45B6-9707-5974575FE96A}.Release|x64.Build.0 = Release|x64 + {360F9AF9-6717-45B6-9707-5974575FE96A}.Release|x64.ActiveCfg = Release|Any CPU + {360F9AF9-6717-45B6-9707-5974575FE96A}.Release|x64.Build.0 = Release|Any CPU {360F9AF9-6717-45B6-9707-5974575FE96A}.Release|x86.ActiveCfg = Release|x86 {360F9AF9-6717-45B6-9707-5974575FE96A}.Release|x86.Build.0 = Release|x86 EndGlobalSection diff --git a/RFiDGear/3rdParty/RedCell/RedCell.Diagnostics.Update/Updater.cs b/RFiDGear/3rdParty/RedCell/RedCell.Diagnostics.Update/Updater.cs index 308e25b..1783481 100644 --- a/RFiDGear/3rdParty/RedCell/RedCell.Diagnostics.Update/Updater.cs +++ b/RFiDGear/3rdParty/RedCell/RedCell.Diagnostics.Update/Updater.cs @@ -88,8 +88,12 @@ public Updater(FileInfo configFile) _localConfig = new Manifest(data); #if DEBUG - _localConfig.Version = 0; + //_localConfig.Version = 0; #endif + if (_localConfig != null) + { + Check(null, null); + } var rootDirectory = new DirectoryInfo(Path.GetDirectoryName(me)); var rootFiles = rootDirectory.GetFiles("*.*", SearchOption.TopDirectoryOnly); } @@ -151,31 +155,12 @@ await Task.Run(() => /// /// Checks the specified state. /// - /// The state. + /// + /// true = download Changelog only public async void Check(object state, EventArgs args) { try { - if (AllowUpdate && !_updating) - { - _timer.Interval = new TimeSpan(0, 0, 0, _localConfig.CheckInterval, 0); - - _updating = true; - await Update(); - _updating = false; - IsUserNotified = false; - eventLog.WriteEntry(string.Format("Check ending."), EventLogEntryType.Information); - return; - } - eventLog.WriteEntry(string.Format("Check starting."), EventLogEntryType.Information); - - if (_updating) - { - eventLog.WriteEntry(string.Format("Updater is already updating."), EventLogEntryType.Warning); - eventLog.WriteEntry(string.Format("Check ending."), EventLogEntryType.Information); - return; - } - var remoteUri = new Uri(_localConfig.RemoteConfigUri); eventLog.WriteEntry(string.Format("Fetching '{0}'.", _localConfig.RemoteConfigUri), EventLogEntryType.Information); @@ -186,7 +171,7 @@ public async void Check(object state, EventArgs args) if (!http.Success) { - + try { eventLog.WriteEntry(string.Format("Fetch error: {0}", http.Response != null ? http.Response.StatusDescription : ""), EventLogEntryType.Error); @@ -196,7 +181,7 @@ public async void Check(object state, EventArgs args) { eventLog.WriteEntry(string.Format("Fetch error: Unknown http Err"), EventLogEntryType.Information); } - + _remoteConfig = null; return; } @@ -212,6 +197,28 @@ public async void Check(object state, EventArgs args) var data = Encoding.UTF8.GetString(http.ResponseData); _remoteConfig = new Manifest(data); + UpdateInfoText = _remoteConfig.VersionInfoText; + + if (AllowUpdate && !_updating) + { + _timer.Interval = new TimeSpan(0, 0, 0, _localConfig.CheckInterval, 0); + + _updating = true; + await Update(); + _updating = false; + IsUserNotified = false; + eventLog.WriteEntry(string.Format("Check ending."), EventLogEntryType.Information); + return; + } + eventLog.WriteEntry(string.Format("Check starting."), EventLogEntryType.Information); + + if (_updating) + { + eventLog.WriteEntry(string.Format("Updater is already updating."), EventLogEntryType.Warning); + eventLog.WriteEntry(string.Format("Check ending."), EventLogEntryType.Information); + return; + } + if (_remoteConfig == null) { UpdateAvailable = false; @@ -223,6 +230,7 @@ public async void Check(object state, EventArgs args) UpdateAvailable = false; return; } + eventLog.WriteEntry(string.Format("Remote config is valid."), EventLogEntryType.Information); eventLog.WriteEntry(string.Format("Local version is ", _localConfig.Version), EventLogEntryType.Information); eventLog.WriteEntry(string.Format("Remote version is ", _remoteConfig.Version), EventLogEntryType.Information); @@ -233,6 +241,7 @@ public async void Check(object state, EventArgs args) UpdateAvailable = false; return; } + if (_remoteConfig.Version < _localConfig.Version) { eventLog.WriteEntry(string.Format("Remote version is older. That's weird o_O. Check ending."), EventLogEntryType.Warning); diff --git a/RFiDGear/DataAccessLayer/Remote/FromFile/ReportReaderWriter.cs b/RFiDGear/DataAccessLayer/Remote/FromFile/ReportReaderWriter.cs index 8260ba3..89efc84 100644 --- a/RFiDGear/DataAccessLayer/Remote/FromFile/ReportReaderWriter.cs +++ b/RFiDGear/DataAccessLayer/Remote/FromFile/ReportReaderWriter.cs @@ -19,7 +19,8 @@ public class ReportReaderWriter : IDisposable private readonly Version Version = Assembly.GetExecutingAssembly().GetName().Version; private readonly EventLog eventLog = new EventLog("Application", ".", Assembly.GetEntryAssembly().GetName().Name); private const string reportTemplateTempFileName = "temptemplate.pdf"; - private readonly string appDataPath; + private readonly string appDataPath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), "RFiDGear"); + private readonly string tempReportTemplateFileName = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), "RFiDGear", reportTemplateTempFileName); public string ReportOutputPath { get; set; } public string ReportTemplateFile { get; set; } @@ -32,18 +33,14 @@ public ReportReaderWriter() // Set license key to use GemBox.Pdf in Free mode. ComponentInfo.SetLicense("FREE-LIMITED-KEY"); - appDataPath = Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData); - - appDataPath = System.IO.Path.Combine(appDataPath, "RFiDGear"); - if (!Directory.Exists(appDataPath)) { Directory.CreateDirectory(appDataPath); } - if (File.Exists(System.IO.Path.Combine(appDataPath, reportTemplateTempFileName))) + if (File.Exists(tempReportTemplateFileName)) { - File.Delete(System.IO.Path.Combine(appDataPath, reportTemplateTempFileName)); + File.Delete(tempReportTemplateFileName); } } catch (Exception e) @@ -97,12 +94,15 @@ public async Task SetReportField(string _field, string _value) { await Task.Run(() => { - using (var pdfDoc = PdfDocument.Load(ReportTemplateFile)) + if (!File.Exists(tempReportTemplateFileName)) + { + File.Copy(ReportTemplateFile, tempReportTemplateFileName, true); + } + + using (var pdfDoc = PdfDocument.Load(tempReportTemplateFileName)) { try { - ReportTemplateFile = System.IO.Path.Combine(appDataPath, reportTemplateTempFileName); - var form = pdfDoc.Form; pdfDoc.Info.Title = "RFiDGear Report"; pdfDoc.Info.Author = "RFiDGear"; @@ -117,14 +117,14 @@ await Task.Run(() => pdfDoc.Save(ReportOutputPath); pdfDoc.Close(); - File.Copy(ReportOutputPath, System.IO.Path.Combine(appDataPath, reportTemplateTempFileName), true); + File.Copy(ReportOutputPath, tempReportTemplateFileName, true); } catch (Exception e) { eventLog.WriteEntry(string.Format(e.Message + "; SetReportField: " + _field), EventLogEntryType.Error); } } - }).ConfigureAwait(true); + }); return; } diff --git a/RFiDGear/DataAccessLayer/Remote/FromFile/SettingsReaderWriter.cs b/RFiDGear/DataAccessLayer/Remote/FromFile/SettingsReaderWriter.cs index 3e14dc0..70a19e7 100644 --- a/RFiDGear/DataAccessLayer/Remote/FromFile/SettingsReaderWriter.cs +++ b/RFiDGear/DataAccessLayer/Remote/FromFile/SettingsReaderWriter.cs @@ -24,12 +24,11 @@ public class SettingsReaderWriter : IDisposable private readonly int _updateInterval = 900; private readonly string _securityToken = "D68EF3A7-E787-4CC4-B020-878BA649B4CD"; private readonly string _payload = "update.zip"; - private readonly string _infoText = "Version Info\n\ngoes here! \n==>"; + private string _infoText = "Version Info\n\ngoes here! \n==>"; private readonly string _baseUri = @"https://github.com/c3rebro/RFiDGear/releases/latest/download/"; private readonly Version Version = Assembly.GetExecutingAssembly().GetName().Version; - private readonly string appDataPath; private bool _disposed; diff --git a/RFiDGear/DataAccessLayer/Remote/FromIO/ElatecNetProvider.cs b/RFiDGear/DataAccessLayer/Remote/FromIO/ElatecNetProvider.cs index 5ed41b3..dd03be7 100644 --- a/RFiDGear/DataAccessLayer/Remote/FromIO/ElatecNetProvider.cs +++ b/RFiDGear/DataAccessLayer/Remote/FromIO/ElatecNetProvider.cs @@ -24,22 +24,13 @@ public class ElatecNetProvider : ReaderDevice, IDisposable private bool _disposed; - public override string ReaderUnitName - { - get; set; - } - public override string ReaderUnitVersion - { - get; set; - } - #region Constructor private async Task Initialize() { if (GenericChip == null) { - GenericChip = new List(); + GenericChip = new GenericChipModel(); } try @@ -73,7 +64,7 @@ public ElatecNetProvider() { if (GenericChip == null) { - GenericChip = new List(); + GenericChip = new GenericChipModel(); } } @@ -143,40 +134,53 @@ public async override Task ReadChipPublic() await readerDevice.SetTagTypesAsync(LFTagTypes.NOTAG, HFTagTypes.AllHFTags); - if (!string.IsNullOrWhiteSpace(hfTag?.UID) && GenericChip.Any(x => x.UID == hfTag.UID)) + if (!string.IsNullOrWhiteSpace(hfTag?.UID) && GenericChip.UID == hfTag.UID) { return ERROR.NoError; } - if (!string.IsNullOrWhiteSpace(hfTag?.UID) && !GenericChip.Any(x => x.UID == hfTag.UID)) + if (!string.IsNullOrWhiteSpace(hfTag?.UID) && !(GenericChip.UID == hfTag.UID)) { - GenericChip = new List(); - if (!string.IsNullOrWhiteSpace(hfTag?.UID)) { - GenericChip.Add(hfTag); + GenericChip = hfTag; + } + } - if (GenericChip[0].Childs == null) - { - GenericChip[0].Childs = new List(); - } + if (hfTag != null && !string.IsNullOrEmpty(lfTag?.UID)) + { + if (GenericChip.Childs == null) + { + GenericChip.Childs = new List(); } + + GenericChip.Childs.Add(lfTag); } - if (!string.IsNullOrEmpty(lfTag?.UID)) + else if (!string.IsNullOrEmpty(lfTag?.UID)) { - GenericChip[0].Childs.Add(lfTag); + GenericChip = lfTag; + } + + if (hfTag != null && !string.IsNullOrEmpty(legicTag?.UID)) + { + if (GenericChip.Childs == null) + { + GenericChip.Childs = new List(); + } + + GenericChip.Childs.Add(legicTag); } - if (!string.IsNullOrEmpty(legicTag?.UID)) + else if (!string.IsNullOrEmpty(legicTag?.UID)) { - GenericChip[0].Childs.Add(legicTag); + GenericChip = legicTag; } } if (hfTag == null && lfTag == null && legicTag == null) { - GenericChip = new List(); + GenericChip = new GenericChipModel(); } return ERROR.NoError; @@ -400,7 +404,7 @@ private async Task ReadWriteAccessOnClassicSector(int sectorNumber, strin #endregion #region MifareUltralight - public override ERROR ReadMifareUltralightSinglePage(int _pageNo) + public override Task ReadMifareUltralightSinglePage(int _pageNo) { throw new NotImplementedException(); } diff --git a/RFiDGear/DataAccessLayer/Remote/FromIO/LibLogicalAccessProvider.cs b/RFiDGear/DataAccessLayer/Remote/FromIO/LibLogicalAccessProvider.cs index 48afcee..cc657cd 100644 --- a/RFiDGear/DataAccessLayer/Remote/FromIO/LibLogicalAccessProvider.cs +++ b/RFiDGear/DataAccessLayer/Remote/FromIO/LibLogicalAccessProvider.cs @@ -7,10 +7,10 @@ using RFiDGear.Model; -using Log4CSharp; - using System; -using System.Threading; +using System.Threading.Tasks; +using System.Diagnostics; +using System.Reflection; namespace RFiDGear.DataAccessLayer.Remote.FromIO { @@ -23,13 +23,11 @@ namespace RFiDGear.DataAccessLayer.Remote.FromIO public class LibLogicalAccessProvider : ReaderDevice, IDisposable { // global (cross-class) Instances go here -> - private static readonly string FacilityName = "RFiDGear"; + private readonly EventLog eventLog = new EventLog("Application", ".", Assembly.GetEntryAssembly().GetName().Name); private ReaderProvider readerProvider; private ReaderUnit readerUnit; private Chip card; - #region properties - #endregion properties #region contructor public LibLogicalAccessProvider() @@ -44,2469 +42,1912 @@ public LibLogicalAccessProvider(ReaderTypes readerType) readerUnit = readerProvider.createReaderUnit(); GenericChip = new GenericChipModel("", CARD_TYPE.Unspecified); - AppIDList = new uint[0]; } catch (Exception e) { - LogWriter.CreateLogEntry(e, FacilityName); + eventLog.WriteEntry(e.Message, EventLogEntryType.Error); } } - #endregion contructor + #endregion contructor - #region common + #region common - public override ERROR Connect() => throw new NotImplementedException(); + /// + /// + /// + public override bool IsConnected => readerUnit?.isConnected() == true; - public override ERROR ReadChipPublic() - { - try + public override async Task ConnectAsync() + { + return await Task.Run(() => { - if (readerUnit.connectToReader()) + if(readerUnit?.connectToReader() == true) { - 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; - } - } + return ERROR.NoError; } - } - catch (Exception e) - { - if (readerProvider != null) - readerProvider.release(); + + else + { + return ERROR.NotReadyError; + } + }); + } - LogWriter.CreateLogEntry(e, FacilityName); + public override async Task ReadChipPublic() + { + try + { + if (await tryInitReader()) + { + card = readerUnit.getSingleChip(); - return ERROR.IOError; - } + if (!string.IsNullOrWhiteSpace(ByteArrayConverter.GetStringFrom(card.getChipIdentifier().ToArray()))) + { + try + { + var uidAsString = ByteArrayConverter.GetStringFrom(card.getChipIdentifier().ToArray()); + var chipType = (CARD_TYPE)Enum.Parse(typeof(CARD_TYPE), card.getCardType()); - return ERROR.IOError; - } + if ((chipType & CARD_TYPE.DESFire) == CARD_TYPE.DESFire) + { + DESFireCommands cmd = card.getCommands() as DESFireCommands; + + DESFireCommands.DESFireCardVersion version = cmd.getVersion(); + + GenericChip = new MifareDesfireChipModel( + uidAsString, + chipType, + "unsupported", + "unsupported", + string.Format("{0}{1}{2}{3}{4}\n{5}\n{6}\n{7}", + version.hardwareVendor.ToString("X2"), + version.hardwareType.ToString("X2"), + version.hardwareSubType.ToString("X2"), + version.softwareMjVersion.ToString("X2"), + version.softwareMnVersion.ToString("X2"), + string.Format("Size: 0x{0}", version.hardwareStorageSize.ToString("X2")), + string.Format("Prod Week: d:{0}", version.cwProd.ToString("X2")), + string.Format("Prod Year: d:{0}", version.yearProd.ToString("D2")) + )); + } - #endregion common + else if ((chipType & CARD_TYPE.MifareClassic) == CARD_TYPE.MifareClassic) + { + MifareCommands cmd = card.getCommands() as MifareCommands; - #region mifare classic + GenericChip = new MifareClassicChipModel( + uidAsString, + chipType + ); + } - public override ERROR ReadMifareClassicSingleSector(int sectorNumber, string aKey, string bKey) - { - var settings = new SettingsReaderWriter(); - Sector = new MifareClassicSectorModel(); + return ERROR.NoError; + } + catch (Exception e) + { + eventLog.WriteEntry(e.Message, EventLogEntryType.Error); - settings.ReadSettings(); + return ERROR.IOError; + } + } + else + return ERROR.NotReadyError; + } + } + catch (Exception e) + { + if (readerProvider != null) + readerProvider.release(); - var keyA = new MifareKey(CustomConverter.KeyFormatQuickCheck(aKey) ? aKey : CustomConverter.FormatMifareClassicKeyWithSpacesEachByte(aKey) ); - var keyB = new MifareKey(CustomConverter.KeyFormatQuickCheck(bKey) ? bKey : CustomConverter.FormatMifareClassicKeyWithSpacesEachByte(bKey) ); + eventLog.WriteEntry(e.Message, EventLogEntryType.Error); - try - { - if (readerUnit.connectToReader()) { - if (readerUnit.waitInsertion(Constants.MAX_WAIT_INSERTION)) { - if (readerUnit.connect()) - { - ReaderUnitName = readerUnit.getConnectedName(); + return ERROR.IOError; + } - card = readerUnit.getSingleChip(); + return ERROR.IOError; + } - 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 - 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; - } - } + #endregion common + #region mifare classic - public override ERROR WriteMifareClassicSingleSector(int sectorNumber, string _aKey, string _bKey, byte[] buffer) + public override async Task ReadMifareClassicSingleSector(int sectorNumber, string aKey, string bKey) { - 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(); + var settings = new SettingsReaderWriter(); + Sector = new MifareClassicSectorModel(); - card = readerUnit.getSingleChip(); + await settings.ReadSettings(); - 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); + var keyA = new MifareKey(CustomConverter.KeyFormatQuickCheck(aKey) ? aKey : CustomConverter.FormatMifareClassicKeyWithSpacesEachByte(aKey)); + var keyB = new MifareKey(CustomConverter.KeyFormatQuickCheck(bKey) ? bKey : CustomConverter.FormatMifareClassicKeyWithSpacesEachByte(bKey)); - return ERROR.IOError; - } - return ERROR.NotReadyError; - } + if (await tryInitReader()) { - 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)); + card = readerUnit.getSingleChip(); - if (readerUnit.connectToReader()) - { - if (readerUnit.waitInsertion(Constants.MAX_WAIT_INSERTION)) - { - if (readerUnit.connect()) - { - ReaderUnitName = readerUnit.getConnectedName(); - //readerSerialNumber = readerUnit.GetReaderSerialNumber(); + var cmd = card.getCommands() as MifareCommands; - card = readerUnit.getSingleChip(); + 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); - 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); + DataBlock = new MifareClassicDataBlockModel( + (byte)CustomConverter.GetChipBasedDataBlockNumber(sectorNumber, k), + k); - return ERROR.IOError; - } - return ERROR.IOError; - } + try + { + cmd.authenticate((byte)CustomConverter.GetChipBasedDataBlockNumber(sectorNumber, k), + (byte)0, + MifareKeyType.KT_KEY_A); - 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)); + Sector.IsAuthenticated = true; - if (readerUnit.connectToReader()) - { - if (readerUnit.waitInsertion(Constants.MAX_WAIT_INSERTION)) - { - if (readerUnit.connect()) - { - ReaderUnitName = readerUnit.getConnectedName(); - //readerSerialNumber = readerUnit.GetReaderSerialNumber(); + try + { + ByteVector data = cmd.readBinary( + (byte)CustomConverter.GetChipBasedDataBlockNumber(sectorNumber, k), + 48); - card = readerUnit.getSingleChip(); + DataBlock.Data = data.ToArray(); - 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); + DataBlock.IsAuthenticated = true; - return ERROR.IOError; - } - return ERROR.IOError; - } + Sector.DataBlock.Add(DataBlock); + } + catch + { + DataBlock.IsAuthenticated = false; + Sector.DataBlock.Add(DataBlock); + } + } + catch + { // Try Auth with keytype b - 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(); + try + { + cmd.loadKey((byte)1, MifareKeyType.KT_KEY_B, keyB); - settings.ReadSettings(); + cmd.authenticate( + (byte)CustomConverter.GetChipBasedDataBlockNumber(sectorNumber, k), + (byte)1, + MifareKeyType.KT_KEY_B); - var mAKeyToUse = new MifareKey(CustomConverter.KeyFormatQuickCheck(_aKeyToUse) ? _aKeyToUse : CustomConverter.FormatMifareClassicKeyWithSpacesEachByte(_aKeyToUse)); - var mBKeyToUse = new MifareKey(CustomConverter.KeyFormatQuickCheck(_bKeyToUse) ? _bKeyToUse : CustomConverter.FormatMifareClassicKeyWithSpacesEachByte(_bKeyToUse)); + Sector.IsAuthenticated = true; - var mAKeyToWrite = new MifareKey(CustomConverter.KeyFormatQuickCheck(_aKeyToWrite) ? _aKeyToWrite : CustomConverter.FormatMifareClassicKeyWithSpacesEachByte(_aKeyToWrite)); - var mBKeyToWrite = new MifareKey(CustomConverter.KeyFormatQuickCheck(_bKeyToWrite) ? _bKeyToWrite : CustomConverter.FormatMifareClassicKeyWithSpacesEachByte(_bKeyToWrite)); + try + { + object data = cmd.readBinary( + (byte)CustomConverter.GetChipBasedDataBlockNumber(sectorNumber, k), + 48); - var madAKeyToUse = new MifareKey(CustomConverter.KeyFormatQuickCheck(_madAKeyToUse) ? _madAKeyToUse : CustomConverter.FormatMifareClassicKeyWithSpacesEachByte(_madAKeyToUse)); - var madBKeyToUse = new MifareKey(CustomConverter.KeyFormatQuickCheck(_madBKeyToUse) ? _madBKeyToUse : CustomConverter.FormatMifareClassicKeyWithSpacesEachByte(_madBKeyToUse)); + DataBlock.Data = (byte[])data; - var madAKeyToWrite = new MifareKey(CustomConverter.KeyFormatQuickCheck(_madAKeyToWrite) ? _madAKeyToWrite : CustomConverter.FormatMifareClassicKeyWithSpacesEachByte(_madAKeyToWrite)); - var madBKeyToWrite = new MifareKey(CustomConverter.KeyFormatQuickCheck(_madBKeyToWrite) ? _madBKeyToWrite : CustomConverter.FormatMifareClassicKeyWithSpacesEachByte(_madBKeyToWrite)); + DataBlock.IsAuthenticated = true; - 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; - } + Sector.DataBlock.Add(DataBlock); + } + catch + { - 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(); + DataBlock.IsAuthenticated = false; - settings.ReadSettings(); + Sector.DataBlock.Add(DataBlock); - var mAKeyToUse = new MifareKey(CustomConverter.KeyFormatQuickCheck(_aKeyToUse) ? _aKeyToUse : CustomConverter.FormatMifareClassicKeyWithSpacesEachByte(_aKeyToUse)); - var mBKeyToUse = new MifareKey(CustomConverter.KeyFormatQuickCheck(_bKeyToUse) ? _bKeyToUse : CustomConverter.FormatMifareClassicKeyWithSpacesEachByte(_bKeyToUse)); + return ERROR.AuthenticationError; + } + } + catch + { + Sector.IsAuthenticated = false; + DataBlock.IsAuthenticated = false; - 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 + Sector.DataBlock.Add(DataBlock); - #region mifare ultralight + return ERROR.AuthenticationError; + } + } + } + } + catch + { + return ERROR.NoError; + } + return ERROR.NoError; - 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; + } + return ERROR.NotReadyError; } catch (Exception e) { - LogWriter.CreateLogEntry(e, FacilityName); - return ERROR.IOError; + eventLog.WriteEntry(e.Message, EventLogEntryType.Error); + return ERROR.AuthenticationError; } } - #endregion mifare ultralight - - #region mifare desfire - - public override ERROR GetMiFareDESFireChipAppIDs(string _appMasterKey, DESFireKeyType _keyTypeAppMasterKey) + public override async Task WriteMifareClassicSingleSector(int sectorNumber, string _aKey, string _bKey, byte[] buffer) { 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); + var keyA = new MifareKey(CustomConverter.FormatMifareClassicKeyWithSpacesEachByte(_aKey)); + var keyB = new MifareKey(CustomConverter.FormatMifareClassicKeyWithSpacesEachByte(_bKey)); + int blockCount = 0; - if (readerUnit.connectToReader()) + if (await tryInitReader()) { - 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; - } + card = readerUnit.getSingleChip(); - 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 cmd = card.getCommands() as MifareCommands; - 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; + 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); - // 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(); + for (int k = 0; k < blockCount; k++) + { + try + { + cmd.authenticate( + (byte)CustomConverter.GetChipBasedDataBlockNumber(sectorNumber, k), + (byte)0, + MifareKeyType.KT_KEY_A); + + try + { + cmd.updateBinary( + (byte)CustomConverter.GetChipBasedDataBlockNumber(sectorNumber, k), + new ByteVector(buffer)); - card = readerUnit.getSingleChip(); + return ERROR.NoError; + } + catch + { + return ERROR.AuthenticationError; + } + } + catch + { // Try Auth with keytype b - if (card.getCardType() == "DESFireEV1" || - card.getCardType() == "DESFireEV2") - { - try - { - var cmd = (card as DESFireChip).getDESFireCommands(); + try + { + cmd.authenticate((byte)CustomConverter.GetChipBasedDataBlockNumber(sectorNumber, k), + (byte)1, + MifareKeyType.KT_KEY_B); try { - cmd.selectApplication((uint)_appID); - cmd.authenticate((byte)0, aiToUse.masterCardKey); + cmd.updateBinary( + (byte)CustomConverter.GetChipBasedDataBlockNumber(sectorNumber, k), + new ByteVector(buffer)); + + return ERROR.NoError; + } 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; + return ERROR.AuthenticationError; } + } + 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; - } - 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; + } + return ERROR.NotReadyError; + } } - catch + catch (Exception e) { + eventLog.WriteEntry(e.Message, EventLogEntryType.Error); + return ERROR.IOError; } + return ERROR.NotReadyError; } - 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) + public override async Task WriteMifareClassicSingleBlock(int _blockNumber, string _aKey, string _bKey, byte[] buffer) { try { - // 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; - } + var keyA = new MifareKey(CustomConverter.FormatMifareClassicKeyWithSpacesEachByte(_aKey)); + var keyB = new MifareKey(CustomConverter.FormatMifareClassicKeyWithSpacesEachByte(_bKey)); - 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) - { + if (await tryInitReader()) + { + card = readerUnit.getSingleChip(); - try - { - // 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; - } + var cmd = card.getCommands() as MifareCommands; - 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; - } - } + try + { + cmd.loadKey((byte)0, MifareKeyType.KT_KEY_A, keyA); // FIXME "sectorNumber" to 0 - public override ERROR GetMifareDesfireAppSettings(string _applicationMasterKey, DESFireKeyType _keyType, int _keyNumberCurrent = 0, int _appID = 0) - { - byte maxNbrOfKeys; - LibLogicalAccess.Card.DESFireKeySettings keySettings; + try + { //try to Auth with Keytype A + cmd.authenticate((byte)(_blockNumber), (byte)0, MifareKeyType.KT_KEY_A); // FIXME same as '303 - 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); + cmd.updateBinary((byte)_blockNumber, new ByteVector(buffer)); - if (readerUnit.connectToReader()) - { - if (readerUnit.waitInsertion(Constants.MAX_WAIT_INSERTION)) - { - if (readerUnit.connect()) - { - ReaderUnitName = readerUnit.getConnectedName(); - card = readerUnit.getSingleChip(); + return ERROR.NoError; + } + catch + { // Try Auth with Keytype b - if (card.getCardType() == "DESFire") - { - var cmd = card.getCommands() as DESFireCommands; - 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())); + cmd.loadKey((byte)0, MifareKeyType.KT_KEY_B, keyB); - 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; - } - } + try + { + cmd.authenticate((byte)(_blockNumber), (byte)0, MifareKeyType.KT_KEY_B); // FIXME same as '303 - 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") + cmd.updateBinary((byte)(_blockNumber), new ByteVector(buffer)); + + return ERROR.NoError; + } + catch { - 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; - } - } + return ERROR.AuthenticationError; + } + } + } + catch + { + return ERROR.AuthenticationError; + } + } + } + catch (Exception e) + { + eventLog.WriteEntry(e.Message, EventLogEntryType.Error); - 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 _) + return ERROR.IOError; + } + return ERROR.IOError; + } + + public async Task ReadMifareClassicSingleBlock(int _blockNumber, string _aKey, string _bKey) { - try - { - DESFireKey masterApplicationKey = new DESFireKey(); - masterApplicationKey.setKeyType((LibLogicalAccess.Card.DESFireKeyType)_keyTypeCurrent); - CustomConverter.FormatMifareDesfireKeyStringWithSpacesEachByte(_applicationMasterKeyCurrent); - masterApplicationKey.fromString(CustomConverter.DesfireKeyToCheck); + try + { + var keyA = new MifareKey(CustomConverter.FormatMifareClassicKeyWithSpacesEachByte(_aKey)); + var keyB = new MifareKey(CustomConverter.FormatMifareClassicKeyWithSpacesEachByte(_bKey)); - DESFireKey applicationMasterKeyTarget = new DESFireKey(); - applicationMasterKeyTarget.setKeyType((LibLogicalAccess.Card.DESFireKeyType)_keyTypeTarget); - CustomConverter.FormatMifareDesfireKeyStringWithSpacesEachByte(_applicationMasterKeyTarget); - applicationMasterKeyTarget.fromString(CustomConverter.DesfireKeyToCheck); - //applicationMasterKeyTarget.setKeyVersion((byte)selectedDesfireAppKeyVersionTargetAsIntint); + if (await tryInitReader()) + { + card = readerUnit.getSingleChip(); - readerUnit.disconnectFromReader(); + if (!string.IsNullOrWhiteSpace(ByteArrayConverter.GetStringFrom(card.getChipIdentifier().ToArray()))) + { + try + { + //CardInfo = new CARD_INFO((CARD_TYPE)Enum.Parse(typeof(CARD_TYPE), card.getCardType()), ByteArrayConverter.GetStringFrom(card.getChipIdentifier().ToArray())); + GenericChip = new GenericChipModel(ByteArrayConverter.GetStringFrom(card.getChipIdentifier().ToArray()), (CARD_TYPE)Enum.Parse(typeof(CARD_TYPE), card.getCardType())); + } + catch (Exception e) + { + eventLog.WriteEntry(e.Message, EventLogEntryType.Error); + } + } - 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; - } - } + var cmd = card.getCommands() as MifareCommands; - 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; - } - } + try + { + cmd.loadKey((byte)0, MifareKeyType.KT_KEY_A, keyA); // FIXME "sectorNumber" to 0 - 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(); + try + { //try to Auth with Keytype A + cmd.authenticate((byte)(_blockNumber), (byte)0, MifareKeyType.KT_KEY_A); // FIXME same as '303 - card = readerUnit.getSingleChip(); + MifareClassicData = cmd.readBinary((byte)(_blockNumber), 48).ToArray(); - if (card.getCardType() == "DESFireEV1" || - card.getCardType() == "DESFireEV2" || - card.getCardType() == "DESFire") - { - try - { - var cmd = card.getCommands() as DESFireCommands; + return ERROR.NoError; + } + catch + { // Try Auth with keytype b - try - { - cmd.selectApplication((uint)_appID); - cmd.authenticate((byte)0, aiToUse.masterCardKey); - } + cmd.loadKey((byte)0, MifareKeyType.KT_KEY_B, keyB); - catch - { - cmd.deleteFile((byte)_fileID); - return ERROR.NoError; - } + try + { + cmd.authenticate((byte)(_blockNumber), (byte)0, MifareKeyType.KT_KEY_B); // FIXME same as '303 - 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; - } - } + MifareClassicData = cmd.readBinary((byte)(_blockNumber), 48).ToArray(); - 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; - } - } + return ERROR.NoError; + } + catch + { + return ERROR.AuthenticationError; + } + } + } + catch + { + return ERROR.AuthenticationError; + } + } + } + catch (Exception e) + { + eventLog.WriteEntry(e.Message, EventLogEntryType.Error); + + return ERROR.IOError; + } + return ERROR.IOError; + } - public override ERROR GetMifareDesfireFileList(string _applicationMasterKey, DESFireKeyType _keyType, int _keyNumberCurrent = 0, int _appID = 0) + public override async Task 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) { - 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; - } - } + try + { + var settings = new SettingsReaderWriter(); + Sector = new MifareClassicSectorModel(); + + await 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)); + + if (await tryInitReader()) + { + card = readerUnit.getSingleChip(); + + 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) + { + eventLog.WriteEntry(e.Message, EventLogEntryType.Error); + return ERROR.AuthenticationError; + } + return ERROR.NoError; + } + } + catch (Exception e) + { + eventLog.WriteEntry(e.Message, EventLogEntryType.Error); + return ERROR.AuthenticationError; + } + return ERROR.NoError; + } - public override ERROR GetMifareDesfireFileSettings(string _applicationMasterKey, DESFireKeyType _keyType, int _keyNumberCurrent = 0, int _appID = 0, int _fileNo = 0) + public override async Task ReadMifareClassicWithMAD(int madApplicationID, string _aKeyToUse, + string _bKeyToUse, string _madAKeyToUse, string _madBKeyToUse, int _length, + byte _madGPB, bool _useMADToAuth = true, bool _aiToUseIsMAD = false) { - 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; - } - } + try + { + var settings = new SettingsReaderWriter(); + Sector = new MifareClassicSectorModel(); - #endregion mifare desfire - - #region mifare plus - - #endregion - - #region ISO15693 + await 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)); + + if (await tryInitReader()) + { + card = readerUnit.getSingleChip(); + + 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) + { + eventLog.WriteEntry(e.Message, EventLogEntryType.Error); + return ERROR.AuthenticationError; + } + return ERROR.NoError; + } + } + catch (Exception e) + { + eventLog.WriteEntry(e.Message, EventLogEntryType.Error); + return ERROR.AuthenticationError; + } + return ERROR.NoError; + } - public ERROR ReadISO15693Chip() + #endregion mifare classic + + #region mifare ultralight + + public override async Task ReadMifareUltralightSinglePage(int _pageNo) { try { - if (readerUnit.connectToReader()) + if (await tryInitReader()) { - if (readerUnit.waitInsertion(Constants.MAX_WAIT_INSERTION)) - { - if (readerUnit.connect()) - { - ReaderUnitName = readerUnit.getConnectedName(); - //readerSerialNumber = readerUnit.GetReaderSerialNumber(); + ReaderUnitName = readerUnit.getConnectedName(); + //readerSerialNumber = readerUnit.GetReaderSerialNumber(); + RawFormat format = new RawFormat(); - card = readerUnit.getSingleChip(); + var chip = readerUnit.getSingleChip() as MifareUltralightChip; - - if (card.getCardType() == "ISO15693") - { - var cmd = card.getCommands() as ISO15693Commands;// IMifareUltralightCommands; + var service = chip.getService(CardServiceType.CST_STORAGE) as StorageCardService; - object t = cmd.getSystemInformation(); - //object res = cmd.ReadPage(4); + Location location = chip.createLocation() as Location; - //appIDs = (appIDsObject as UInt32[]); - } + if (chip.getCardType() == "MifareUltralight") + { + var cmd = chip.getCommands() as MifareUltralightCommands;// IMifareUltralightCommands; + MifareUltralightPageData = cmd.readPages(_pageNo, _pageNo).ToArray(); + } - return ERROR.NoError; - } - } - } + return ERROR.NoError; + } return ERROR.NoError; } catch (Exception e) { - LogWriter.CreateLogEntry(e, FacilityName); + eventLog.WriteEntry(e.Message, EventLogEntryType.Error); return ERROR.IOError; } } - #endregion + #endregion mifare ultralight - #region EM4135 + #region mifare desfire - public ERROR ReadEM4135ChipPublic() - { + public override async Task GetMiFareDESFireChipAppIDs(string _appMasterKey, DESFireKeyType _keyTypeAppMasterKey) + { try { - if (readerUnit.connectToReader()) + if (DesfireChip == null) { - if (readerUnit.waitInsertion(Constants.MAX_WAIT_INSERTION)) - { - if (readerUnit.connect()) - { - ReaderUnitName = readerUnit.getConnectedName(); - //readerSerialNumber = readerUnit.GetReaderSerialNumber(); + DesfireChip = new MifareDesfireChipModel(); + } - card = readerUnit.getSingleChip(); + // 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 (true) //card.getCardType() == "ISO15693" - { - var cmd = (card as EM4135Chip).getChipIdentifier();// IMifareUltralightCommands; - //object res = cmd.ReadPage(4); - //appIDs = (appIDsObject as UInt32[]); - } + if (await tryInitReader()) + { + card = readerUnit.getSingleChip(); - return ERROR.NoError; - } + //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(); + foreach (uint appID in appIDsObject.ToArray()) + { + 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); + + UIntCollection appIDsObject = cmd.getApplicationIDs(); + foreach (uint appID in appIDsObject.ToArray()) + { + 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.getCardType() == "DESFireEV1" || + card.getCardType() == "DESFireEV2") + { + + var cmd = (card as DESFireChip).getDESFireCommands(); + + try + { + UIntCollection appIDsObject = cmd.getApplicationIDs(); + foreach (uint appID in appIDsObject.ToArray()) + { + DesfireChip.AppList.Add(new MifareDesfireAppModel(appID)); + } + + var ev1Cmd = (card as DESFireEV1Chip).getDESFireEV1Commands(); + DesfireChip.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(); + foreach (uint appID in appIDsObject.ToArray()) + { + DesfireChip.AppList.Add(new MifareDesfireAppModel(appID)); + } + + var ev1Cmd = (card as DESFireEV1Chip).getDESFireEV1Commands(); + DesfireChip.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(); + foreach (uint appID in appIDsObject.ToArray()) + { + DesfireChip.AppList.Add(new MifareDesfireAppModel(appID)); + } + + return ERROR.NoError; + } + + if (card.getCardType() == "DESFireEV1" || + card.getCardType() == "DESFireEV2") + { + var cmd = (card as DESFireEV1Chip).getDESFireEV1Commands(); + + } + else + return ERROR.NotReadyError; + } + + catch + { + + } } } - return ERROR.NoError; + return ERROR.NotReadyError; } + catch (Exception e) { - LogWriter.CreateLogEntry(e, FacilityName); + 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 async Task 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); + + var arToUse = 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 + }; + + if (await tryInitReader()) + { + card = readerUnit.getSingleChip(); + + try + { + DESFireCommands cmd; + + if (card.getCardType() == "DESFireEV1" || + card.getCardType() == "DESFireEV2") + { + cmd = (card as DESFireChip).getDESFireCommands(); + } + else if (card.getCardType() == "DESFire") + { + cmd = card.getCommands() as DESFireCommands; + } + else + { + cmd = (card as DESFireChip).getDESFireCommands(); + } + + + cmd.selectApplication((uint)_appID); + cmd.authenticate((byte)0, aiToUse.masterCardKey); + + switch (_fileType) + { + case FileType_MifareDesfireFileType.StdDataFile: + cmd.createStdDataFile((byte)_fileNo, (LibLogicalAccess.Card.EncryptionMode)_encMode, arToUse, (uint)_fileSize); + break; + + case FileType_MifareDesfireFileType.BackupFile: + cmd.createBackupFile((byte)_fileNo, (LibLogicalAccess.Card.EncryptionMode)_encMode, arToUse, (uint)_fileSize); + break; + + case FileType_MifareDesfireFileType.ValueFile: + cmd.createValueFile((byte)_fileNo, (LibLogicalAccess.Card.EncryptionMode)_encMode, arToUse, _minValue, _maxValue, _initValue, _isValueLimited); + break; + + case FileType_MifareDesfireFileType.CyclicRecordFile: + cmd.createCyclicRecordFile((byte)_fileNo, (LibLogicalAccess.Card.EncryptionMode)_encMode, arToUse, (uint)_fileSize, (uint)_maxNbOfRecords); + break; + + case FileType_MifareDesfireFileType.LinearRecordFile: + cmd.createLinearRecordFile((byte)_fileNo, (LibLogicalAccess.Card.EncryptionMode)_encMode, arToUse, (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; + } + } + return ERROR.NotReadyError; + } + catch + { + return ERROR.IOError; + } + } + + public override async Task 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 + 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 (await tryInitReader()) + { + 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 async Task 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 + 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 (await tryInitReader()) + { + 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 async Task 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 + + // 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 (await tryInitReader()) + { + 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; } } - #endregion + public override async Task GetMifareDesfireAppSettings(string _applicationMasterKey, DESFireKeyType _keyType, int _keyNumberCurrent = 0, int _appID = 0) + { + byte maxNbrOfKeys; + LibLogicalAccess.Card.DESFireKeySettings keySettings; + + if (DesfireChip == null) + { + DesfireChip = new MifareDesfireChipModel(); + } + + 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 (await tryInitReader()) + { + card = readerUnit.getSingleChip(); + + DESFireCommands cmd; + + if (card.getCardType() == "DESFire") + { + cmd = card.getCommands() as DESFireCommands; + } + + else if (card.getCardType() == "DESFireEV1" || + card.getCardType() == "DESFireEV2" || card.getCardType() == "GENERIC_T_CL_A") + { + cmd = (card as DESFireChip).getDESFireCommands(); + } + else + { + cmd = card.getCommands() as DESFireCommands; + } + + try + { + cmd.selectApplication((uint)_appID); + DesfireChip.UID = ByteArrayConverter.GetStringFrom(card.getChipIdentifier().ToArray()); + + 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; + } + } + return ERROR.NotReadyError; + } + catch + { + return ERROR.IOError; + } + } + + public override async Task 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 (await tryInitReader()) + { + card = readerUnit.getSingleChip(); + + var cmd = card.getCommands() as DESFireCommands; + var ev1Cmd = (card as DESFireEV1Chip).getDESFireEV1Commands(); + + try + { + cmd.selectApplication(0); + + if (authenticateToPICCFirst) + cmd.authenticate((byte)0, aiToUse.masterCardKey); + + if (card.getCardType() == "DESFire") + { + cmd.createApplication((uint)_appID, (LibLogicalAccess.Card.DESFireKeySettings)_keySettingsTarget, (byte)_maxNbKeys); + } + else if (card.getCardType() == "DESFireEV1" || + card.getCardType() == "DESFireEV2") + { + ev1Cmd.createApplication((uint)_appID, (LibLogicalAccess.Card.DESFireKeySettings)_keySettingsTarget, (byte)_maxNbKeys, (LibLogicalAccess.Card.DESFireKeyType)_keyTypeTargetApplication); + } + else + { + return ERROR.NotAllowed; + } + 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; + } + } + return ERROR.NotReadyError; + } + catch + { + return ERROR.IOError; + } + } + + public override async Task 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); + + readerUnit.disconnectFromReader(); + + if (await tryInitReader()) + { + 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; + + 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 async Task DeleteMifareDesfireApplication(string _applicationMasterKey, DESFireKeyType _keyType, uint _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 (await tryInitReader()) + { + 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 async Task 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 (await tryInitReader()) + { + card = readerUnit.getSingleChip(); + + if (card.getCardType() == "DESFireEV1" || + card.getCardType() == "DESFireEV2" || + card.getCardType() == "DESFire") + { + try + { + var cmd = card.getCommands() as DESFireCommands; + + try + { + 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; + } + } + + public override async Task FormatDesfireCard(string _applicationMasterKey, DESFireKeyType _keyType) + { + try + { + // The excepted memory tree + DESFireLocation location = new DESFireLocation(); + // The Application ID to use + location.aid = (uint)0; + // 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 (await tryInitReader()) + { + 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(); + + 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 async Task 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 (await tryInitReader()) + { + 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 async Task GetMifareDesfireFileSettings(string _applicationMasterKey, DESFireKeyType _keyType, int _keyNumberCurrent = 0, int _appID = 0, int _fileNo = 0) + { + 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); + + DESFireCommands.FileSetting fsFromChip; + + if (await tryInitReader()) + { + 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 + { + fsFromChip = cmd.getFileSettings((byte)_fileNo); + DesfireFileSettings = new DESFireFileSettings(); + + DesfireFileSettings.accessRights = fsFromChip.accessRights; + DesfireFileSettings.comSett = fsFromChip.comSett; + //dataFile = fs.getDataFile(), + DesfireFileSettings.FileType = fsFromChip.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; + } + } + + fsFromChip = cmd.getFileSettings((byte)_fileNo); + DesfireFileSettings = new DESFireFileSettings(); + + DesfireFileSettings.accessRights = fsFromChip.accessRights; + DesfireFileSettings.comSett = fsFromChip.comSett; + //dataFile = fs.getDataFile(), + DesfireFileSettings.FileType = fsFromChip.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 + + private async Task tryInitReader() + { + return await Task.Run(() => + { + try + { + if (readerUnit.connectToReader()) + { + if (readerUnit.waitInsertion(Constants.MAX_WAIT_INSERTION)) + { + if (readerUnit.connect()) + { + ReaderUnitName = readerUnit.getConnectedName(); + + return true; + } + } + } + } + catch + { + return false; + } + + return false; + }); + } protected override void Dispose(bool disposing) { diff --git a/RFiDGear/DataAccessLayer/Remote/FromIO/ReaderDevice.cs b/RFiDGear/DataAccessLayer/Remote/FromIO/ReaderDevice.cs index fd05dbc..be5ac3a 100644 --- a/RFiDGear/DataAccessLayer/Remote/FromIO/ReaderDevice.cs +++ b/RFiDGear/DataAccessLayer/Remote/FromIO/ReaderDevice.cs @@ -15,7 +15,7 @@ public static ReaderDevice Instance { switch (Reader) { - /* + case ReaderTypes.PCSC: lock (syncRoot) { @@ -34,7 +34,7 @@ public static ReaderDevice Instance return instance; } } - */ + case ReaderTypes.Elatec: lock (syncRoot) { @@ -76,13 +76,13 @@ public static ReaderDevice Instance public MifareClassicSectorModel Sector { get; set; } public MifareClassicDataBlockModel DataBlock { get; set; } - public List GenericChip { get; set; } + public GenericChipModel GenericChip { get; set; } public MifareDesfireChipModel DesfireChip { get; set; } public MifareClassicChipModel ClassicChip { get; set; } public ReaderTypes ReaderProvider { get; set; } - public abstract string ReaderUnitName { get; set; } - public abstract string ReaderUnitVersion { get; set; } + public string ReaderUnitName { get; set; } + public string ReaderUnitVersion { get; set; } public byte[] MifareClassicData { get; set; } public bool DataBlockSuccessfullyAuth { get; set; } public bool SectorSuccessfullyAuth { get; set; } @@ -116,7 +116,7 @@ public abstract Task ReadMifareClassicWithMAD(int madApplicationID, strin #region MifareUltralight // Mifare Ultralight Method Definitions - public abstract ERROR ReadMifareUltralightSinglePage(int _pageNo); + public abstract Task ReadMifareUltralightSinglePage(int _pageNo); #endregion #region MifareDesfire diff --git a/RFiDGear/Model/MifareDesfire/MifareDesfireChipModel.cs b/RFiDGear/Model/MifareDesfire/MifareDesfireChipModel.cs index 41e5d49..939bd62 100644 --- a/RFiDGear/Model/MifareDesfire/MifareDesfireChipModel.cs +++ b/RFiDGear/Model/MifareDesfire/MifareDesfireChipModel.cs @@ -35,12 +35,15 @@ public List AppList public MifareDesfireChipModel() { + AppList = new List(); } public MifareDesfireChipModel(string uid, CARD_TYPE cardType) { UID = uid; CardType = cardType; + + AppList = new List(); } public MifareDesfireChipModel(string uid, CARD_TYPE cardType, string sak, string rats) @@ -49,6 +52,8 @@ public MifareDesfireChipModel(string uid, CARD_TYPE cardType, string sak, string CardType = cardType; SAK = sak; RATS = rats; + + AppList = new List(); } public MifareDesfireChipModel(string uid, CARD_TYPE cardType, string sak, string rats, string versionL4) @@ -58,6 +63,8 @@ public MifareDesfireChipModel(string uid, CARD_TYPE cardType, string sak, string SAK = sak; RATS = rats; VersionL4 = versionL4; + + AppList = new List(); } public MifareDesfireChipModel(MifareDesfireChipModel genericChip) @@ -68,6 +75,8 @@ public MifareDesfireChipModel(MifareDesfireChipModel genericChip) RATS = genericChip.RATS; VersionL4 = genericChip.VersionL4; Childs = genericChip.Childs; + + AppList = new List(); } public string SAK { get; set; } diff --git a/RFiDGear/Properties/AssemblyInfo.cs b/RFiDGear/Properties/AssemblyInfo.cs index bce9144..e944f0e 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.8.*")] +[assembly: AssemblyVersion("1.9.*")] [assembly: Guid("a34bc413-e349-4fd1-8b90-2eb95a333436")] [assembly: NeutralResourcesLanguage("")] diff --git a/RFiDGear/RFiDGear.csproj b/RFiDGear/RFiDGear.csproj index 523b242..34e2e7e 100644 --- a/RFiDGear/RFiDGear.csproj +++ b/RFiDGear/RFiDGear.csproj @@ -81,7 +81,7 @@ true - bin\x64\Release\ + bin\Release\ TRACE true 4096 @@ -160,6 +160,7 @@ + @@ -399,13 +400,16 @@ 8.0.0 - 17.0.1258 + 17.0.1565 1.9.1.8 - 3.0.0 + 3.1.1 + + + 3.0.1 7.0.0 diff --git a/RFiDGear/RFiDGear.csproj.user b/RFiDGear/RFiDGear.csproj.user index 80deecb..9f835dd 100644 --- a/RFiDGear/RFiDGear.csproj.user +++ b/RFiDGear/RFiDGear.csproj.user @@ -1,8 +1,7 @@  - - + 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" %24JOBNUMBER="KP-000005" %24CHIPNUMBER="5" AUTORUN=0 D:\CardCheck_Data @@ -16,9 +15,8 @@ false - D:\Seafile\Dokumente Privat\Steven\Projekte\Software\Windows\RFIDGear\RFiDGear\bin\Debug\ - - + D:\CardCheck_data + REPORTTARGETPATH="D:\CardCheck_data\KP-000005-5_final.pdf" CUSTOMPROJECTFILE="D:\CardCheck_data\KPruefung_Vorlagen\00_RFID_Gear_Vorlage\CardCheck_OhneSchreibvorgang_Deutsch_DESFire-Classic-Unbekannt_01_mitEXIT.rfPrj" %24JOBNUMBER="KP-000005" %24CHIPNUMBER="5" AUTORUN=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_FreeMem.rfPrj" %24JOBNUMBER="KP-000005" %24CHIPNUMBER="5" AUTORUN=1 diff --git a/RFiDGear/Resources/Manifest.en.resx b/RFiDGear/Resources/Manifest.en.resx index 6508b38..4f0c311 100644 --- a/RFiDGear/Resources/Manifest.en.resx +++ b/RFiDGear/Resources/Manifest.en.resx @@ -1639,4 +1639,7 @@ https://github.com/c3rebro/rfidgear No Reader Found + + Write Key No. + \ No newline at end of file diff --git a/RFiDGear/View/MainWindow.xaml.cs b/RFiDGear/View/MainWindow.xaml.cs index a0be5c3..8551185 100644 --- a/RFiDGear/View/MainWindow.xaml.cs +++ b/RFiDGear/View/MainWindow.xaml.cs @@ -79,7 +79,7 @@ private void MainWindowTreeViewControlMouseButtonDown(object sender, MouseButton } } } - //Missing Visual implementation in "Run" Method of Textblock + //Missing Visual implementation in "InitOnFirstRun" Method of Textblock catch { } diff --git a/RFiDGear/ViewModel/HirarchicalDataTemplateViewModels/RFiDChipParentLayerViewModel.cs b/RFiDGear/ViewModel/HirarchicalDataTemplateViewModels/RFiDChipParentLayerViewModel.cs index cfbbdf1..d184352 100644 --- a/RFiDGear/ViewModel/HirarchicalDataTemplateViewModels/RFiDChipParentLayerViewModel.cs +++ b/RFiDGear/ViewModel/HirarchicalDataTemplateViewModels/RFiDChipParentLayerViewModel.cs @@ -524,7 +524,7 @@ await device.GetMifareDesfireAppSettings("00000000000000000000000000000000", DES /// /// /// - private void MifareUltralightQuickCheck() + private async void MifareUltralightQuickCheck() { if (!isTask) { @@ -535,7 +535,7 @@ private void MifareUltralightQuickCheck() foreach (var cnVM in Children) { - if (device.ReadMifareUltralightSinglePage(cnVM.PageNumber) == ERROR.NoError) + if (await device.ReadMifareUltralightSinglePage(cnVM.PageNumber) == ERROR.NoError) { //var dataToShow = ByteArrayConverter.GetStringFrom(device.MifareUltralightPageData); /* diff --git a/RFiDGear/ViewModel/MainWindowViewModel.cs b/RFiDGear/ViewModel/MainWindowViewModel.cs index b26c166..9fe7124 100644 --- a/RFiDGear/ViewModel/MainWindowViewModel.cs +++ b/RFiDGear/ViewModel/MainWindowViewModel.cs @@ -75,7 +75,6 @@ public class MainWindowViewModel : ObservableObject private int currentTaskIndex = 0; // set if task was completed; indicates greenlight to continue execution // if programming takes too long; quit the process - private bool firstRun = true; private bool userIsNotifiedForAvailableUpdate = false; private protected Mutex mutex; @@ -378,7 +377,7 @@ private async void UpdateChip(object sender, EventArgs args) IsReaderBusy = true; await device.ReadChipPublic(); - GenericChip = device.GenericChip[0]; + GenericChip = device.GenericChip; IsReaderBusy = false; ; } @@ -968,63 +967,67 @@ private async Task OnNewReadChipCommand() using (var device = ReaderDevice.Instance) { - foreach (var item in treeViewParentNodes) + if(device != null) { - item.IsExpanded = false; - item.IsSelected = false; - } - - device?.GenericChip?.Clear(); - var result = await device?.ReadChipPublic(); - var wellKnownTvNodes = from nodes in treeViewParentNodes from chips in device.GenericChip where nodes.UID == chips.UID select nodes; - - if (result == ERROR.NoError && !wellKnownTvNodes.Any()) - { - foreach (var gCM in device.GenericChip) + foreach (var item in treeViewParentNodes) { - switch ((CARD_TYPE)((short)gCM.CardType & 0xF000)) - { - case CARD_TYPE.MifareClassic: - treeViewParentNodes.Add( - new RFiDChipParentLayerViewModel( - new MifareClassicChipModel(gCM as MifareClassicChipModel), Dialogs, false)); - break; - - case CARD_TYPE.DESFireEV0: - case CARD_TYPE.DESFireEV1: - case CARD_TYPE.DESFireEV2: - case CARD_TYPE.DESFireEV3: - treeViewParentNodes.Add( - new RFiDChipParentLayerViewModel( - new MifareDesfireChipModel(gCM as MifareDesfireChipModel), Dialogs, false)); - break; - - case CARD_TYPE.MifarePlus: - treeViewParentNodes.Add( - new RFiDChipParentLayerViewModel( - new MifareClassicChipModel(gCM as MifareClassicChipModel), Dialogs, false)); - break; + item.IsExpanded = false; + item.IsSelected = false; + } - case CARD_TYPE.MifareUltralight: - treeViewParentNodes.Add( - new RFiDChipParentLayerViewModel( - new MifareUltralightChipModel(gCM), Dialogs, false)); - break; + device.GenericChip = new GenericChipModel(); + var result = await device.ReadChipPublic(); + var wellKnownTvNodes = from nodes in treeViewParentNodes where nodes.UID == device.GenericChip.UID select nodes; - default: - treeViewParentNodes.Add( - new RFiDChipParentLayerViewModel( - new GenericChipModel(gCM), Dialogs, false)); - break; - } + if (result == ERROR.NoError && !wellKnownTvNodes.Any()) + { + switch ((CARD_TYPE)((short)device.GenericChip.CardType & 0xF000)) + { + case CARD_TYPE.MifareClassic: + treeViewParentNodes.Add( + new RFiDChipParentLayerViewModel( + new MifareClassicChipModel(device.GenericChip as MifareClassicChipModel), Dialogs, false)); + break; + + case CARD_TYPE.DESFireEV0: + case CARD_TYPE.DESFireEV1: + case CARD_TYPE.DESFireEV2: + case CARD_TYPE.DESFireEV3: + treeViewParentNodes.Add( + new RFiDChipParentLayerViewModel( + new MifareDesfireChipModel(device.GenericChip as MifareDesfireChipModel), Dialogs, false)); + break; + + case CARD_TYPE.MifarePlus: + treeViewParentNodes.Add( + new RFiDChipParentLayerViewModel( + new MifareClassicChipModel(device.GenericChip as MifareClassicChipModel), Dialogs, false)); + break; + + case CARD_TYPE.MifareUltralight: + treeViewParentNodes.Add( + new RFiDChipParentLayerViewModel( + new MifareUltralightChipModel(device.GenericChip), Dialogs, false)); + break; + + default: + if(device.GenericChip?.CardType != CARD_TYPE.NOTAG) + { + treeViewParentNodes.Add( + new RFiDChipParentLayerViewModel( + new GenericChipModel(device.GenericChip), Dialogs, false)); + } + break; + } + // fill treeview with dummy models and viewmodels + } + else if (wellKnownTvNodes.Any()) + { + //wellKnownTvNodes.FirstOrDefault().IsExpanded = true; + wellKnownTvNodes.FirstOrDefault().IsSelected = true; } - // fill treeview with dummy models and viewmodels - } - else if (wellKnownTvNodes.Any()) - { - //wellKnownTvNodes.FirstOrDefault().IsExpanded = true; - wellKnownTvNodes.FirstOrDefault().IsSelected = true; } + } Mouse.OverrideCursor = null; @@ -1164,7 +1167,7 @@ private async Task OnNewWriteToChipOnceCommand() OnPropertyChanged(nameof(TreeViewParentNodes)); OnPropertyChanged(nameof(ChipTasks)); - var GenericChip = new GenericChipModel("", CARD_TYPE.NOTAG); + var GenericChip = ReaderDevice.Instance.GenericChip; //new GenericChipModel("", CARD_TYPE.NOTAG); currentTaskIndex = 0; var taskDictionary = new Dictionary(); @@ -1194,17 +1197,24 @@ private async Task OnNewWriteToChipOnceCommand() //reader was ready - proceed if (device != null) { - await device.ReadChipPublic(); + - if (device.GenericChip != null && device.GenericChip.Count > 0) + if (device.GenericChip != null && !string.IsNullOrEmpty(device.GenericChip.UID)) { - GenericChip = device.GenericChip[0]; - if (GenericChip.CardType.ToString().ToLower(CultureInfo.CurrentCulture).Contains("desfire")) { await device.GetMiFareDESFireChipAppIDs(); + + GenericChip = device.GenericChip; } } + + else + { + await device.ReadChipPublic(); + + GenericChip = device.GenericChip; + } } @@ -1659,12 +1669,17 @@ private async Task OnNewWriteToChipOnceCommand() try { - treeViewParentNodes.First(y => y.IsSelected).IsBeingProgrammed = null; - triggerReadChip.IsEnabled = (bool)triggerReadChip.Tag; - _runSelectedOnly = false; + if(treeViewParentNodes.Any(x => x.IsSelected) == true) + { + treeViewParentNodes.First(y => y.IsSelected).IsBeingProgrammed = null; + triggerReadChip.IsEnabled = (bool)triggerReadChip.Tag; + _runSelectedOnly = false; + } } - catch { } + catch { + // do nothing if no element found. this is intended on autorun, to speed up + } } @@ -2376,196 +2391,168 @@ private async void LoadCompleted(object sender, EventArgs e) checkUpdate = new Timer(CheckUpdate, null, 100, 5000); // ! UI-Thread ! checkReader = new Timer(CheckReader, null, 5000, 3000); // ! UI-Thread ! + var projectFileToUse = ""; + await InitOnFirstRun(projectFileToUse); - await Run(); - } - - private async Task Run() - { - if (firstRun) + using (var settings = new SettingsReaderWriter()) { - var projectFileToUse = ""; - - firstRun = false; - - try + if (args.Length > 1) { - using (var settings = new SettingsReaderWriter()) + foreach (var arg in args) { - await settings.ReadSettings(); + switch (arg.Split('=')[0]) + { + case "REPORTTARGETPATH": - settings.InitUpdateFile(); + variablesFromArgs.Add(arg.Split('=')[0], arg.Split('=')[1]); - if (args.Length > 1) - { - foreach (var arg in args) - { - switch (arg.Split('=')[0]) + if (Directory.Exists(Path.GetDirectoryName(arg.Split('=')[1]))) { + reportOutputPath = arg.Split('=')[1]; + var numbersInFileNames = new int[Directory.GetFiles(Path.GetDirectoryName(reportOutputPath)).Length]; - case "LASTUSEDPROJECTPATH": - if (File.Exists(arg.Split('=')[1])) + if (reportOutputPath.Contains("?")) + { + for (var i = 0; i < numbersInFileNames.Length; i++) { - settings.DefaultSpecification.LastUsedProjectPath = new DirectoryInfo(arg.Split('=')[1]).FullName; - await settings.SaveSettings(); + var fileName = Directory.GetFiles(Path.GetDirectoryName(reportOutputPath))[i]; + + if (fileName.Replace(".pdf", string.Empty).ToLower().Contains(reportOutputPath.ToLower().Replace("?", string.Empty).Replace(".pdf", string.Empty))) + { + _ = int.TryParse(fileName.ToLower().Replace( + reportOutputPath.ToLower().Replace("?", string.Empty).Replace(".pdf", string.Empty), string.Empty).Replace(".pdf", string.Empty), out var n); + numbersInFileNames[i] = n; + } } - break; + } - case "CUSTOMPROJECTFILE": + if (reportOutputPath.Contains("???")) + { + reportOutputPath = reportOutputPath.Replace("???", string.Format("{0:D3}", numbersInFileNames.Max() + 1)); + } - if (File.Exists(arg.Split('=')[1])) - { - projectFileToUse = new DirectoryInfo(arg.Split('=')[1]).FullName; - } - break; + else if (reportOutputPath.Contains("??")) + { + reportOutputPath = reportOutputPath.Replace("??", string.Format("{0:D2}", numbersInFileNames.Max() + 1)); + } - default: - break; + else if (reportOutputPath.Contains("?")) + { + reportOutputPath = reportOutputPath.Replace("?", string.Format("{0:D1}", numbersInFileNames.Max() + 1)); + } } - } - } + break; - CurrentReader = string.IsNullOrWhiteSpace(settings.DefaultSpecification.DefaultReaderName) - ? Enum.GetName(typeof(ReaderTypes), settings.DefaultSpecification.DefaultReaderProvider) - : settings.DefaultSpecification.DefaultReaderName; + case "REPORTTEMPLATEFILE": - if (int.TryParse(settings.DefaultSpecification.LastUsedComPort, out var portNumber)) - { - ReaderDevice.PortNumber = portNumber; - } + variablesFromArgs.Add(arg.Split('=')[0], arg.Split('=')[1]); - else - { - ReaderDevice.PortNumber = 0; - } - - culture = (settings.DefaultSpecification.DefaultLanguage == "german") ? new CultureInfo("de-DE") : new CultureInfo("en-US"); + if (File.Exists(arg.Split('=')[1])) + { + reportTemplateFile = arg.Split('=')[1]; + } + break; - var autoLoadLastUsedDB = settings.DefaultSpecification.AutoLoadProjectOnStart; + case "AUTORUN": + if (arg.Split('=')[1] == "1") + { + await OnNewReadChipCommand(); + await OnNewWriteToChipOnceCommand(); + } + break; - var mySplash = new SplashScreenViewModel(); + case "LASTUSEDPROJECTPATH": + if (File.Exists(arg.Split('=')[1])) + { + settings.DefaultSpecification.LastUsedProjectPath = new DirectoryInfo(arg.Split('=')[1]).FullName; + await settings.SaveSettings(); + } + break; - if (autoLoadLastUsedDB) - { - Dialogs.Add(mySplash); - } + case "CUSTOMPROJECTFILE": - if (autoLoadLastUsedDB) - { - if (string.IsNullOrEmpty(projectFileToUse)) - { - await OpenLastProjectFile(); - } - else - { - await OpenLastProjectFile(projectFileToUse); - } + if (File.Exists(arg.Split('=')[1])) + { + projectFileToUse = new DirectoryInfo(arg.Split('=')[1]).FullName; + } + break; + default: + if (arg.Split('=')[0].Contains("$")) + { + variablesFromArgs.Add(arg.Split('=')[0], arg.Split('=')[1]); + } + break; } - - - Task.Run(async () => - { - while (true) - { - await Task.Delay(300); - DateTimeStatusBar = string.Format("{0}", DateTime.Now); - } - }); - - await OnNewResetTaskStatusCommand(); } + } + } + } - using (var settings = new SettingsReaderWriter()) - { - if (args.Length > 1) - { - foreach (var arg in args) - { - switch (arg.Split('=')[0]) - { - case "REPORTTARGETPATH": - - variablesFromArgs.Add(arg.Split('=')[0], arg.Split('=')[1]); - - if (Directory.Exists(Path.GetDirectoryName(arg.Split('=')[1]))) - { - reportOutputPath = arg.Split('=')[1]; - var numbersInFileNames = new int[Directory.GetFiles(Path.GetDirectoryName(reportOutputPath)).Length]; - - if (reportOutputPath.Contains("?")) - { - for (var i = 0; i < numbersInFileNames.Length; i++) - { - var fileName = Directory.GetFiles(Path.GetDirectoryName(reportOutputPath))[i]; + private async Task InitOnFirstRun(string projectFileToUse) + { + try + { + using (var settings = new SettingsReaderWriter()) + { + await settings.ReadSettings(); - if (fileName.Replace(".pdf", string.Empty).ToLower().Contains(reportOutputPath.ToLower().Replace("?", string.Empty).Replace(".pdf", string.Empty))) - { - _ = int.TryParse(fileName.ToLower().Replace( - reportOutputPath.ToLower().Replace("?", string.Empty).Replace(".pdf", string.Empty), string.Empty).Replace(".pdf", string.Empty), out var n); - numbersInFileNames[i] = n; - } - } - } + settings.InitUpdateFile(); - if (reportOutputPath.Contains("???")) - { - reportOutputPath = reportOutputPath.Replace("???", string.Format("{0:D3}", numbersInFileNames.Max() + 1)); - } + CurrentReader = string.IsNullOrWhiteSpace(settings.DefaultSpecification.DefaultReaderName) + ? Enum.GetName(typeof(ReaderTypes), settings.DefaultSpecification.DefaultReaderProvider) + : settings.DefaultSpecification.DefaultReaderName; - else if (reportOutputPath.Contains("??")) - { - reportOutputPath = reportOutputPath.Replace("??", string.Format("{0:D2}", numbersInFileNames.Max() + 1)); - } + if (int.TryParse(settings.DefaultSpecification.LastUsedComPort, out var portNumber)) + { + ReaderDevice.PortNumber = portNumber; + } - else if (reportOutputPath.Contains("?")) - { - reportOutputPath = reportOutputPath.Replace("?", string.Format("{0:D1}", numbersInFileNames.Max() + 1)); - } - } - break; + else + { + ReaderDevice.PortNumber = 0; + } - case "REPORTTEMPLATEFILE": + culture = (settings.DefaultSpecification.DefaultLanguage == "german") ? new CultureInfo("de-DE") : new CultureInfo("en-US"); - variablesFromArgs.Add(arg.Split('=')[0], arg.Split('=')[1]); + var autoLoadLastUsedDB = settings.DefaultSpecification.AutoLoadProjectOnStart; - if (File.Exists(arg.Split('=')[1])) - { - reportTemplateFile = arg.Split('=')[1]; - } - break; + var mySplash = new SplashScreenViewModel(); - case "AUTORUN": - if (arg.Split('=')[1] == "1") - { - await OnNewWriteToChipOnceCommand(); - } - break; + if (autoLoadLastUsedDB) + { + Dialogs.Add(mySplash); + } - default: - if (arg.Split('=')[0].Contains("$")) - { - variablesFromArgs.Add(arg.Split('=')[0], arg.Split('=')[1]); - } - break; - } - } + if (autoLoadLastUsedDB) + { + if (string.IsNullOrEmpty(projectFileToUse)) + { + await OpenLastProjectFile(); } + else + { + await OpenLastProjectFile(projectFileToUse); + } + } - } - catch (Exception ex) - { - eventLog.WriteEntry(ex.Message, EventLogEntryType.Error); - } - using (var settings = new SettingsReaderWriter()) - { - if (settings.DefaultSpecification.AutoCheckForUpdates) + Task.Run(async () => { - updater?.StartMonitoring(); - } + while (true) + { + await Task.Delay(300); + DateTimeStatusBar = string.Format("{0}", DateTime.Now); + } + }); + + await OnNewResetTaskStatusCommand(); } } + catch (Exception ex) + { + eventLog.WriteEntry(ex.Message, EventLogEntryType.Error); + } } private async void CheckReader(object sender) diff --git a/RFiDGear/ViewModel/SetupViewModel.cs b/RFiDGear/ViewModel/SetupViewModel.cs index b7d5ee3..4b80ce5 100644 --- a/RFiDGear/ViewModel/SetupViewModel.cs +++ b/RFiDGear/ViewModel/SetupViewModel.cs @@ -70,10 +70,8 @@ private async Task ConnectToReader() { await UpdateReaderStatusCommand.ExecuteAsync(true); - //OnConnect?.Invoke(this); switch (SelectedReader) { - /* case ReaderTypes.PCSC: if (device != null) { @@ -83,14 +81,15 @@ private async Task ConnectToReader() device = new LibLogicalAccessProvider(SelectedReader); } - device.ReadChipPublic(); } else { device = new LibLogicalAccessProvider(SelectedReader); } + + await device.ReadChipPublic(); break; - */ + case ReaderTypes.Elatec: if (device != null) { @@ -105,13 +104,13 @@ private async Task ConnectToReader() { await device.ConnectAsync(); } - - var t = await device.ReadChipPublic(); } else { device = new ElatecNetProvider(); } + + await device.ReadChipPublic(); break; case ReaderTypes.None: @@ -119,7 +118,7 @@ private async Task ConnectToReader() break; } - if (device?.GenericChip?.Count > 0) + if (device?.GenericChip?.UID != null) { DefaultReader = Enum.GetName(typeof(ReaderTypes), SelectedReader); @@ -128,8 +127,8 @@ private async Task ConnectToReader() + "UID: {0} " + '\n' + "Type: {1}", - device.GenericChip[0].UID, - ResourceLoader.GetResource(string.Format("ENUM.CARD_TYPE.{0}", Enum.GetName(typeof(CARD_TYPE), device.GenericChip[0].CardType)))); + device.GenericChip.UID, + ResourceLoader.GetResource(string.Format("ENUM.CARD_TYPE.{0}", Enum.GetName(typeof(CARD_TYPE), device.GenericChip.CardType)))); } else diff --git a/RFiDGear/ViewModel/TaskSetupViewModels/CommonTaskViewModel.cs b/RFiDGear/ViewModel/TaskSetupViewModels/CommonTaskViewModel.cs index 499688d..8d24d42 100644 --- a/RFiDGear/ViewModel/TaskSetupViewModels/CommonTaskViewModel.cs +++ b/RFiDGear/ViewModel/TaskSetupViewModels/CommonTaskViewModel.cs @@ -958,7 +958,6 @@ private async Task OnNewWriteReportCommand(ReportReaderWriter _reportReaderWrite foreach (var checkpoint in Checkpoints) { - var hasVariable = false; var concatenate = false; @@ -1438,7 +1437,7 @@ private async Task OnNewCheckLogicConditionCommand(ObservableCollection OnNewCheckLogicConditionCommand(ObservableCollection /// /// - public IAsyncRelayCommand CheckChipType => new AsyncRelayCommand>((x) => OnNewCheckChipTypeCommand(x)); + public IAsyncRelayCommand CheckChipType => new AsyncRelayCommand((x) => OnNewCheckChipTypeCommand(x)); private async Task OnNewCheckChipTypeCommand() { return await OnNewCheckChipTypeCommand(null); } - private async Task OnNewCheckChipTypeCommand(List chipList) + private async Task OnNewCheckChipTypeCommand(GenericChipModel chipList) { CurrentTaskErrorLevel = ERROR.Empty; - List chipListToUse; + GenericChipModel chipToUse; using (var device = ReaderDevice.Instance) { @@ -346,17 +346,17 @@ private async Task OnNewCheckChipTypeCommand(List chipL if (chipList != null) { - chipListToUse = chipList; + chipToUse = chipList; } else { await device.ReadChipPublic(); - chipListToUse = device.GenericChip; + chipToUse = device.GenericChip; } if (((int)SelectedChipType | 0xF000) == 0xF000) // Do NOT Check for explicit Subtype e.g desfire ev1 >2k, 4k, 8k etc.< { - if (chipListToUse.Where(x => (CARD_TYPE)((int)x.CardType & 0xF000) == (CARD_TYPE)SelectedChipType).Any()) + if ((CARD_TYPE)((int)chipToUse.CardType & 0xF000) == (CARD_TYPE)SelectedChipType) { result = ERROR.NoError; } @@ -368,7 +368,7 @@ private async Task OnNewCheckChipTypeCommand(List chipL } else // Take explicit Type into account { - if (chipListToUse.Where(x => x.CardType == SelectedChipType).Any()) + if (chipToUse.CardType == SelectedChipType) { result = ERROR.NoError; } @@ -401,12 +401,12 @@ private async Task OnNewCheckChipTypeCommand(List chipL /// /// /// - public IAsyncRelayCommand CheckChipIsMultiTecChip => new AsyncRelayCommand>((x) => OnNewCheckChipIsMultiTecChipCommand(x)); - private async Task OnNewCheckChipIsMultiTecChipCommand(List chipList) + public IAsyncRelayCommand CheckChipIsMultiTecChip => new AsyncRelayCommand((x) => OnNewCheckChipIsMultiTecChipCommand(x)); + private async Task OnNewCheckChipIsMultiTecChipCommand(GenericChipModel chip) { CurrentTaskErrorLevel = ERROR.Empty; - List chipListToUse; + GenericChipModel chipToUse; using (var device = ReaderDevice.Instance) { @@ -414,18 +414,18 @@ private async Task OnNewCheckChipIsMultiTecChipCommand(List= 1) + if (chipToUse != null && chipToUse.HasChilds == true) { result = ERROR.NoError; } @@ -470,9 +470,7 @@ private async Task OnNewCheckChipUIDCommand() if (result == ERROR.NoError) { - if (device.GenericChip - .Where(x => x.UID.ToLower(CultureInfo.CurrentCulture) == SelectedUIDOfChip.ToLower(CultureInfo.CurrentCulture)) - .Any()) + if (device.GenericChip.UID.ToLower(CultureInfo.CurrentCulture) == SelectedUIDOfChip.ToLower(CultureInfo.CurrentCulture)) { result = ERROR.NoError; } diff --git a/RFiDGearBundleSetup/Bundle.wxs b/RFiDGearBundleSetup/Bundle.wxs index 10841b3..eefe582 100644 --- a/RFiDGearBundleSetup/Bundle.wxs +++ b/RFiDGearBundleSetup/Bundle.wxs @@ -2,31 +2,31 @@ - + - - + + - + - + - + - - + + @@ -100,25 +100,41 @@ - + - - - + + + + + - + \ No newline at end of file diff --git a/RFiDGearBundleSetup/RFiDGearBundleSetup.wixproj b/RFiDGearBundleSetup/RFiDGearBundleSetup.wixproj index 6ec92a8..f36c4fd 100644 --- a/RFiDGearBundleSetup/RFiDGearBundleSetup.wixproj +++ b/RFiDGearBundleSetup/RFiDGearBundleSetup.wixproj @@ -20,6 +20,7 @@ + diff --git a/Setup/Product.wxs b/Setup/Product.wxs index c2cc1ec..9aaa6b8 100644 --- a/Setup/Product.wxs +++ b/Setup/Product.wxs @@ -186,6 +186,9 @@ + + + @@ -195,15 +198,27 @@ + + + + + + + + + - + + + + @@ -240,12 +255,19 @@ + + + + + + + @@ -357,12 +379,17 @@ + + - + + + + @@ -374,9 +401,11 @@ + + diff --git a/debugParam.txt b/debugParam.txt index d98b10a..944239b 100644 --- a/debugParam.txt +++ b/debugParam.txt @@ -1 +1,3 @@ -#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" $JOBNUMBER="KP-000005" $CHIPNUMBER="5" AUTORUN=1 \ No newline at end of file +#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" $JOBNUMBER="KP-000005" $CHIPNUMBER="5" AUTORUN=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_FreeMem.rfPrj" $JOBNUMBER="KP-000005" $CHIPNUMBER="5" AUTORUN=1 \ No newline at end of file