Advertisement
filmee24

SKGL with named features

Jan 17th, 2016
254
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 25.95 KB | None | 0 0
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Net.NetworkInformation;
  4. using System.Linq;
  5. //Copyright (C) 2014 Steve Aitken, Artem Los
  6. //All rights reserved.
  7.  
  8. //This code is based on SKGL 2.0.5.2 with improvements and changes by Steve Aitken
  9.  
  10. using System.Management;
  11. using System.Numerics;
  12.  
  13.  
  14. namespace SKGL
  15. {
  16.     #region "S E R I A L  K E Y  G E N E R A T I N G  L I B R A R Y"
  17.  
  18.     #region "CONFIGURATION"
  19.  
  20.     public abstract class BaseConfiguration
  21.     {
  22.         //Put all functions/variables that should be shared with
  23.         //all other classes that inherit this class.
  24.         //
  25.         //note, this class cannot be used as a normal class that
  26.         //you define because it is MustInherit.
  27.  
  28.         protected internal string _key = "";
  29.         /// <summary>
  30.         /// The key will be stored here
  31.         /// </summary>
  32.         public virtual string Key
  33.         {
  34.             //will be changed in both generating and validating classe.
  35.             get { return _key; }
  36.             set { _key = value; }
  37.         }
  38.  
  39.         /// <summary>
  40.         ///
  41.         /// </summary>
  42.         /// <value></value>
  43.         /// <returns></returns>
  44.         /// <remarks></remarks>
  45.         public virtual int MachineCode
  46.         {
  47.  
  48.             get { return getMachineCode(); }
  49.         }
  50.  
  51.  
  52.         private static int getMachineCode()
  53.         {
  54.             //      * Copyright (C) 2012 Artem Los, All rights reserved.
  55.             //      *
  56.             //      * This code will generate a 5 digits long key, finger print, of the system
  57.             //      * where this method is being executed. However, that might be changed in the
  58.             //      * hash function "GetStableHash", by changing the amount of zeroes in
  59.             //      * MUST_BE_LESS_OR_EQUAL_TO to the one you want to have. Ex 1000 will return
  60.             //      * 3 digits long hash.
  61.             methods m = new methods();
  62.             ManagementObjectSearcher searcher = new ManagementObjectSearcher("SELECT * FROM Win32_PhysicalMedia");
  63.  
  64.             string collectedInfo = "";
  65.  
  66.             collectedInfo += System.Environment.MachineName;
  67.             var x = new List<string>();
  68.             foreach (NetworkInterface ni in NetworkInterface.GetAllNetworkInterfaces())
  69.             {
  70.                 // probably need to do some filtering on ni.NetworkInterfaceType here
  71.                 //collectedInfo +=ni.GetPhysicalAddress();
  72.                 x.Add(ni.GetPhysicalAddress().ToString());
  73.             }
  74.             x.Sort();
  75.             collectedInfo += x[x.Count - 1];
  76.             x.Clear();
  77.  
  78.             foreach (ManagementObject wmi_HD in searcher.Get())
  79.             {
  80.                 // get the hardware serial no.
  81.                 if (wmi_HD["SerialNumber"] == null && wmi_HD["Removable"] == null && wmi_HD["Replaceable"] == null)
  82.                 {
  83.                     // Don't add
  84.                 }
  85.                 else
  86.                 {
  87.                     //serialNo = wmi_HD["SerialNumber"].ToString();
  88.                     //hotSwap = Convert.ToBoolean(wmi_HD["HotSwappable"]);
  89.                     //Console.WriteLine(hotSwap);
  90.                     x.Add(wmi_HD["SerialNumber"].ToString());
  91.                 }
  92.             }
  93.             x.Sort();
  94.             collectedInfo += string.Join("", x);
  95.  
  96.             return m.getEightByteHash(collectedInfo, 100000);
  97.         }
  98.  
  99.     }
  100.     public class SerialKeyConfiguration : BaseConfiguration
  101.     {
  102.  
  103.         #region "V A R I A B L E S"
  104.         private bool[] _Features = new bool[8] {
  105.         false,
  106.         false,
  107.         false,
  108.         false,
  109.         false,
  110.         false,
  111.         false,
  112.         false
  113.         //the default value of the Fetures array.
  114.     };
  115.         private List<string> _featureNames = new List<string>(8);
  116.  
  117.         public virtual bool[] Features
  118.         {
  119.             //will be changed in validating class.
  120.             get { return _Features; }
  121.             set { _Features = value; }
  122.         }
  123.         private bool _addSplitChar = true;
  124.         public bool addSplitChar
  125.         {
  126.             get { return _addSplitChar; }
  127.             set { _addSplitChar = value; }
  128.         }
  129.  
  130.         public bool this[string name]
  131.         {
  132.             get
  133.             {
  134.                 return _Features[getIndexOfItem(name)];
  135.             }
  136.             set
  137.             {
  138.                 if (_featureNames.Count == 8)
  139.                 {
  140.                     throw new Exception("Maximum amount of Features reached");
  141.                 }
  142.                 else
  143.                 {
  144.                     if (_featureNames.Contains(name.ToLower()))
  145.                     {
  146.                         _Features[getIndexOfItem(name.ToLower())] = value;
  147.                     }
  148.                     else
  149.                     {
  150.                         _featureNames.Add(name.ToLower());
  151.                         Features[getIndexOfItem(name.ToLower())] = value;
  152.                     }
  153.                 }
  154.  
  155.                
  156.             }
  157.         }
  158.  
  159.         public string this[int index]
  160.         {
  161.             get
  162.             {
  163.                 return _featureNames[index];
  164.             }
  165.             set
  166.             {
  167.                 _featureNames[index] = value;
  168.             }
  169.         }
  170.  
  171.  
  172.         private int getIndexOfItem(string key)
  173.         {
  174.             for (int i = 0; i < _featureNames.Count; i++)
  175.             {
  176.                 if(_featureNames[i] == key)
  177.                 {
  178.                     return i;
  179.                 }
  180.             }
  181.  
  182.             return -1;
  183.         }
  184.  
  185.         #endregion
  186.  
  187.         public override string ToString()
  188.         {
  189.             return string.Join(",", _featureNames);
  190.         }
  191.  
  192.         public static SerialKeyConfiguration Parse(string names)
  193.         {
  194.             var c = new SerialKeyConfiguration();
  195.  
  196.             c._featureNames = names.Split(',').Select((s) => s.Trim()).ToList();
  197.  
  198.             return c;
  199.         }
  200.  
  201.     }
  202.     #endregion
  203.  
  204.     #region "ENCRYPTION"
  205.     public class Generate : BaseConfiguration
  206.     {
  207.         //this class have to be inherited because of the key which is shared with both encryption/decryption classes.
  208.  
  209.         SerialKeyConfiguration skc = new SerialKeyConfiguration();
  210.         methods m = new methods();
  211.         Random r = new Random();
  212.         public Generate()
  213.         {
  214.             // No overloads works with Sub New
  215.             r = new Random(DateTime.Now.Millisecond);
  216.         }
  217.         public Generate(SerialKeyConfiguration _serialKeyConfiguration)
  218.         {
  219.             skc = _serialKeyConfiguration;
  220.             r = new Random(DateTime.Now.Millisecond);
  221.         }
  222.  
  223.         private string _secretPhase;
  224.         /// <summary>
  225.         /// If the key is to be encrypted, enter a password here.
  226.         /// </summary>
  227.  
  228.         public string secretPhase
  229.         {
  230.             get { return _secretPhase; }
  231.             set
  232.             {
  233.                 if ((value != _secretPhase) && (!string.IsNullOrEmpty(value)))
  234.                 {
  235.                     _secretPhase = m.twentyfiveByteHash(value);
  236.                 }
  237.             }
  238.         }
  239.  
  240.         private int _numUsers;
  241.  
  242.         public int numUsers
  243.         {
  244.             get { return _numUsers; }
  245.             set
  246.             {
  247.                 _numUsers = value;
  248.             }
  249.         }
  250.  
  251.         /// <summary>
  252.         /// This function will generate a key.
  253.         /// </summary>
  254.         /// <param name="timeLeft">For instance, 30 days.</param>
  255.         public string doKey(int timeLeft, int users = 0, int assets = 0, int concurrentUsers = 0)
  256.         {
  257.             return doKey(timeLeft, DateTime.Today, users, assets, concurrentUsers); // removed extra argument false
  258.         }
  259.  
  260.         /// <summary>
  261.         ///
  262.         /// </summary>
  263.         /// <param name="timeLeft">For instance, 30 days</param>
  264.         /// <param name="useMachineCode">Lock a serial key to a specific machine, given its "machine code". Should be 5 digits long.</param>
  265.         /// <returns></returns>
  266.         /// <remarks></remarks>
  267.         public object doKey(int timeLeft, int useMachineCode, int users = 0, int assets = 0, int concurrentUsers = 0)
  268.         {
  269.             return doKey(timeLeft, DateTime.Today, useMachineCode, users, assets, concurrentUsers);
  270.         }
  271.  
  272.         /// <summary>
  273.         /// This function will generate a key. You may also change the creation date.
  274.         /// </summary>
  275.         /// <param name="timeLeft">For instance, 30 days.</param>
  276.         /// <param name="creationDate">Change the creation date of a key.</param>
  277.         /// <param name="useMachineCode">Lock a serial key to a specific machine, given its "machine code". Should be 5 digits long.</param>
  278.         public string doKey(int timeLeft, System.DateTime creationDate, int useMachineCode = 0, int users = 0, int assets = 0, int concurrentUsers = 0)
  279.         {
  280.             if (timeLeft > 999)
  281.             {
  282.                 //Checking if the timeleft is NOT larger than 999..
  283.                 throw new ArgumentException("The timeLeft is larger than 999. It can only consist of three digits.");
  284.             }
  285.             if (users > 100000)
  286.             {
  287.                 //Checking if the timeleft is NOT larger than 999. .
  288.                 throw new ArgumentException("Users is larger than 99,999. It can only consist of five digits.");
  289.             }
  290.             if (assets > 100)
  291.             {
  292.                 //Checking if the timeleft is NOT larger than 999. .
  293.                 throw new ArgumentException("Assets is larger than 99. It can only consist of two digits.");
  294.             }
  295.             if (MachineCode > 99999)
  296.             {
  297.                 //Checking if the timeleft is NOT larger than 999. .
  298.                 throw new ArgumentException("Machine ID is larger than 99999. It can only consist of five digits.");
  299.             }
  300.             if (concurrentUsers > 9999)
  301.             {
  302.                 //Checking if the timeleft is NOT larger than 999. .
  303.                 throw new ArgumentException("concurrentUsers is larger than 9999. It can only consist of four digits.");
  304.             }
  305.  
  306.  
  307.             if (!string.IsNullOrEmpty(secretPhase) | secretPhase != null)
  308.             {
  309.                 //if some kind of value is assigned to the variable "secretPhase", the code will execute it FIRST.
  310.                 //the secretPhase shall only consist of digits!
  311.                 System.Text.RegularExpressions.Regex reg = new System.Text.RegularExpressions.Regex("^\\d$");
  312.                 //cheking the string
  313.                 if (reg.IsMatch(secretPhase))
  314.                 {
  315.                     //throwing new exception if the string contains non-numrical letters.
  316.                     throw new ArgumentException("The secretPhase consist of non-numerical letters.");
  317.                 }
  318.             }
  319.  
  320.             //if no exception is thown, do following
  321.             string _stageThree = null;
  322.             if (useMachineCode > 0 & useMachineCode <= 99999)
  323.             {
  324.                 _stageThree = m._encrypt(users, timeLeft, skc.Features, secretPhase, useMachineCode, creationDate, assets, concurrentUsers);
  325.                 // stage one
  326.             }
  327.             else
  328.             {
  329.                 _stageThree = m._encrypt(users, timeLeft, skc.Features, secretPhase, r.Next(0, 99999), creationDate, assets, concurrentUsers);
  330.                 // stage one
  331.             }
  332.  
  333.             //if it is the same value as default, we do not need to mix chars. This step saves generation time.
  334.  
  335.             if (skc.addSplitChar == true)
  336.             {
  337.                 // by default, a split character will be added - this loop adds a split at every 5 characters.
  338.                 Key = "";
  339.                 var i = 0;
  340.                 foreach (char c in _stageThree)
  341.                 {
  342.                     if (i % 5 == 0 && i != 0)
  343.                     {
  344.                         Key = Key + "-";
  345.                     }
  346.                     Key = Key + c;
  347.                     i++;
  348.                 }
  349.             }
  350.             else
  351.             {
  352.                 Key = _stageThree;
  353.             }
  354.  
  355.  
  356.  
  357.             //we also include the key in the Key variable to make it possible for user to get this key without generating a new one.
  358.             return Key;
  359.  
  360.         }
  361.  
  362.  
  363.     }
  364.     #endregion
  365.  
  366.     #region "DECRYPTION"
  367.     public class Validate : BaseConfiguration
  368.     {
  369.         //this class have to be inherited becuase of the key which is shared with both encryption/decryption classes.
  370.  
  371.         SerialKeyConfiguration skc = new SerialKeyConfiguration();
  372.         methods _a = new methods();
  373.         public Validate()
  374.         {
  375.             // No overloads works with Sub New
  376.         }
  377.         public Validate(SerialKeyConfiguration _serialKeyConfiguration)
  378.         {
  379.             skc = _serialKeyConfiguration;
  380.         }
  381.         /// <summary>
  382.         /// Enter a key here before validating.
  383.         /// </summary>
  384.         public override string Key
  385.         {
  386.             //re-defining the Key
  387.             get { return _key; }
  388.             set
  389.             {
  390.                 _res = "";
  391.                 _key = value;
  392.             }
  393.         }
  394.  
  395.         private string _secretPhase = "";
  396.         /// <summary>
  397.         /// If the key has been encrypted, when it was generated, please set the same secretPhase here.
  398.         /// </summary>
  399.         public string secretPhase
  400.         {
  401.             get { return _secretPhase; }
  402.             set
  403.             {
  404.                 if ((value != _secretPhase) && (!string.IsNullOrEmpty(value)))
  405.                 {
  406.                     _secretPhase = _a.twentyfiveByteHash(value);
  407.                     _res = "";
  408.                 }
  409.             }
  410.         }
  411.  
  412.         /// <summary>
  413.         /// This is the decrypted, decoded key, is only set if the key has been processed, and is reset to blank if the key is changed.
  414.         /// </summary>
  415.         private string _res = "";
  416.  
  417.         private void decodeKeyToString()
  418.         {
  419.             // checking if the key already have been decoded.
  420.             if (string.IsNullOrEmpty(_res) | _res == null)
  421.             {
  422.  
  423.                 string _stageOne = "";
  424.  
  425.                 Key = Key.Replace("-", "");
  426.  
  427.                 //if the admBlock has been changed, the getMixChars will be executed.
  428.  
  429.  
  430.                 _stageOne = Key;
  431.  
  432.  
  433.                 _stageOne = Key;
  434.  
  435.                 // _stageTwo = _a._decode(_stageOne)
  436.  
  437.                 if (!string.IsNullOrEmpty(secretPhase) | secretPhase != null)
  438.                 {
  439.                     //if no value "secretPhase" given, the code will directly decrypt without using somekind of encryption
  440.                     //if some kind of value is assigned to the variable "secretPhase", the code will execute it FIRST.
  441.                     //the secretPhase shall only consist of digits!
  442.                     System.Text.RegularExpressions.Regex reg = new System.Text.RegularExpressions.Regex("^\\d$");
  443.                     //cheking the string
  444.                     if (reg.IsMatch(secretPhase))
  445.                     {
  446.                         //throwing new exception if the string contains non-numrical letters.
  447.                         throw new ArgumentException("The secretPhase consist of non-numerical letters.");
  448.                     }
  449.                 }
  450.                 _res = _a._decrypt(_stageOne, secretPhase);
  451.  
  452.  
  453.             }
  454.         }
  455.         private bool _IsValid()
  456.         {
  457.             //Dim _a As New methods ' is only here to provide the geteighthashcode method
  458.             try
  459.             {
  460.                 if (string.IsNullOrEmpty(_res))
  461.                 {
  462.                     decodeKeyToString();
  463.                     string _decodedHash = _res.Substring(0, 9);
  464.                     string _calculatedHash = _a.getEightByteHash(_res.Substring(9, _res.Length - 9)).ToString().Substring(0, 9);
  465.                     // changed Math.Abs(_res.Substring(0, 17).GetHashCode).ToString.Substring(0, 8)
  466.  
  467.                     //When the hashcode is calculated, it cannot be taken for sure,
  468.                     //that the same hash value will be generated.
  469.                     //learn more about this issue: http://msdn.microsoft.com/en-us/library/system.object.gethashcode.aspx
  470.                     if (_decodedHash == _calculatedHash)
  471.                     {
  472.                         return true;
  473.                     }
  474.                     else
  475.                     {
  476.                         //reset the decoded string
  477.                         _res = "";
  478.                         return false;
  479.                     }
  480.                 }
  481.                 else
  482.                 {//_res contains decrypted valid key - so this is valid
  483.                     return true;
  484.                 }
  485.  
  486.             }
  487.             catch (Exception ex)
  488.             {
  489.                 //if something goes wrong, for example, when decrypting,
  490.                 //this function will return false, so that user knows that it is unvalid.
  491.                 //if the key is valid, there won't be any errors.
  492.                 return false;
  493.             }
  494.         }
  495.         /// <summary>
  496.         /// Checks whether the key has been modified or not. If the key has been modified - returns false; if the key has not been modified - returns true.
  497.         /// </summary>
  498.         public bool IsValid
  499.         {
  500.             get { return _IsValid(); }
  501.         }
  502.         private bool _IsExpired()
  503.         {
  504.             if (DaysLeft > 0)
  505.             {
  506.                 return false;
  507.             }
  508.             else
  509.             {
  510.                 return true;
  511.             }
  512.         }
  513.         /// <summary>
  514.         /// If the key has expired - returns true; if the key has not expired - returns false.
  515.         /// </summary>
  516.         public bool IsExpired
  517.         {
  518.             get { return _IsExpired(); }
  519.         }
  520.         private System.DateTime _CreationDay()
  521.         {
  522.             if (this.IsValid)
  523.             {
  524.                 System.DateTime _date = new System.DateTime();
  525.                 _date = new DateTime(Convert.ToInt32(_res.Substring(9, 4)), Convert.ToInt32(_res.Substring(13, 2)), Convert.ToInt32(_res.Substring(15, 2)));
  526.                 return _date;
  527.             }
  528.             else
  529.             {
  530.                 return DateTime.MinValue;
  531.             }
  532.         }
  533.         /// <summary>
  534.         /// Returns the creation date of the key.
  535.         /// </summary>
  536.         public System.DateTime CreationDate
  537.         {
  538.             get { if (IsValid) return _CreationDay(); else return DateTime.MinValue; }
  539.         }
  540.         private int _DaysLeft()
  541.         {
  542.             int _setDays = SetTime;
  543.             return Convert.ToInt32(((TimeSpan)(ExpireDate - DateTime.Today)).TotalDays); //or viseversa
  544.         }
  545.         /// <summary>
  546.         /// Returns the amount of days the key will be valid.
  547.         /// </summary>
  548.         public int DaysLeft
  549.         {
  550.             get { if (IsValid) return _DaysLeft(); else return 0; }
  551.         }
  552.  
  553.         private int _ConcurrentUsers()
  554.         {
  555.             if (_res.Length > 35)
  556.             {
  557.                 return Convert.ToInt32(_res.Substring(35, 4));
  558.             }
  559.             else//old license, no concurrent users.
  560.                 return 0;
  561.         }
  562.  
  563.         public int ConcurrentUsers
  564.         {
  565.             get { if (IsValid) return _ConcurrentUsers(); else return 0; }
  566.         }
  567.  
  568.         public int MaxUsers
  569.         {
  570.             get { if (IsValid) return _MaxUsers(); else return 0; }
  571.         }
  572.  
  573.         private int _MaxUsers()
  574.         {
  575.             return Convert.ToInt32(_res.Substring(28, 5));
  576.         }
  577.  
  578.         public int MaxAssets
  579.         {
  580.             get { if (IsValid) return _MaxAssets(); else return 0; }
  581.         }
  582.  
  583.         private int _MaxAssets()
  584.         {
  585.             return Convert.ToInt32(_res.Substring(33, 2));
  586.         }
  587.         private int _SetTime()
  588.         {
  589.             return Convert.ToInt32(_res.Substring(17, 3));
  590.         }
  591.         /// <summary>
  592.         /// Returns the actual amount of days that were set when the key was generated.
  593.         /// </summary>
  594.         public int SetTime
  595.         {
  596.             get { if (IsValid) return _SetTime(); else return 0; }
  597.         }
  598.         private System.DateTime _ExpireDate()
  599.         {
  600.             if (IsValid)
  601.             {
  602.                 System.DateTime _date = new System.DateTime();
  603.                 _date = CreationDate;
  604.                 if (SetTime > 0)
  605.                 {
  606.                     return _date.AddDays(SetTime);
  607.                 }
  608.                 else
  609.                 {
  610.                     return DateTime.MaxValue;
  611.                 }
  612.             }
  613.             else
  614.             {
  615.                 return DateTime.MinValue;
  616.             }
  617.         }
  618.         /// <summary>
  619.         /// Returns the date when the key is to be expired.
  620.         /// </summary>
  621.         public System.DateTime ExpireDate
  622.         {
  623.             get { return _ExpireDate(); }
  624.         }
  625.  
  626.         private bool[] _Features()
  627.         {
  628.             skc.Features = _a.intToBoolean(Convert.ToInt32(_res.Substring(20, 3)));
  629.  
  630.             return skc.Features;
  631.         }
  632.         /// <summary>
  633.         /// Returns all 8 features in a boolean array
  634.         /// </summary>
  635.         public bool[] Features
  636.         {
  637.             //we already have defined Features in the BaseConfiguration class.
  638.             //Here we only change it to Read Only.
  639.             get { if (IsValid) return _Features(); else return new bool[] { false, false, false, false, false, false, false, false }; }
  640.         }
  641.  
  642.         public int DecodedMachineCode
  643.         {
  644.             get
  645.             {
  646.                 if (IsValid)
  647.                 {
  648.                     return Convert.ToInt32(_res.Substring(23, 5));
  649.                 }
  650.                 else
  651.                     return -1;
  652.             }
  653.         }
  654.  
  655.         /// <summary>
  656.         /// If the current machine's machine code is equal to the one that this key is designed for, return true.
  657.         /// </summary>
  658.         /// <value></value>
  659.         /// <returns></returns>
  660.         /// <remarks></remarks>
  661.         public bool IsOnRightMachine
  662.         {
  663.             get
  664.             {
  665.                 if (IsValid)
  666.                 {
  667.                     int decodedMachineCode = Convert.ToInt32(_res.Substring(23, 5));
  668.                     return decodedMachineCode == MachineCode || decodedMachineCode == 1;
  669.                 }
  670.                 else
  671.                 {
  672.                     return false;
  673.                 }
  674.             }
  675.         }
  676.  
  677.  
  678.         public override string ToString()
  679.         {
  680.             return string.Format("Valid: {0} \n Days Left: {1} \n Features: {2},{3},{4},{5},{6},{7},{8},{9} \n machine code: {10} \n current machine code:{11} \n Valid on machine: {12} \n Users: {13} \n Assets: {14}\n ConcurrentUsers: {15}\n",
  681.                                         this.IsValid,
  682.                                         this.DaysLeft,
  683.                                         this.Features[0],
  684.                                         this.Features[1],
  685.                                         this.Features[2],
  686.                                         this.Features[3],
  687.                                         this.Features[4],
  688.                                         this.Features[5],
  689.                                         this.Features[6],
  690.                                         this.Features[7],
  691.                                         this.DecodedMachineCode,
  692.                                         this.MachineCode,
  693.                                         this.IsOnRightMachine,
  694.                                         this.MaxUsers,
  695.                                         this.MaxAssets,
  696.                                         this.ConcurrentUsers);
  697.         }
  698.  
  699.     }
  700.     #endregion
  701.  
  702.     #region "T H E  C O R E  O F  S K G L"
  703.  
  704.     internal class methods : SerialKeyConfiguration
  705.     {
  706.  
  707.         //The construction of the key
  708.         protected internal string _encrypt(int _users, int _days, bool[] _tfg, string _secretPhase, int ID, System.DateTime _creationDate, int _assets = 0, int _concurrentUsers = 0)
  709.         {
  710.             // This function will store information in Artem's ISF-2
  711.             Random rnd = new Random();
  712.             int _retInt = Convert.ToInt32(_creationDate.ToString("yyyyMMdd"));
  713.             // today
  714.             string keygen = _retInt.ToString("D8");
  715.             // adding the current date; the generation date; today.
  716.             keygen += _days.ToString("D3");
  717.             // adding time left
  718.             keygen += booleanToInt(_tfg).ToString("D3");
  719.             // adding features
  720.             keygen += ID.ToString("D5");
  721.             // adding machineID
  722.             keygen += _users.ToString("D4");
  723.             keygen += _assets.ToString("D3");
  724.             keygen += _concurrentUsers.ToString("D4");
  725.             //add a random number to the end to make a unique license - so that we could revoke it if we want to.
  726.             keygen += rnd.Next(0, 10000).ToString("D5");
  727.             // This part of the function uses Artem's SKA-2
  728.  
  729.             if (string.IsNullOrEmpty(_secretPhase) | _secretPhase == null)
  730.             {
  731.                 // if not password is set, return an unencrypted key
  732.                 return base10ToBase36((getEightByteHash(keygen) + keygen));
  733.             }
  734.             else
  735.             {
  736.                 // if password is set, return an encrypted
  737.                 return base10ToBase36((getEightByteHash(keygen) + _encText(keygen, _secretPhase)));
  738.             }
  739.  
  740.  
  741.         }
  742.         protected internal string _decrypt(string _key, string _secretPhase)
  743.         {
  744.             if (string.IsNullOrEmpty(_secretPhase) | _secretPhase == null)
  745.             {
  746.                 // if not password is set, return an unencrypted key
  747.                 return base36ToBase10(_key);
  748.             }
  749.             else
  750.             {
  751.                 // if password is set, return an encrypted
  752.                 string usefulInformation = base36ToBase10(_key);
  753.                 return usefulInformation.Substring(0, 9) + _decText(usefulInformation.Substring(9), _secretPhase);
  754.             }
  755.  
  756.         }
  757.         //Deeper - encoding, decoding, et cetera.
  758.  
  759.         //Convertions, et cetera.----------------
  760.         protected internal int booleanToInt(bool[] _booleanArray)
  761.         {
  762.             int _aVector = 0;
  763.             //
  764.             //In this function we are converting a binary value array to a int
  765.             //A binary array can max contain 4 values.
  766.             //Ex: new boolean(){1,1,1,1}
  767.  
  768.             for (int _i = 0; _i < _booleanArray.Length; _i++)
  769.             {
  770.                 switch (_booleanArray[_i])
  771.                 {
  772.                     case true:
  773.                         _aVector += Convert.ToInt32((Math.Pow(2, (_booleanArray.Length - _i - 1))));
  774.                         // times 1 has been removed
  775.                         break;
  776.                 }
  777.             }
  778.             return _aVector;
  779.         }
  780.         protected internal bool[] intToBoolean(int _num)
  781.         {
  782.             //In this function we are converting an integer (created with privious function) to a binary array
  783.  
  784.             int _bReturn = Convert.ToInt32(Convert.ToString(_num, 2));
  785.             string _aReturn = _bReturn.ToString("D8");
  786.             bool[] _cReturn = new bool[8];
  787.             for (int i = 0; i <= 7; i++)
  788.             {
  789.                 _cReturn[i] = _aReturn.ToString().Substring(i, 1) == "1" ? true : false;
  790.             }
  791.             return _cReturn;
  792.         }
  793.         protected internal string _encText(string _inputPhase, string _secretPhase)
  794.         {
  795.             //in this class we are encrypting the integer array.
  796.             string _res = "";
  797.  
  798.             for (int i = 0; i <= _inputPhase.Length - 1; i++)
  799.             {
  800.                 _res += modulo(Convert.ToInt32(_inputPhase.Substring(i, 1)) + Convert.ToInt32(_secretPhase.Substring(modulo(i, _secretPhase.Length), 1)), 10);
  801.             }
  802.  
  803.             return _res;
  804.         }
  805.         protected internal string _decText(string _encryptedPhase, string _secretPhase)
  806.         {
  807.             //in this class we are decrypting the text encrypted with the function above.
  808.             string _res = "";
  809.  
  810.             for (int i = 0; i <= _encryptedPhase.Length - 1; i++)
  811.             {
  812.                 _res += modulo(Convert.ToInt32(_encryptedPhase.Substring(i, 1)) - Convert.ToInt32(_secretPhase.Substring(modulo(i, _secretPhase.Length), 1)), 10);
  813.             }
  814.  
  815.             return _res;
  816.         }
  817.  
  818.         protected internal int modulo(int _num, int _base)
  819.         {
  820.             // canged return type to integer.
  821.             //this function simply calculates the "right modulo".
  822.             //by using this function, there won't, hopefully be a negative
  823.             //number in the result!
  824.             return _num - _base * Convert.ToInt32(Math.Floor((decimal)_num / (decimal)_base));
  825.         }
  826.         protected internal string twentyfiveByteHash(string s)
  827.         {
  828.             int amountOfBlocks = s.Length / 5;
  829.             string[] preHash = new string[amountOfBlocks + 1];
  830.  
  831.             if (s.Length <= 5)
  832.             {
  833.                 //if the input string is shorter than 5, no need of blocks!
  834.                 preHash[0] = getEightByteHash(s).ToString();
  835.             }
  836.             else if (s.Length > 5)
  837.             {
  838.                 //if the input is more than 5, there is a need of dividing it into blocks.
  839.                 for (int i = 0; i <= amountOfBlocks - 2; i++)
  840.                 {
  841.                     preHash[i] = getEightByteHash(s.Substring(i * 5, 5)).ToString();
  842.                 }
  843.  
  844.                 preHash[preHash.Length - 2] = getEightByteHash(s.Substring((preHash.Length - 2) * 5, s.Length - (preHash.Length - 2) * 5)).ToString();
  845.             }
  846.             return string.Join("", preHash);
  847.         }
  848.         protected internal int getEightByteHash(string s, int MUST_BE_LESS_THAN = 1000000000)
  849.         {
  850.             //This function generates a eight byte hash
  851.  
  852.             //The length of the result might be changed to any length
  853.             //just set the amount of zeroes in MUST_BE_LESS_THAN
  854.             //to any length you want
  855.             uint hash = 0;
  856.  
  857.             foreach (byte b in System.Text.Encoding.Unicode.GetBytes(s))
  858.             {
  859.                 hash += b;
  860.                 hash += (hash << 10);
  861.                 hash ^= (hash >> 6);
  862.             }
  863.  
  864.             hash += (hash << 3);
  865.             hash ^= (hash >> 11);
  866.             hash += (hash << 15);
  867.  
  868.             int result = (int)(hash % MUST_BE_LESS_THAN);
  869.             int check = MUST_BE_LESS_THAN / result;
  870.  
  871.             if (check > 1)
  872.             {
  873.                 result *= check;
  874.             }
  875.  
  876.             return result;
  877.         }
  878.         internal string licenseCharacters = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz1234567890%$#@*&~";
  879.         protected internal string base10ToBase36(string s)
  880.         {
  881.             // This method is converting a base 10 number to base 26 number.
  882.             // Note that this method will still work, even though you only
  883.             // it is limited at 232 characters with a bigint.
  884.             char[] allowedLetters = licenseCharacters.ToCharArray();
  885.             var numletters = allowedLetters.Count();
  886.             BigInteger num = BigInteger.Parse(s);
  887.             int reminder = 0;
  888.  
  889.             char[] result = new char[s.ToString().Length + 1];
  890.             int j = 0;
  891.  
  892.  
  893.             while ((num >= numletters))
  894.             {
  895.                 reminder = (int)(num % numletters);
  896.                 result[j] = allowedLetters[reminder];
  897.                 num = (num - reminder) / numletters;
  898.                 j += 1;
  899.             }
  900.  
  901.             result[j] = allowedLetters[(int)(num)];
  902.             // final calculation
  903.  
  904.             string returnNum = "";
  905.  
  906.             for (int k = j; k >= 0; k -= 1)  // not sure
  907.             {
  908.                 returnNum += result[k];
  909.             }
  910.             return returnNum;
  911.  
  912.         }
  913.         protected internal string base36ToBase10(string s)
  914.         {
  915.             // This function will convert a number that has been generated
  916.             // with functin above, and get the actual number in decimal
  917.             //
  918.             // This function requieres Mega Math to work correctly.
  919.  
  920.             string allowedLetters = licenseCharacters;
  921.             System.Numerics.BigInteger result = new System.Numerics.BigInteger();
  922.             for (int i = 0; i <= s.Length - 1; i += 1)
  923.             {
  924.                 BigInteger pow = powof(allowedLetters.Length, (s.Length - i - 1));
  925.                 result = result + allowedLetters.IndexOf(s.Substring(i, 1)) * pow;
  926.             }
  927.  
  928.             return result.ToString(); //not sure
  929.         }
  930.         protected internal BigInteger powof(int x, int y)
  931.         {
  932.             // Because of the uncertain answer using Math.Pow and ^,
  933.             // this function is here to solve that issue.
  934.             // It is currently using the MegaMath library to calculate.
  935.             BigInteger newNum = 1;
  936.  
  937.             if (y == 0)
  938.             {
  939.                 return 1;
  940.                 // if 0, return 1, e.g. x^0 = 1 (mathematicaly proven!)
  941.             }
  942.             else if (y == 1)
  943.             {
  944.                 return x;
  945.                 // if 1, return x, which is the base, e.g. x^1 = x
  946.             }
  947.             else
  948.             {
  949.                 for (int i = 0; i <= y - 1; i++)
  950.                 {
  951.                     newNum = newNum * x;
  952.                 }
  953.                 return newNum;
  954.                 // if both conditions are not satisfied, this loop
  955.                 // will continue to y, which is the exponent.
  956.             }
  957.         }
  958.     }
  959.  
  960.  
  961.     #endregion
  962.  
  963.     #endregion
  964. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement