public List <string> GenerateLicenseKeys(string rsaXmlString, LicenseBase scutexLicense, LicenseGenerationOptions generationOptions, int count) { HashSet <string> licenses = new HashSet <string>(); int doupCount = 0; while (licenses.Count < count) { string key = GenerateLicenseKey(rsaXmlString, scutexLicense, generationOptions); if (licenses.Contains(key) == false) { licenses.Add(key); //Debug.WriteLine(string.Format("{0} of {1} keys generated", licenses.Count, count)); } else { doupCount++; Debug.WriteLine(string.Format("Duplicate key was generated {0}", key)); } } if (doupCount > 0) { Debug.WriteLine(string.Format("{0} duplicate keys were generated at a {1}% chance", doupCount, doupCount * 100m / count)); } return(licenses.ToList()); }
private bool ValidateKey(string licenseKey, LicenseBase scutexLicense) { if (licenseKey.Length == 15) { return(keyGenerator.ValidateLicenseKey(licenseKey, scutexLicense)); } else { return(_largeKeyGenerator.ValidateLicenseKey(licenseKey, scutexLicense)); } }
private KeyData GetKeyData(string licenseKey, LicenseBase scutexLicense) { if (licenseKey.Length == 15) { return(keyGenerator.GetLicenseKeyData(licenseKey, scutexLicense)); } else { return(_largeKeyGenerator.GetLicenseKeyData(licenseKey, scutexLicense)); } }
public string GenerateLicenseKey(string rsaXmlString, LicenseBase scutexLicense, LicenseGenerationOptions generationOptions) { if (generationOptions.GeneratorType == KeyGeneratorTypes.StaticSmall) { return(keyGenerator.GenerateLicenseKey(rsaXmlString, scutexLicense, generationOptions)); } else { return(_largeKeyGenerator.GenerateLicenseKey(rsaXmlString, scutexLicense, generationOptions)); } }
private void btnParseKey_Click(object sender, System.EventArgs e) { LicenseBase licenseBase = new LicenseBase(); try { licenseBase.LicenseKey = tbKey.Text; SetKeyNumber(licenseBase); switch (licenseBase.LicenseObject.Type) { case LicenseType.LicenseTypes.Trial: cbLicenseType.SelectedIndex = 0; calDate.SelectionStart = licenseBase.ExpiryDate.LicenseDateTime; break; case LicenseType.LicenseTypes.Full: cbLicenseType.SelectedIndex = 1; calDate.SelectionStart = licenseBase.RegistrationDate.LicenseDateTime; break; case LicenseType.LicenseTypes.Invalid: cbLicenseType.SelectedIndex = 2; break; case LicenseType.LicenseTypes.None: cbLicenseType.SelectedIndex = 3; break; default: throw new Exception("Key parsing error"); } } catch (Exception ex) { MessageBox.Show(ex.Message); } switch (licenseBase.ProductObject.ProductCode) { case Product.Products.None: cbProduct.SelectedIndex = 0; break; case Product.Products.XEditNetCtrl: cbProduct.SelectedIndex = 1; break; default: throw new Exception("Key parsing error"); } cbRelease.SelectedIndex = licenseBase.ReleaseObject.Value; }
private void SetKeyNumber(LicenseBase licenseBase) { LicenseRandomNumber[] numbers = licenseBase.LicenceNumberObject; StringBuilder sb = new StringBuilder(); foreach (LicenseRandomNumber number in numbers) { sb.AppendFormat("{0:000}-", number.Value); } string keyNumber = sb.ToString(); tbKeyNumber.Text = keyNumber.Substring(0, keyNumber.Length - 1); }
public ServiceLicense(LicenseBase licenseBase) { base.UniqueId = licenseBase.UniqueId; base.KeyPair = licenseBase.KeyPair; if (base.KeyPair != null) base.KeyPair.PrivateKey = base.KeyPair.PublicKey; // We can't include the private license on the client side. base.LicenseSets = licenseBase.LicenseSets; base.Product = licenseBase.Product; base.TrailNotificationSettings = licenseBase.TrailNotificationSettings; base.TrialNotificationType = licenseBase.TrialNotificationType; base.TrialSettings = licenseBase.TrialSettings; base.KeyGeneratorType = licenseBase.KeyGeneratorType; }
public bool ValidateLicenseKey(string licenseKey, LicenseBase scutexLicense, bool catchException) { if (catchException) { try { return(ValidateKey(licenseKey, scutexLicense)); } catch (ScutexLicenseException) { return(false); } } return(ValidateKey(licenseKey, scutexLicense)); }
public ServiceLicense(LicenseBase licenseBase) { base.UniqueId = licenseBase.UniqueId; base.KeyPair = licenseBase.KeyPair; if (base.KeyPair != null) { base.KeyPair.PrivateKey = base.KeyPair.PublicKey; // We can't include the private license on the client side. } base.LicenseSets = licenseBase.LicenseSets; base.Product = licenseBase.Product; base.TrailNotificationSettings = licenseBase.TrailNotificationSettings; base.TrialNotificationType = licenseBase.TrialNotificationType; base.TrialSettings = licenseBase.TrialSettings; base.KeyGeneratorType = licenseBase.KeyGeneratorType; }
private void btnGenerateKey_Click(object sender, System.EventArgs e) { LicenseBase licenseBase = new LicenseBase(); switch (cbLicenseType.SelectedIndex) { case 0: licenseBase.LicenseObject.Type = LicenseType.LicenseTypes.None; break; case 1: licenseBase.LicenseObject.Type = LicenseType.LicenseTypes.Trial; licenseBase.ExpiryDate.LicenseDateTime = calDate.SelectionStart; break; case 2: licenseBase.LicenseObject.Type = LicenseType.LicenseTypes.Full; licenseBase.RegistrationDate.LicenseDateTime = calDate.SelectionStart; break; case 3: licenseBase.LicenseObject.Type = LicenseType.LicenseTypes.Invalid; break; default: throw new Exception("Key generation error"); } switch (cbProduct.SelectedIndex) { case 0: licenseBase.ProductObject.ProductCode = Product.Products.None; break; case 1: licenseBase.ProductObject.ProductCode = Product.Products.XEditNetCtrl; break; default: throw new Exception("Key generation error"); } licenseBase.ReleaseObject.Value = (int)Enum.Parse(typeof(Release.Releases), cbRelease.SelectedItem.ToString()); tbKey.Text = licenseBase.LicenseKey; SetKeyNumber(licenseBase); }
public XEditNetLicence(string strSavedLicense) { /* * Constructor, creates and destroys the underlying real BaseLicense, * providing access to the 3 public Members, LicenseKey, Validity and ExpiryDate * */ try { LicenseBase licReal= new LicenseBase(strSavedLicense.ToUpper()); licenseKey=licReal.LicenseKey; validity=XEditNetLicenseValidator.ValidateLicense(LicenseKey); if ( licReal.LicenseObject.Type == LicenseType.LicenseTypes.Trial ) expiryDate=licReal.ExpiryDate.LicenseDateTime; licReal=null; } catch (InvalidLicenseException) { validity=LicenseState.Invalid; expiryDate=DateTime.MinValue; } }
public KeyData GetLicenseKeyData(string licenseKey, LicenseBase scutexLicense, bool catchException) { if (licenseKey == null) { throw new ArgumentNullException("licenseKey"); } KeyData data = null; if (catchException) { try { return(GetKeyData(licenseKey, scutexLicense)); } catch (ScutexLicenseException) { return(data); } } return(GetKeyData(licenseKey, scutexLicense)); }
public bool ValidateLicenseKey(string licenseKey, LicenseBase scutexLicense) { // Init all required variables for the process. Dictionary <int, LicensePlaceholder> placeholerLocations; List <LicensePlaceholder> licensePlaceholders = CreateLicensePlaceholders(scutexLicense, null); char[] licenseKeyArray; string decodedLicenseKey = licenseKey.Replace("-", ""); // Locate all the placeholder tokens in the license template placeholerLocations = FindAllPlaceholdersInTemplate(licenseKeyTemplate.Replace("-", ""), licensePlaceholders); // STEP 1: Basic length checks if (licenseKey.Length != licenseKeyTemplate.Length) { throw new ScutexLicenseException(Resources.ErrorMsg_VerifyLicenseKey); } if (decodedLicenseKey.Length != licenseKeyTemplate.Replace("-", "").Length) { throw new ScutexLicenseException(Resources.ErrorMsg_VerifyLicenseKey); } // STEP 2: Compute and verify all the checksum placeholders in the key foreach (var p in placeholerLocations) { if (p.Value.IsChecksum) { string originalHash; int originalHashValue; int verifyHashValue; try { originalHash = decodedLicenseKey.Substring(p.Key, p.Value.Length); originalHashValue = int.Parse(originalHash, System.Globalization.NumberStyles.HexNumber); verifyHashValue = hashingProvider.Checksum16(decodedLicenseKey.Substring(0, p.Key)); } catch { throw new ScutexLicenseException(Resources.ErrorMsg_VerifyLicenseKey); } if (originalHashValue != verifyHashValue) { throw new ScutexLicenseException(Resources.ErrorMsg_VerifyLicenseKey); } } } // STEP 3: DeObfuscate key license placeholders that are not checksums foreach (var p in placeholerLocations) { if (!p.Value.IsChecksum) { licenseKeyArray = decodedLicenseKey.ToCharArray(); for (int i = 0; i < p.Value.Length; i++) { char previousChar = licenseKeyArray[(p.Key) - 1]; char deObfKey = KeyIntegerValueDeObfuscator(previousChar, licenseKeyArray[p.Key + i], p.Key + i); licenseKeyArray[p.Key + i] = deObfKey; } decodedLicenseKey = new string(licenseKeyArray); } } // STEP 4: Validate each non-checksum placeholder foreach (var p in placeholerLocations) { if (!p.Value.IsChecksum) { switch (p.Value.ValidationType) { case ValidationTypes.LicenseKeyType: int licenseKeyTypeValue = 0; bool licenseKeyTypeValueCheck = int.TryParse(decodedLicenseKey.Substring(p.Key, p.Value.Length), NumberStyles.HexNumber, CultureInfo.InvariantCulture, out licenseKeyTypeValue); // The LicenseKeyType value should be able to be converted to an int, else it is invalid if (!licenseKeyTypeValueCheck) { throw new ScutexLicenseException(Resources.ErrorMsg_VerifyLicenseKey); } LicenseKeyTypeFlag typeFlag; // It is possible that a LicenseKeyType has no supporting LicenseKeyTypeFlag (which means it was // placeholded in the LicenseKeyType enum but is not operable). If this parse (cast) fails then // there was a valid LicenseKeyType enum value but no valid LicenseKeyTypeFlag value. try { int type = licenseKeyTypeValue; if (((LicenseKeyTypes)licenseKeyTypeValue) == LicenseKeyTypes.HardwareLockLocal) { type = (int)LicenseKeyTypes.HardwareLock; } typeFlag = (LicenseKeyTypeFlag)Enum.Parse(typeof(LicenseKeyTypeFlag), ((LicenseKeyTypes)type).ToString(), true); } catch (Exception) { throw new ScutexLicenseException(Resources.ErrorMsg_VerifyLicenseKey); } LicenseSet ls = null; try { var licSetPH = placeholerLocations.Where(x => x.Value.ValidationType == ValidationTypes.LicenseSet).SingleOrDefault(); int licenseSetIdValue1 = int.Parse(decodedLicenseKey.Substring(licSetPH.Key, licSetPH.Value.Length)); Debug.WriteLine(string.Format("Decoded Key: {0}", decodedLicenseKey)); Debug.WriteLine(string.Format("LicenseSet Placeholder: {0}", licSetPH)); Debug.WriteLine(string.Format("LicenseSet Placeholder Key: {0}", licSetPH.Key)); Debug.WriteLine(string.Format("LicenseSet Placeholder Length: {0}", licSetPH.Value.Length)); Debug.WriteLine(string.Format("LicenseSetId Value: {0}", licenseSetIdValue1)); Debug.WriteLine(string.Format("LicenseSets: {0}", scutexLicense.LicenseSets.First().LicenseSetId)); ls = scutexLicense.LicenseSets.Where(x => x.LicenseSetId == licenseSetIdValue1).SingleOrDefault(); } catch { throw new ScutexLicenseException(Resources.ErrorMsg_VerifyLicenseKey); } Debug.WriteLine(string.Format("LicenseSet: {0}", ls)); if (ls == null) { throw new ScutexLicenseException(Resources.ErrorMsg_VerifyLicenseKey); } Debug.WriteLine(string.Format("LicenseSet Types: {0}", ls.SupportedLicenseTypes)); // If the LicenseSet does not support the key type supplied then throw an error if (!ls.SupportedLicenseTypes.IsSet(typeFlag)) { throw new ScutexLicenseException(Resources.ErrorMsg_VerifyLicenseKey); } break; case ValidationTypes.LicenseSet: int licenseSetIdValue = 0; bool licenseSetIdValueCheck = int.TryParse(decodedLicenseKey.Substring(p.Key, p.Value.Length), out licenseSetIdValue); // The LicenseSetId value should be able to be converted to an int, else it is invalid if (!licenseSetIdValueCheck) { throw new ScutexLicenseException(Resources.ErrorMsg_VerifyLicenseKey); } LicenseSet ls1 = null; try { ls1 = scutexLicense.LicenseSets.Where(x => x.LicenseSetId == licenseSetIdValue).SingleOrDefault(); } catch { throw new ScutexLicenseException(Resources.ErrorMsg_VerifyLicenseKey); } if (ls1 == null) { throw new ScutexLicenseException(Resources.ErrorMsg_VerifyLicenseKey); } break; case ValidationTypes.Product: int productIdValue = 0; bool productIdValueCheck = int.TryParse(decodedLicenseKey.Substring(p.Key, p.Value.Length), out productIdValue); // The ProductId value should be able to be converted to an int, else it is invalid if (!productIdValueCheck) { throw new ScutexLicenseException(Resources.ErrorMsg_VerifyLicenseKey); } if (scutexLicense.Product.ProductId != productIdValue) { throw new ScutexLicenseException(Resources.ErrorMsg_VerifyLicenseKey); } break; case ValidationTypes.Fingerprint: string fingerPrint = hashingProvider.Checksum16(_fingerprintService.GetHardwareFingerprint(FingerprintTypes.Default)).ToString("X"); if (fingerPrint != p.Value.Value) { throw new ScutexLicenseException(Resources.ErrorMsg_VerifyLicenseKey); } break; case ValidationTypes.ProductIdentifier: string prodId = hashingProvider.Checksum16(scutexLicense.GetLicenseProductIdentifier()).ToString("X"); prodId = prodId.PadLeft(4, char.Parse("0")); if (prodId != p.Value.Value) { throw new ScutexLicenseException(Resources.ErrorMsg_VerifyLicenseKey); } break; case ValidationTypes.None: string keyValue = decodedLicenseKey.Substring(p.Key, p.Value.Length); if (keyValue != p.Value.Value) { throw new ScutexLicenseException(Resources.ErrorMsg_VerifyLicenseKey); } break; default: throw new ScutexLicenseException(Resources.ErrorMsg_VerifyLicenseKey); } } } return(true); }
public RegisterResult Register(string licenseKey, LicenseBase scutexLicense, ScutexLicense license) { RegisterResult registerResult = new RegisterResult(); registerResult.ScutexLicense = license; bool result = _licenseKeyService.ValidateLicenseKey(licenseKey, scutexLicense, true); ClientLicense cl = null; if (result) { KeyData keyData = _licenseKeyService.GetLicenseKeyData(licenseKey, scutexLicense, false); if (keyData.LicenseKeyType != LicenseKeyTypes.Enterprise && keyData.LicenseKeyType != LicenseKeyTypes.HardwareLockLocal) { try { if (keyData.LicenseKeyType == LicenseKeyTypes.HardwareLock) { cl = _licenseActivationService.ActivateLicenseKey(licenseKey, null, false, (ClientLicense)scutexLicense, _hardwareFingerprintService.GetHardwareFingerprint(FingerprintTypes.Default)); } else { cl = _licenseActivationService.ActivateLicenseKey(licenseKey, null, false, (ClientLicense)scutexLicense, null); } if (cl.IsLicensed && cl.IsActivated) { registerResult.Result = ProcessCodes.ActivationSuccess; registerResult.ClientLicense = cl; } else { registerResult.Result = ProcessCodes.ActivationFailed; } } catch { registerResult.Result = ProcessCodes.ActivationFailed; } } else { cl = _licenseActivationService.ActivateLicenseKey(licenseKey, null, true, (ClientLicense)scutexLicense, null); registerResult.Result = ProcessCodes.LicenseKeyNotActivated; } } else { registerResult.Result = ProcessCodes.KeyInvalid; } if (cl != null) { license.IsLicensed = cl.IsLicensed; license.IsActivated = cl.IsActivated; license.ActivatedOn = cl.ActivatedOn; } return(registerResult); }
private void PrintReadable(List <PackageDef> packages, HashSet <PackageDef> installed) { var packageList = packages.GroupBy(p => p.Name).Select(x => x.OrderByDescending(p => p.Version).First()).OrderBy(x => x.Name).ToList(); if (packageList.Count == 0) { log.Info("Selected directory has no packages installed."); return; } var nameLen = packageList.Select(p => p.Name?.Length).Max(); var verLen = packageList.Select(p => p.Version?.ToString().Length).Max() ?? 0; verLen = Math.Max(verLen, installed.Select(p => p.Version?.ToString().Length).Max() ?? 0); foreach (var plugin in packageList) { var installedPackage = installed.FirstOrDefault(p => p.Name == plugin.Name); var latestPackage = packages.Where(p => p.Name == plugin.Name).OrderByDescending(p => p.Version).FirstOrDefault(); string logMessage = string.Format($"{{0,-{nameLen}}} - {{1,-{verLen}}}{{2}}", plugin.Name, (installedPackage ?? plugin).Version, installedPackage != null ? " - installed" : ""); if (installedPackage != null && installedPackage?.Version?.CompareTo(latestPackage.Version) < 0) { logMessage += $" - update available ({latestPackage.Version})"; } // assuming that all dlls in the package requires has the same or distinct license requirements. // Duplicates are made if one file requires X|Y and the other X|Z or even Y|X. var licensesRequiredStrings = plugin.Files.Select(p => p.LicenseRequired).Where(l => string.IsNullOrWhiteSpace(l) == false).Select(l => LicenseBase.FormatFriendly(l)).Distinct(); var licenses = string.Join(" & ", licensesRequiredStrings); if (licenses != "") { logMessage += " - requires license " + licenses; } log.Info(logMessage); } }
internal List <LicensePlaceholder> CreateLicensePlaceholders(LicenseBase scutexLicense, LicenseGenerationOptions generationOptions) { List <LicensePlaceholder> Placeholders = new List <LicensePlaceholder>(); if (generationOptions != null) { Placeholders.Add(new LicensePlaceholder { Length = 1, Token = Char.Parse("k"), Type = PlaceholderTypes.Number, Value = ((int)generationOptions.LicenseKeyType).ToString(), IsChecksum = false, ValidationType = ValidationTypes.LicenseKeyType }); } else { Placeholders.Add(new LicensePlaceholder { Length = 1, Token = Char.Parse("k"), Type = PlaceholderTypes.Number, Value = "0", IsChecksum = false, ValidationType = ValidationTypes.LicenseKeyType }); } Placeholders.Add(new LicensePlaceholder { Length = 2, Token = Char.Parse("a"), Type = PlaceholderTypes.Number, Value = scutexLicense.Product.GetFormattedProductId(2), IsChecksum = false, ValidationType = ValidationTypes.None }); Placeholders.Add(new LicensePlaceholder { Length = 1, Token = Char.Parse("c"), Type = PlaceholderTypes.Number, Value = "", IsChecksum = true, ValidationType = ValidationTypes.None }); string licProdChecksum = hashingProvider.Checksum16(scutexLicense.GetLicenseProductIdentifier()).ToString("X"); if (licProdChecksum.Length < 4) { licProdChecksum = licProdChecksum.PadLeft(4, char.Parse("0")); } Placeholders.Add(new LicensePlaceholder { Length = 4, Token = Char.Parse("p"), Type = PlaceholderTypes.Number, Value = licProdChecksum, IsChecksum = false, ValidationType = ValidationTypes.None }); return(Placeholders); }
/// <summary> /// Creates a *.TapPackage file from the definition in this PackageDef. /// </summary> static public void CreatePackage(this PackageDef pkg, string path) { foreach (PackageFile file in pkg.Files) { if (!File.Exists(file.FileName)) { log.Error("{0}: File '{1}' not found", pkg.Name, file.FileName); throw new InvalidDataException(); } } if (pkg.Files.Any(s => s.HasCustomData <MissingPackageData>())) { bool resolved = true; foreach (var file in pkg.Files) { while (file.HasCustomData <MissingPackageData>()) { MissingPackageData missingPackageData = file.GetCustomData <MissingPackageData>().FirstOrDefault(); if (missingPackageData.TryResolve(out ICustomPackageData customPackageData)) { file.CustomData.Add(customPackageData); } else { resolved = false; log.Error($"Missing plugin to handle XML Element '{missingPackageData.XmlElement.Name.LocalName}' on file {file.FileName}. (Line {missingPackageData.GetLine()})"); } file.CustomData.Remove(missingPackageData); } } if (!resolved) { throw new ArgumentException("Missing plugins to handle XML elements specified in input package.xml..."); } } string tempDir = Path.GetTempPath() + Path.GetRandomFileName(); Directory.CreateDirectory(tempDir); log.Debug("Using temporary folder at '{0}'", tempDir); try { UpdateVersionInfo(tempDir, pkg.Files, pkg.Version); // License Inject // Obfuscate // Sign CustomPackageActionHelper.RunCustomActions(pkg, PackageActionStage.Create, new CustomPackageActionArgs(tempDir, false)); // Concat license required from all files. But only if the property has not manually been set. if (string.IsNullOrEmpty(pkg.LicenseRequired)) { var licenses = pkg.Files.Select(f => f.LicenseRequired).Where(l => l != null).ToList(); pkg.LicenseRequired = string.Join(", ", licenses.Distinct().Select(l => LicenseBase.FormatFriendly(l, false)).ToList()); } log.Info("Creating OpenTAP package."); pkg.Compress(path, pkg.Files); } finally { FileSystemHelper.DeleteDirectory(tempDir); } }
internal List <LicensePlaceholder> CreateLicensePlaceholders(LicenseBase scutexLicense, LicenseGenerationOptions generationOptions) { List <LicensePlaceholder> placeholders = new List <LicensePlaceholder>(); string payload = null; if (generationOptions != null) { placeholders.Add(new LicensePlaceholder { Length = 1, Token = Char.Parse("k"), Type = PlaceholderTypes.Number, Value = ((int)generationOptions.LicenseKeyType).ToString("X"), IsChecksum = false, ValidationType = ValidationTypes.LicenseKeyType }); placeholders.Add(new LicensePlaceholder { Length = 1, Token = Char.Parse("s"), Type = PlaceholderTypes.Number, Value = generationOptions.LicenseSetId.ToString(), IsChecksum = false, ValidationType = ValidationTypes.LicenseSet }); if (generationOptions.LicenseKeyType == LicenseKeyTypes.HardwareLockLocal) { placeholders.Add(new LicensePlaceholder { Length = 4, Token = Char.Parse("p"), Type = PlaceholderTypes.String, Value = hashingProvider.Checksum16(generationOptions.HardwareFingerprint).ToString("X"), IsChecksum = false, ValidationType = ValidationTypes.Fingerprint }); } else { payload = hashingProvider.Checksum16(scutexLicense.GetLicenseProductIdentifier()).ToString("X"); payload = payload.PadLeft(4, char.Parse("0")); placeholders.Add(new LicensePlaceholder { Length = 4, Token = Char.Parse("p"), Type = PlaceholderTypes.String, Value = payload, IsChecksum = false, ValidationType = ValidationTypes.ProductIdentifier }); } } else { placeholders.Add(new LicensePlaceholder { Length = 1, Token = Char.Parse("k"), Type = PlaceholderTypes.Number, Value = "0", IsChecksum = false, ValidationType = ValidationTypes.LicenseKeyType }); placeholders.Add(new LicensePlaceholder { Length = 1, Token = Char.Parse("s"), Type = PlaceholderTypes.Number, Value = "0", IsChecksum = false, ValidationType = ValidationTypes.LicenseSet }); payload = hashingProvider.Checksum16(scutexLicense.GetLicenseProductIdentifier()).ToString("X"); payload = payload.PadLeft(4, char.Parse("0")); placeholders.Add(new LicensePlaceholder { Length = 4, Token = Char.Parse("p"), Type = PlaceholderTypes.String, Value = payload, IsChecksum = false, ValidationType = ValidationTypes.ProductIdentifier }); } placeholders.Add(new LicensePlaceholder { Length = 1, Token = Char.Parse("v"), Type = PlaceholderTypes.Number, Value = ((int)LicenseDataCheckTypes.Standard).ToString(), IsChecksum = false }); placeholders.Add(new LicensePlaceholder { Length = 2, Token = Char.Parse("a"), Type = PlaceholderTypes.Number, Value = scutexLicense.Product.GetFormattedProductId(2), IsChecksum = false, ValidationType = ValidationTypes.Product }); placeholders.Add(new LicensePlaceholder { Length = 4, Token = Char.Parse("c"), Type = PlaceholderTypes.Number, Value = "", IsChecksum = true, ValidationType = ValidationTypes.None }); placeholders.Add(new LicensePlaceholder { Length = 1, Token = Char.Parse("l"), Type = PlaceholderTypes.String, Value = "F", IsChecksum = false }); //placeholders.Add(new LicensePlaceholder //{ // Length = 1, // Token = Char.Parse("s"), // Type = PlaceholderTypes.String, // Value = "0", // IsChecksum = false //}); return(placeholders); }
public KeyData GetLicenseKeyData(string licenseKey, LicenseBase scutexLicense) { // Init all required variables for the process. Dictionary <int, LicensePlaceholder> placeholerLocations; List <LicensePlaceholder> licensePlaceholders = CreateLicensePlaceholders(scutexLicense, null); char[] licenseKeyArray; string decodedLicenseKey = licenseKey.Replace("-", ""); KeyData keyData = new KeyData(); keyData.IsKeyValid = true; // Locate all the placeholder tokens in the license template placeholerLocations = FindAllPlaceholdersInTemplate(licenseKeyTemplate.Replace("-", ""), licensePlaceholders); bool isKeyValid = ValidateLicenseKey(licenseKey, scutexLicense); keyData.IsKeyValid = isKeyValid; if (isKeyValid) { foreach (var p in placeholerLocations) { if (!p.Value.IsChecksum) { licenseKeyArray = decodedLicenseKey.ToCharArray(); for (int i = 0; i < p.Value.Length; i++) { char previousChar = licenseKeyArray[(p.Key) - 1]; char deObfKey = KeyIntegerValueDeObfuscator(previousChar, licenseKeyArray[p.Key + i], p.Key + i); licenseKeyArray[p.Key + i] = deObfKey; } decodedLicenseKey = new string(licenseKeyArray); } } foreach (var p in placeholerLocations) { if (!p.Value.IsChecksum) { if (p.Value.Token == Char.Parse("k")) { int licenseKeyTypeValue = 0; bool licenseKeyTypeValueCheck = int.TryParse(decodedLicenseKey.Substring(p.Key, p.Value.Length), out licenseKeyTypeValue); if (licenseKeyTypeValueCheck) { keyData.LicenseKeyType = (LicenseKeyTypes)licenseKeyTypeValue; } } else if (p.Value.Token == Char.Parse("a")) { int prodValue = 0; bool prodValueCheck = int.TryParse(decodedLicenseKey.Substring(p.Key, p.Value.Length), out prodValue); if (prodValueCheck) { keyData.ProductId = prodValue; } } else if (p.Value.Token == Char.Parse("s")) { int licenseSetValue = 0; bool licenseSetValueCheck = int.TryParse(decodedLicenseKey.Substring(p.Key, p.Value.Length), out licenseSetValue); if (licenseSetValueCheck) { keyData.LicenseSetId = licenseSetValue; } } } } } return(keyData); }
public string GenerateLicenseKey(string rsaXmlString, LicenseBase scutexLicense, LicenseGenerationOptions generationOptions) { // Init all required variables for the process. Dictionary <int, LicensePlaceholder> placeholerLocations; List <LicensePlaceholder> licensePlaceholders = CreateLicensePlaceholders(scutexLicense, generationOptions); string licenseKey; char[] licenseKeyArray; // Setup the license key to work on licenseKey = licenseKeyTemplate.Replace("-", ""); // Locate all the placeholder tokens in the license template placeholerLocations = FindAllPlaceholdersInTemplate(licenseKey, licensePlaceholders); // Verify that all the registered placeholders were located in the template. if (placeholerLocations.Count != licensePlaceholders.Count) { throw new Exception(string.Format(Resources.ErrorMsg_PlaceholderCount, licensePlaceholders.Count, placeholerLocations.Count)); } // Change all non-checksum placeholders to their actual values in the key foreach (var p in placeholerLocations) { if (!p.Value.IsChecksum) { string token = ""; for (int i = 0; i < p.Value.Length; i++) { token = token + p.Value.Token; } licenseKey = licenseKey.Replace(token, p.Value.Value); } } // Compute and change the random license key placeholders licenseKeyArray = licenseKey.ToCharArray(); for (int i = 0; i < licenseKeyArray.Length; i++) { if (licenseKeyArray[i] == char.Parse("x")) { licenseKeyArray[i] = GetRandomCharacter(); } } licenseKey = new string(licenseKeyArray); // Obfuscate key license placeholders that are not checksums foreach (var p in placeholerLocations) { if (!p.Value.IsChecksum) { if (p.Value.Type == PlaceholderTypes.Number) { //Console.WriteLine(p.Value.Token); //Console.WriteLine("-----------------"); licenseKeyArray = licenseKey.ToCharArray(); for (int i = 0; i < p.Value.Length; i++) { char previousChar = licenseKeyArray[(p.Key) - 1]; int data = int.Parse(licenseKeyArray[p.Key + i].ToString(), NumberStyles.HexNumber); char obfKey = KeyIntegerValueObfuscator(previousChar, data, p.Key + i); licenseKeyArray[p.Key + i] = obfKey; } licenseKey = new string(licenseKeyArray); } else if (p.Value.Type == PlaceholderTypes.String) { licenseKeyArray = licenseKey.ToCharArray(); for (int i = 0; i < p.Value.Length; i++) { char previousChar = licenseKeyArray[(p.Key) - 1]; int modData = CharacterMap.ReverseMap[licenseKeyArray[p.Key + i]]; //Console.WriteLine(string.Format("Char: {0}", licenseKeyArray[p.Key + i])); char obfKey = KeyIntegerValueObfuscator(previousChar, modData, p.Key + i); licenseKeyArray[p.Key + i] = obfKey; } licenseKey = new string(licenseKeyArray); } } } // Now compute and change all the checksum placeholders in the key foreach (var p in placeholerLocations) { if (p.Value.IsChecksum) { string token = ""; for (int i = 0; i < p.Value.Length; i++) { token = token + p.Value.Token; } string hash = hashingProvider.Checksum16(licenseKey.Substring(0, p.Key)).ToString("X"); hash = hash.PadLeft(4, char.Parse("0")); licenseKey = licenseKey.Replace(token, hash); } } // Insert the seperators List <int> seperatorLocations = FindAllSeperatorsInTemplate(licenseKeyTemplate); string finalKey = licenseKey; if (seperatorLocations.Count > 0) { int remaining = seperatorLocations.Count - 1; for (int i = 0; i < seperatorLocations.Count; i++) { finalKey = finalKey.Insert(seperatorLocations[i] - remaining, "-"); remaining--; } } return(finalKey); }
public bool ValidateLicenseKey(string licenseKey, LicenseBase scutexLicense) { // Init all required variables for the process. Dictionary <int, LicensePlaceholder> placeholerLocations; List <LicensePlaceholder> licensePlaceholders = CreateLicensePlaceholders(scutexLicense, null); char[] licenseKeyArray; string decodedLicenseKey = licenseKey.Replace("-", ""); // Locate all the placeholder tokens in the license template placeholerLocations = FindAllPlaceholdersInTemplate(licenseKeyTemplate.Replace("-", ""), licensePlaceholders); // STEP 1: Basic length checks if (licenseKey.Length != licenseKeyTemplate.Length) { throw new ScutexLicenseException(Resources.ErrorMsg_VerifyLicenseKey); } if (decodedLicenseKey.Length != licenseKeyTemplate.Replace("-", "").Length) { throw new ScutexLicenseException(Resources.ErrorMsg_VerifyLicenseKey); } // STEP 2: Compute and verify all the cheksums in the key foreach (var p in placeholerLocations) { if (p.Value.IsChecksum) { string originalHash = decodedLicenseKey.Substring(p.Key, p.Value.Length); int originalHashValue = 0; // Try and covert the value from originalHash into a Hex number, if this value has been changed (altered) the key is invalid as // it should always be a hex value. bool verifyHexOriginalHash = int.TryParse(originalHash, NumberStyles.HexNumber, CultureInfo.InvariantCulture, out originalHashValue); // If this isn't a hex value throw the standard exception if (!verifyHexOriginalHash) { throw new ScutexLicenseException(Resources.ErrorMsg_VerifyLicenseKey); } // Compute the hash again using the rest of hte license key. int verifyHashValue = int.Parse(hashingProvider.GetChecksumChar(decodedLicenseKey.Substring(0, p.Key)).ToString(), NumberStyles.HexNumber); // Verify that the stored has is the same as the newly computed hash if (verifyHashValue != originalHashValue) { throw new ScutexLicenseException(Resources.ErrorMsg_VerifyLicenseKey); } if (!hashingProvider.ValidateChecksumChar(decodedLicenseKey)) { throw new ScutexLicenseException(Resources.ErrorMsg_VerifyLicenseKey); } } } // STEP 3: DeObfuscate key license placeholders that are not cheksums (so they can be verified) foreach (var p in placeholerLocations) { if (!p.Value.IsChecksum) { licenseKeyArray = decodedLicenseKey.ToCharArray(); for (int i = 0; i < p.Value.Length; i++) { char previousChar = licenseKeyArray[(p.Key) - 1]; char deObfKey = KeyIntegerValueDeObfuscator(previousChar, licenseKeyArray[p.Key + i], p.Key + i); licenseKeyArray[p.Key + i] = deObfKey; } decodedLicenseKey = new string(licenseKeyArray); } } // STEP 4: Validate each non-checksum placeholder foreach (var p in placeholerLocations) { if (!p.Value.IsChecksum) { switch (p.Value.ValidationType) { case ValidationTypes.LicenseKeyType: int licenseKeyTypeValue = 0; bool licenseKeyTypeValueCheck = int.TryParse(decodedLicenseKey.Substring(p.Key, p.Value.Length), out licenseKeyTypeValue); // The LicenseKeyType value should be able to be convered to an int, else it is invalid if (!licenseKeyTypeValueCheck) { throw new ScutexLicenseException(Resources.ErrorMsg_VerifyLicenseKey); } LicenseKeyTypeFlag typeFlag; // It is possible that a LicenseKeyType has no supporting LicenseKeyTypeFlag (which means it was // placeholded in the LicenseKeyType enum but is not operable). If this parse (cast) fails then // there was a valid LicenseKeyType enum value but no valid LicenseKeyTypeFlag value. try { typeFlag = (LicenseKeyTypeFlag)Enum.Parse(typeof(LicenseKeyTypeFlag), ((LicenseKeyTypes)licenseKeyTypeValue).ToString(), true); } catch (Exception) { throw new ScutexLicenseException(Resources.ErrorMsg_VerifyLicenseKey); } // If the LicenseSet does not support the key type supplied then throw an error if (!scutexLicense.LicenseSets.First().SupportedLicenseTypes.IsSet(typeFlag)) { throw new ScutexLicenseException(Resources.ErrorMsg_VerifyLicenseKey); } break; case ValidationTypes.None: string keyValue = decodedLicenseKey.Substring(p.Key, p.Value.Length); if (keyValue != p.Value.Value) { throw new ScutexLicenseException(Resources.ErrorMsg_VerifyLicenseKey); } break; default: throw new ScutexLicenseException(Resources.ErrorMsg_VerifyLicenseKey); } } } // If we've gotten this far then it must be valid, right? return(true); }