/// <summary> /// Проверяет, действительна ли лицензия. /// Это включает проверку подписи на ней, /// а также сроков ее действия. /// </summary> /// <param name="license">Лицензия</param> /// <returns>true если лицензия действительна. Иначе false.</returns> public bool IsValid(LicenseInfo license) { if (license == null) throw new ArgumentNullException("license cannot be null"); try { RSACryptoServiceProvider rsa = new RSACryptoServiceProvider(); rsa.ImportParameters(_publicKey); if (!rsa.VerifyData( GetBytesToSign(license), "SHA1", license.Signature ) ) return false; if (!(license.IssueDate <= DateTime.Now && DateTime.Now <= license.IssueDate + license.Duration) ) return false; } catch { return false; } return true; }
/// <summary> /// Конструктор класса, должен будет принимать в параметрах объект новой лицензии /// </summary> public ChangeLicenseAction(LicenseInfo aLicenseInfo) { if (aLicenseInfo == null) throw new ArgumentNullException("aLicenseInfo"); license = aLicenseInfo; }
/// <summary> /// Точка входа в программу. /// </summary> /// <param name="args">Аргументы: /// 1. Имя xml-файла с закрытым ключом. /// 2. Имя клиента. /// 3. E-mail клиента. /// 4. Дата выдачи лицензии. /// 5. Длительность лицензии. /// 6. Количество компьютеров. /// </param> static int Main(string[] args) { if (args.Length > 0 && args[0].Equals("-p")) return GenerateKey(args); if (args.Length < 6) return 1; FileStream fs = new FileStream(args[0], FileMode.Open); StreamReader sr = new StreamReader(fs); StringBuilder xmlkey = new StringBuilder(""); string s; while( (s = sr.ReadLine()) != null ) { xmlkey.AppendLine(s); } RSACryptoServiceProvider rsa = new RSACryptoServiceProvider(); rsa.FromXmlString(xmlkey.ToString()); LicenseInfo license = new LicenseInfo(); license.Name = args[1]; license.Email = args[2]; license.IssueDate = DateTime.Parse(args[3]); license.Duration = TimeSpan.FromDays(double.Parse(args[4])); license.Computers = int.Parse(args[5]); license.Sign(rsa.ExportParameters(true)); Console.Out.WriteLine(license.ToString()); return 0; }
public void InitTest() { license = new LicenseInfo(); license.Name = "J Random Hacker"; license.Email = "*****@*****.**"; license.IssueDate = DateTime.Now - TimeSpan.FromDays(1); license.Duration = TimeSpan.FromDays(10); license.Computers = 100; }
/// <summary> /// Обновление кеша. /// </summary> protected internal void UpdateData(bool updateDevices) { bool isDriverLoaded; long driverVersion; LicenseInfo license; List<IDevice> devices = null; List<DeviceProxy> addedDevices = null; List<DeviceProxy> removedDevices = null; // Получаем новые данные try { _computer.Context.PushContext(); lock (_hostSync) { if (_host == null) return; isDriverLoaded = _host.IsDriverLoaded; driverVersion = _host.DriverVersion; license = _host.License; if (updateDevices) { devices = new List<IDevice>(_host.GetDevices()); addedDevices = new List<DeviceProxy>(); removedDevices = new List<DeviceProxy>(); } } bool propertyChanged = false; lock (this) { // Проверяем, изменились ли свойства. if (_cachedIsDriverLoaded != isDriverLoaded || _cachedDriverVersion != driverVersion || _cachedLicense != license) { propertyChanged = true; //Обновляем данные кеша. _cachedIsDriverLoaded = isDriverLoaded; _cachedDriverVersion = driverVersion; _cachedLicense = license; } if (updateDevices) { #region Определение списков новых и старых устройств // Добавляем новые устройства, которых нет в старом списке. foreach (IDevice device in devices) if (!_deviceProxies.Exists( delegate(DeviceProxy devProxy) { return devProxy.IsBoundTo(device); })) { DeviceProxy devProxy = new DeviceProxy(_computer, this, device); _deviceProxies.Add(devProxy); addedDevices.Add(devProxy); } // Удаляем исчезнувшие устройства. _deviceProxies.RemoveAll( delegate(DeviceProxy devProxy) { if( !devices.Exists( delegate(IDevice device) { return devProxy.IsBoundTo(device); }) ) { removedDevices.Add(devProxy); return true; } return false; } ); #endregion } } // lock // Оповещаем слушателей об изменениях. if (propertyChanged) OnPropertyChanged(new HostEventArgs()); if (updateDevices) { foreach (DeviceProxy devProxy in addedDevices) OnDeviceAdded(new HostEventArgs(devProxy)); foreach (DeviceProxy devProxy in removedDevices) OnDeviceRemoved(new HostEventArgs(devProxy)); // Обновляем данные устройств. List<DeviceProxy> deviceProxies = new List<DeviceProxy>(); lock (this) { deviceProxies.AddRange(_deviceProxies); } foreach (DeviceProxy devProxy in deviceProxies) devProxy.UpdateData(); } } catch (System.Security.SecurityException) { } catch (System.Runtime.Remoting.RemotingException) { _computer.OnDisconnect(); return; } catch (System.Net.Sockets.SocketException) { _computer.OnDisconnect(); return; } finally { _computer.Context.PopContext(); } }
private void SetLicense(LicenseInfo license) { if (license == null) { lock (this) { InvalidLicense(); _license = null; _licensor.IsMonitoring = false; _isValid = false; return; } } lock (this) { if (!_validator.IsValid(license)) { InvalidLicense(); throw new System.ComponentModel.LicenseException( typeof(Service) ); } _license = license; _isValid = true; _licensor.Key = Encoding.ASCII.GetBytes( _license.GetHashCode().ToString() ); _licensor.MaxComputers = _license.Computers; _licensor.IsMonitoring = true; } }
/// <summary> /// Возвращает представление лицензии /// в виде массива байт. /// Подпись в них не входит. /// </summary> /// <returns></returns> private byte[] GetBytesToSign(LicenseInfo license) { return Encoding.UTF8.GetBytes(license.GetMessage()); }
public object Clone() { LicenseInfo license = new LicenseInfo(); license._name = this._name; license._email = this._email; license._issueDate = this._issueDate; license._duration = this._duration; license._computers = this._computers; license._signature = this._signature; return license; }
/// <summary> /// Проверяет, является ли данная строка /// корректной строкой лицензии. /// </summary> /// <param name="licenseString"></param> /// <returns></returns> public static bool IsCorrect(string licenseString) { try { LicenseInfo license = new LicenseInfo(licenseString); } catch { return false; } return true; }