private void SetLicense() { using (Stream license = new FileStream(_config.LisansXmlPath, FileMode.Open, FileAccess.Read)) { LicenseUtil.setLicenseXml(license); } }
public void Can_push_transition_to_license_with_new_apikey_via_update_license() { var old = LicenseUtil.GenerateLicense(_oldApikeyLicenseArgs); var eventSubscriber = new XUri("mock://event/subscriber"); var subForAuthorized = new XDoc("subscription-set") .Elem("uri.owner", eventSubscriber) .Start("subscription") .Attr("id", "1") .Elem("channel", "event://default/deki/site/license/update") .Start("recipient") .Attr("authtoken", Utils.Settings.ApiKey) .Elem("uri", eventSubscriber) .End() .End(); var result = Utils.Settings.Server.At("pubsub", "subscribers").With("apikey", Utils.Settings.ApiKey).PostAsync(subForAuthorized).Wait(); Assert.IsTrue(result.IsSuccessful); MockPlug.Setup(eventSubscriber).Verb("POST").WithMessage(msg => { var doc = msg.ToDocument(); _log.Debug("transition doc:\r\n" + doc.ToPrettyString()); return("COMMERCIAL".EqualsInvariantIgnoreCase(doc["previous-license/@state"].AsText) && "COMMERCIAL".EqualsInvariantIgnoreCase(doc["new-license/@state"].AsText)); }).ExpectCalls(Times.Once()); var licenses = new XDoc("licenses") .Start("old-license").Add(old).End() .Start("new-license").Add(LicenseUtil.TestLicense); var response = Utils.Settings.Server.At("license") .With("apikey", Utils.Settings.ApiKey) .Put(licenses, new Result <DreamMessage>()) .Wait(); Assert.AreEqual(DreamStatus.Ok, response.Status, "unable to update license"); MockPlug.VerifyAll(10.Seconds()); }
public LandConflictDetectionMain() { if (!ESRI.ArcGIS.RuntimeManager.Bind(ProductCode.EngineOrDesktop)) { LOG.Error("arcgis license init error"); throw new Exception("arcgis license init error"); } LicenseUtil.CheckOutLicenseAdvanced(); // 初始化输入参数 base.InputParametersMeta.Add(nameof(this.FeatureClass_Source_First), new Property(nameof(this.FeatureClass_Source_First), "总规用地的图层信息", Base.Common.EnumValueMetaType.TYPE_MDB_FEATURECLASS, "", "", "总规用地的图层信息,格式:mdb路径" + SEPARATOR_FEATURE_PATH + "要素类名称", null)); base.InputParametersMeta.Add(nameof(this.FeatureClass_Source_Second), new Property(nameof(this.FeatureClass_Source_Second), "控规用地的图层信息", Base.Common.EnumValueMetaType.TYPE_MDB_FEATURECLASS, "", "", "控规用地的图层路径信息,格式:mdb路径" + SEPARATOR_FEATURE_PATH + "要素类名称", null)); base.InputParametersMeta.Add(nameof(this.Yddm_First), new Property(nameof(this.Yddm_First), "总规用地代码属性", Base.Common.EnumValueMetaType.TYPE_STRING, "", "", "总规用地代码属性", null)); base.InputParametersMeta.Add(nameof(this.Yddm_Second), new Property(nameof(this.Yddm_Second), "控规用地代码属性", Base.Common.EnumValueMetaType.TYPE_STRING, "", "", "控规用地代码属性", null)); // 初始化输出参数 string resultGDBDir = System.AppDomain.CurrentDomain.BaseDirectory + "/result/"; base.OutputParametersMeta.Add(nameof(this.ResultGDBPath), new Property(nameof(this.ResultGDBPath), "输出结果", Base.Common.EnumValueMetaType.TYPE_GDB_PATH, resultGDBDir, resultGDBDir, "分析结果为gdb文件", null)); base.OutputParametersMeta.Add(nameof(this.ReulstLayerName), new Property(nameof(this.ReulstLayerName), "图层名称", Base.Common.EnumValueMetaType.TYPE_STRING, this.ReulstLayerName, this.ReulstLayerName, "分析结果为gdb文件", null)); }
public LicenseEditorViewModel() { // Calcolo e setto il numero di serie hardware _giornale.Debug("calcolo Machine Code"); machineCode = LicenseUtil.getMachineCode(); _giornale.Info("Machine Code = " + machineCode); // Carico il codice di licenza (eventuale) dal registry codiceLicenza = LicenseUtil.readCurrentLicenseKey(); _giornale.Info("caricato cod. licenza = " + codiceLicenza); validareLicenza(codiceLicenza, false); }
void caricaDatiLicenza() { registryLicense = LicenseUtil.createCurrentLicense(); if (haveValidLicense) { _giornale.Info("Caricata licenza ed è valida"); } else { _giornale.Warn("Licenza non valida"); } }
//private static bool freeLicenseLoaded = false; //private static bool testLicenseLoaded = false; //public static void loadFreeLicense() //{ // if(freeLicenseLoaded) // return; // string currentDirectory = Directory.GetCurrentDirectory(); // string lisansFilePath = currentDirectory + "\\lisans\\lisansFree.xml"; // LicenseUtil.setLicenseXml(new FileStream(lisansFilePath, FileMode.Open, FileAccess.Read)); // freeLicenseLoaded = true; //} public static void loadLicense() { // logger.Debug("License is being loaded from: " + LICENSE); LicenseUtil.setLicenseXml(new FileStream(@"lisans\Full_lisans.xml", FileMode.Open, FileAccess.Read)); //var assembly = Assembly.GetExecutingAssembly(); //var resourceName = "global::ESigner.Properties.Resources.Full_lisans.xml"; //Stream stream = assembly.GetManifestResourceStream(resourceName); //StreamReader reader = new StreamReader(stream); ////{ //// string result = reader.ReadToEnd(); ////} //LicenseUtil.setLicenseXml(stream); }
public void Bad_license_prevents_instance_from_starting_up() { Assert.AreEqual(0, Utils.Settings.Server.At("host").With("apikey", Utils.Settings.ApiKey).Get().ToDocument()["tenant"].ListLength); File.Delete(Utils.Settings.LicensePath); var community = LicenseUtil.GenerateLicense(_communityLicenseArgs); community.Save(Utils.Settings.LicensePath); _log.InfoFormat("--- wrote community license to {0}", Utils.Settings.LicensePath); RemoteInstanceService.Instance.LicenseOverride = _ => community; Assert.IsFalse(Utils.Settings.Server.At("site", "settings").Get(new Result <DreamMessage>()).Wait().IsSuccessful); var tenants = Utils.Settings.Server.At("host").With("apikey", Utils.Settings.ApiKey).Get().ToDocument(); _log.Info("tenants:\r\n" + tenants.ToPrettyString()); var tenant = tenants["tenant"]; Assert.AreEqual(1, tenant.ListLength); Assert.AreEqual("abandoned", tenant["@status"].AsText); }
static void Main() { LicenseUtil utilities = new LicenseUtil(); var license = utilities.Read("License"); license = "Electronic Store"; if (StringComparer.OrdinalIgnoreCase.Equals(license, "Electronic Store")) { Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); Application.Run(new MDI()); } else { MessageBox.Show("Bạn không có quyền sử dụng chương trình này."); Application.Exit(); } }
public void Local_license_expiring_after_startup_affects_license_state_in_settings() { var p = Utils.BuildPlugForAdmin(); var tenants = Utils.Settings.Server.At("host").With("apikey", Utils.Settings.ApiKey).Get().ToDocument(); _log.Info("tenants:\r\n" + tenants.ToPrettyString()); Assert.AreEqual(1, tenants["tenant[@wikiid='default']"].ListLength); try { var expired = LicenseUtil.GenerateLicense(_expiredLicenseArgs); RemoteInstanceService.Instance.LicenseOverride = _ => expired; LicenseManager.LicenseCheckInterval = 0; File.Delete(Utils.Settings.LicensePath); expired.Save(Utils.Settings.LicensePath); _log.Debug("---- forcing license check"); var settings = p.At("site", "settings").With("apikey", Utils.Settings.ApiKey).Get(); Assert.AreEqual(DreamStatus.Ok, settings.Status, "unable to retrieve settings"); Assert.AreEqual("EXPIRED", settings.ToDocument()["license/state"].AsText); } finally { LicenseManager.LicenseCheckInterval = LicenseManager.LICENSE_CHECK_INTERVAL; } }
private void btnGenerateMachineCode_Click(object sender, EventArgs e) { try { this.SetUIEnable(false); StringBuilder stringBuilder = new StringBuilder(); byte[] bytes = LicenseUtil.ByteConvertor.GetBytes(LicenseUtil.SystemInfo); LicenseUtil.GetStringFromByte(bytes); string str = Convert.ToBase64String(bytes); stringBuilder.Append(str); this.MachineCode.Text = stringBuilder.ToString(); } catch (Exception ex) { int num = (int)MessageBox.Show(ex.ToString(), "错误"); } finally { this.SetUIEnable(true); } }
public OverlayMain() { if (!ESRI.ArcGIS.RuntimeManager.Bind(ProductCode.EngineOrDesktop)) { LOG.Error("arcgis license init error"); throw new Exception("arcgis license init error"); } LicenseUtil.CheckOutLicenseAdvanced(); // 初始化输入参数 base.InputParametersMeta.Add(nameof(this.SourceFeatureClass), new Property(nameof(this.SourceFeatureClass), "源要素类,叠加的图层", EnumValueMetaType.TYPE_FEATURECLASS, new InputFeatureClassDTO(), new InputFeatureClassDTO(), "源要素类,叠加的图层", null)); base.InputParametersMeta.Add(nameof(this.TargetFeatureClass), new Property(nameof(this.TargetFeatureClass), "目标要素类,被叠加的图层", EnumValueMetaType.TYPE_FEATURECLASS, new InputFeatureClassDTO(), new InputFeatureClassDTO(), "目标要素类,被叠加的图层", null)); base.InputParametersMeta.Add(nameof(this.AnalysisType), new Property(nameof(this.AnalysisType), "分析类型", EnumValueMetaType.TYPE_INTEGER, null, (int)AnalysisType.COVER, "分析类型选择", new object[] { new Property(nameof(AnalysisType.COVER), EnumUtil.GetEnumDescription(AnalysisType.COVER), EnumValueMetaType.TYPE_INTEGER, (int)AnalysisType.COVER, null, EnumUtil.GetEnumDescription(AnalysisType.COVER)), new Property(nameof(AnalysisType.OVERTOP), EnumUtil.GetEnumDescription(AnalysisType.OVERTOP), EnumValueMetaType.TYPE_INTEGER, (int)AnalysisType.OVERTOP, null, EnumUtil.GetEnumDescription(AnalysisType.OVERTOP)) })); base.InputParametersMeta.Add(nameof(IsClearTemp), new Property(nameof(IsClearTemp), nameof(IsClearTemp), EnumValueMetaType.TYPE_BOOLEAN, false, false, "是否清理临时目录或文件", new object[] { true, false })); // 指定输出参数类型 base.OutputParametersMeta.Add(nameof(Result), new Property(nameof(Result), "输出结果", EnumValueMetaType.TYPE_JSON, null, null, "输出结果,json格式", null, 1, 1)); }
//private static readonly ILog logger = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); public static void loadLicense() { ublSigner.LOGGER.Debug("License is being loaded from: " + Conn.ROOT_DIR + "efatura\\lisans\\BES_lisans.xml"); LicenseUtil.setLicenseXml(new FileStream(Conn.ROOT_DIR + "efatura\\lisans/BES_lisans.xml", FileMode.Open, FileAccess.Read)); }
/// <summary> /// /// </summary> /// <param name="signedXml">İmzası kontrol edilecek XML içeriği</param> /// <param name="unQaulifiedDigestAlgoritmList">Geçersiz signature.SignedInfo.SignatureMethod.Url /// <example>http://www.w3.org/2000/09/xmldsig#sha1</example></param> /// <param name="checkForEnvelopedSignature">Eğer true set edilirse İmzanın Enveloped yapısında olduğu kontrolü yapılır. Envelped yapısına olmayan İmzalarda Doğrulama sonucu başarısız döner.</param> /// <returns></returns> public static SignedDocumentValidationResult ValidateSignatureFromXml(string signedXml) { LicenseUtil.setLicenseXml(new MemoryStream(System.IO.File.ReadAllBytes(System.AppDomain.CurrentDomain.BaseDirectory + "/SignatureValidationConfig/Lisans/lisans.xml"))); var context = new Context(); context.Config = new tr.gov.tubitak.uekae.esya.api.xmlsignature.config.Config(System.AppDomain.CurrentDomain.BaseDirectory + "/SignatureValidationConfig/xmlsignature-config.xml"); var file = System.IO.Path.GetTempFileName(); System.IO.File.WriteAllText(file, signedXml); var sdvr = new SignedDocumentValidationResult(); var signature = XMLSignature.parse(new FileDocument(new FileInfo(file)), context); var result = signature.verify(); try { System.IO.File.Delete(file); } finally { } sdvr.Certificate = signature.SigningCertificate.asX509Certificate2(); sdvr.CertificateValidationResult = new CertificateValidationResult(); sdvr.SignatureInfo = new SignatureInfo(); sdvr.SignatureInfo.SigningTime = signature.SigningTime; sdvr.CertificateValidationResult.ValidationResultList = new List <SignatureValidator.DataTransferObject.ValidationResult>(); // var nodeList = signature.Document.GetElementsByTagName("UBLVersionID", "urn:oasis:names:specification:ubl:schema:xsd:CommonBasicComponents-2"); if (nodeList != null && nodeList.Count > 0) { sdvr.SignatureInfo.UBLVersionID = nodeList.Item(0).InnerText; } if (context.ValidationResult != null && context.ValidationResult.getDetails() != null) { foreach (var item in context.ValidationResult.getDetails()) { var vr = new SignatureValidator.DataTransferObject.ValidationResult(); vr.Successful = item.isSuccessful(); vr.Result = vr.Successful ? tr.gov.tubitak.uekae.esya.api.signature.ValidationResultType.VALID.ToString() : tr.gov.tubitak.uekae.esya.api.signature.ValidationResultType.INVALID.ToString(); vr.CheckText = item.getCheckText(); vr.ResultText = item.getResultText(); sdvr.CertificateValidationResult.ValidationResultList.Add(vr); } sdvr.CertificateValidationResult.Successful = !sdvr.CertificateValidationResult.ValidationResultList.Exists(x => x.Successful.Equals(false)); } sdvr.SignatureValidationResult = new SignatureValidator.DataTransferObject.SignatureValidationResult(); sdvr.SignatureValidationResult.Successful = result.getResultType() == tr.gov.tubitak.uekae.esya.api.signature.ValidationResultType.VALID; sdvr.SignatureValidationResult.ResultText = result.getMessage() + Environment.NewLine + result.getResultType(); sdvr.SignatureValidationResult.ValidationResultList = new List <SignatureValidator.DataTransferObject.ValidationResult>(); foreach (var item in result.getDetails <tr.gov.tubitak.uekae.esya.api.xmlsignature.ValidationResult>()) { var vr = new SignatureValidator.DataTransferObject.ValidationResult(); vr.Successful = item.getResultType() == tr.gov.tubitak.uekae.esya.api.signature.ValidationResultType.VALID; vr.Result = item.getResultType().ToString(); vr.CheckText = item.getCheckMessage(); vr.ResultText = item.getCheckResult(); sdvr.SignatureValidationResult.ValidationResultList.Add(vr); } return(sdvr); }
public void setLicenseXmlWithPassword(System.IO.FileStream FileStream, string password) { LicenseUtil.setLicenseXml(FileStream, password); }
public bool setLicenseXml(System.IO.FileStream FileStream) { return(LicenseUtil.setLicenseXml(FileStream)); }
public PdfSigner() { LicenseUtil.setLicenseXml(new FileStream(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "lisans.xml"), FileMode.Open, FileAccess.Read)); }
public static bool CheckLicense(string licenseFilePath, out string message) { const string PublicKey = "<RSAKeyValue><Modulus>r+Fknz/UEsPyB+rOJpRt6BLPUnPvYFEAuXFtL6x23NI7LrUf+Xvcfo1iPMMJruOdNPs+wYNpxNy1166n5mRuSLn7EPbt1aumfCmtgq150NDWWdmx1y5rHNGFu9sUSUm+EgNEgVNbrjTTq8ru7ZJU2X5CLuLMYevuXwBaLZoS8kk=</Modulus><Exponent>AQAB</Exponent></RSAKeyValue>"; try { message = ""; #region 许可过滤(不存在、不合法、空) if (!File.Exists(licenseFilePath)) { message = "许可文件不存在!"; return(false); } //.lic结尾的文件 Path.GetExtension(licenseFilePath).Trim().ToUpper(); if (!Path.GetExtension(licenseFilePath).Trim().ToUpper().Equals(LicenseUtil.DefaultLicenseFileExtension.ToUpper())) { message = "指定的许可文件不合法!"; return(false); } string s = LicenseUtil.ReadContentFromFile2(licenseFilePath); if (string.IsNullOrEmpty(s)) { message = "许可内容为空!"; return(false); } #endregion #region 对许可解密获取时间信息(fromDate,toDate,lastDate) DateTime fromDate; DateTime toDate; DateTime lastDate; LicenseUtil.ReadDateTiFromFile(licenseFilePath, out fromDate, out toDate, out lastDate); #endregion #region 许可使用的注册表判断 bool flag1 = false; //注册表信息控制器 string str1 = ""; string str2 = ""; if (lastDate == fromDate) //如果起始时间等于最后时间 { try { //检索 SOFTWARE\\PrivateCMW\\TimeLimitKey,是否在当前用户的注册表中,不将写访问权限应用于该项。 using (RegistryKey registryKey = Registry.CurrentUser.OpenSubKey("SOFTWARE\\PrivateCMW\\TimeLimitKey", false)) { //如果是空的话,注册表信息控制值为true if (registryKey == null) { flag1 = true; } else { //如果不为空,则检索注册表中与指定名称关联的值 str1 = registryKey.GetValue("Start").ToString(); str2 = registryKey.GetValue("End").ToString(); //判断两个值中是否包含 fromDate 和 toDate 两个值 //如果包含了这两个值,则判断许可已经使用 if (str1.Contains(fromDate.ToString()) && str2.Contains(toDate.ToShortDateString())) { message = "许可已使用!"; return(false); } //如果不包含 fromDate 和 toDate ,则返回true flag1 = true; } } } catch (Exception) { message = "验证注册表失败"; } } #endregion #region 许可使用的时间期限判断 /* * fromDate(授权许可开始的时间) * toDate(授权许可结束的时间) * lastDate(授权许可最后一次生效的时间) * * DataTime.Now < lastData(现在的时间 小于 授权许可最后一次生效的时间) * lastDate < fromDate(授权许可最后一次生效的时间 小于 授权许可开始的时间) * lastDate > toDate(授权许可最后一次生效的时间 大于 授权许可结束的时间) * DateTime.Now < fromDate(现在的时间 小于 授权许可开始的时间) * DateTime.Now > toDate(现在的时间 大于 授权许可结束的时间) * */ if (DateTime.Now < lastDate || lastDate < fromDate || (lastDate > toDate || DateTime.Now < fromDate) || DateTime.Now > toDate) { message = "许可已经过期!"; return(false); } #endregion #region 加密算法验证许可文件 //创建一个 RSA不对称加密解密算法 对象 RSACryptoServiceProvider cryptoServiceProvider = new RSACryptoServiceProvider(); //XML字符串中的密钥信息(包含公钥或者包含公钥和私钥): //<RSAKeyValue><Modulus>uqYMs9AxuAfGsbVvo+ah8Z7c91qbYJ8ARbX/7585ZVH1Jl9V5ebnjUEv+cuMjDEYzMCbJujoKZbqSRD5X5f9I2b9lNhRBhvBNBJj6ntzYKYp7HxYGTOr5NQ+eqNUejPhv9+fGedNa1oe/KyyfvE//NshoUN/oxVvCMlBIgHS98s=</Modulus><Exponent>AQAB</Exponent></RSAKeyValue> /* PEM格式公钥 * -----BEGIN PUBLIC KEY----- * MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQC6pgyz0DG4B8axtW+j5qHxntz3 * WptgnwBFtf/vnzllUfUmX1Xl5ueNQS/5y4yMMRjMwJsm6OgplupJEPlfl/0jZv2U * 2FEGG8E0EmPqe3NgpinsfFgZM6vk1D56o1R6M+G/358Z501rWh78rLJ+8T/82yGh * Q3+jFW8IyUEiAdL3ywIDAQAB * -----END PUBLIC KEY----- */ //初始化 RSA不对称加密解密算法 cryptoServiceProvider.FromXmlString(PublicKey); bool flag2; try { //将字符编码转为一个UTF-16格式的字节序列 byte[] bytes = LicenseUtil.ByteConvertor.GetBytes(LicenseUtil.SystemInfo); //打开许可文件,读取第一行的秘钥信息(s),通过Base64算法解密 byte[] signature = Convert.FromBase64String(s); //传入字符序列,SHA1加密算法的哈希值,Base64的解密信息进行验证 /* * VerifyData(buffer, halg, signature) * 通过使用提供的公钥计算签名中的哈希值,然后将其与提供的数据的哈希值进行比较,从而验证数字签名是否有效。 * * 返回值: * 如果签名有效,则为 true;否则为 false。 * * 参数: * buffer * Type: Byte[] * 已签名的数据。 * * halg * Type: Object * 用于创建数据哈希值的哈希算法的名称。 * * signature * Type: System.Byte[] * 要验证的签名数据。 * */ flag2 = cryptoServiceProvider.VerifyData(bytes, (object)LicenseUtil.DefaultHashAlgorithm, signature); } catch { message = "许可文件验证错误!"; return(false); } #endregion #region 注册表和许可文件更新 //加密解密算法验证通过 if (flag2) { //注册表验证通过 if (flag1) { //检索注册表 SOFTWARE\\PrivateCMW\\TimeLimitKey,并支持写入操作 using (RegistryKey registryKey = Registry.CurrentUser.OpenSubKey("SOFTWARE\\PrivateCMW\\TimeLimitKey", true)) { //如果注册表为空 if (registryKey == null) { //创建注册表信息 using (RegistryKey subKey = Registry.CurrentUser.CreateSubKey("SOFTWARE\\PrivateCMW\\TimeLimitKey")) { //写入许可开始时间 subKey.SetValue("Start", (object)fromDate.ToString()); //写入许可结束时间 subKey.SetValue("End", (object)toDate.ToShortDateString()); } } else { //如果不为空 //追加新的许可开始时间和结束时间 registryKey.SetValue("Start", (object)(str1 + ";" + fromDate.ToString())); registryKey.SetValue("End", (object)(str2 + ";" + toDate.ToShortDateString())); } } } // LicenseUtil.UpdateDateToFile(licenseFilePath, DateTime.Now); } else { message = "许可文件验证不通过!"; } return(flag2); #endregion } catch { message = "许可文件可能被篡改!"; return(false); } }
private void btnSaveLicense_Click(object sender, EventArgs e) { LicenseUtil.SaveFile(this.LicenseCode.Text.Replace("\n", Environment.NewLine), ".lic", "License(*.lic)|*.lic"); }
private void btnSaveMachineCode_Click(object sender, EventArgs e) { LicenseUtil.SaveFile(this.MachineCode.Text.Replace("\n", Environment.NewLine), ".txt", "文本文件(*.txt)|*.txt"); }