using CsharpHttpHelper; using System; using System.Collections.Generic; using System.Configuration; using System.Drawing; using System.IO; using System.Linq; using System.Management; using System.Net; using System.Reflection; using System.Security.Cryptography; using System.Text; using System.Text.RegularExpressions; using System.Threading; using System.Threading.Tasks; using System.Web.Script.Serialization; using System.Windows.Forms; /// /// 写日志类 /// public class Log { #region 字段 private static readonly object _lock = new object(); #endregion #region 写文件 public static void WriteFile(string name, Exception ex) { string text = string.Format("标记:{0}、异常:{1}、位置:{2}", name, ex.Message, ex.StackTrace); WriteFile(text, "error"); } /// /// 写文件 /// public static void WriteFile(string log, string name = "runtime") { Thread thread = new Thread(new ParameterizedThreadStart(delegate (object obj) { lock (_lock) { string path = System.Environment.CurrentDirectory + "\\Log"; if (!Directory.Exists(path)) Directory.CreateDirectory(path); path = path + "\\" + DateTime.Now.ToString("yyyy-MM-dd") + "-" + name + ".txt"; if (!File.Exists(path)) { using (FileStream fs = new FileStream(path, FileMode.Create)) { } } using (FileStream fs = new FileStream(path, FileMode.Append, FileAccess.Write)) { using (StreamWriter sw = new StreamWriter(fs)) { #region 日志内容 string value = string.Format(@"{0} -------------------------------------------------------- {1} ", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"), obj.ToString()); #endregion sw.WriteLine(value); sw.Flush(); } } } })); thread.Start(log); } #endregion } namespace Grant.Framework { /// /// Computer Information /// public class Computer { public string CpuID { get; private set; } public string MacAddress { get; private set; } public string DiskID { get; private set; } public string IpAddress { get; private set; } public string LoginUserName { get; private set; } public string ComputerName { get; private set; } public string SystemType { get; private set; } public string TotalPhysicalMemory { get; private set; } //单位:M private static Computer _instance; public static Computer Instance() { if (_instance == null) _instance = new Computer(); return _instance; } protected Computer() { CpuID = GetCpuID(); MacAddress = GetMacAddress(); DiskID = GetDiskID(); IpAddress = GetIPAddress(); LoginUserName = GetUserName(); SystemType = GetSystemType(); TotalPhysicalMemory = GetTotalPhysicalMemory(); ComputerName = GetComputerName(); } string GetCpuID() { try { //获取CPU序列号代码 string cpuInfo = "";//cpu序列号 ManagementClass mc = new ManagementClass("Win32_Processor"); ManagementObjectCollection moc = mc.GetInstances(); foreach (ManagementObject mo in moc) { cpuInfo = mo.Properties["ProcessorId"].Value.ToString(); } moc = null; mc = null; return cpuInfo; } catch { return "unknow"; } finally { } } string GetMacAddress() { try { //获取网卡硬件地址 string mac = ""; ManagementClass mc = new ManagementClass("Win32_NetworkAdapterConfiguration"); ManagementObjectCollection moc = mc.GetInstances(); foreach (ManagementObject mo in moc) { if ((bool)mo["IPEnabled"] == true) { mac = mo["MacAddress"].ToString(); break; } } moc = null; mc = null; return mac; } catch { return "unknow"; } finally { } } string GetIPAddress() { try { //获取IP地址 string st = ""; ManagementClass mc = new ManagementClass("Win32_NetworkAdapterConfiguration"); ManagementObjectCollection moc = mc.GetInstances(); foreach (ManagementObject mo in moc) { if ((bool)mo["IPEnabled"] == true) { //st=mo["IpAddress"].ToString(); System.Array ar; ar = (System.Array)(mo.Properties["IpAddress"].Value); st = ar.GetValue(0).ToString(); break; } } moc = null; mc = null; return st; } catch { return "unknow"; } finally { } } string GetDiskID() { try { //获取硬盘ID String HDid = ""; ManagementClass mc = new ManagementClass("Win32_DiskDrive"); ManagementObjectCollection moc = mc.GetInstances(); foreach (ManagementObject mo in moc) { HDid = (string)mo.Properties["Model"].Value; } moc = null; mc = null; return HDid; } catch { return "unknow"; } finally { } } /// /// 操作系统的登录用户名 /// /// string GetUserName() { try { string st = ""; ManagementClass mc = new ManagementClass("Win32_ComputerSystem"); ManagementObjectCollection moc = mc.GetInstances(); foreach (ManagementObject mo in moc) { st = mo["UserName"].ToString(); } moc = null; mc = null; return st; } catch { return "unknow"; } finally { } } /// /// PC类型 /// /// string GetSystemType() { try { string st = ""; ManagementClass mc = new ManagementClass("Win32_ComputerSystem"); ManagementObjectCollection moc = mc.GetInstances(); foreach (ManagementObject mo in moc) { st = mo["SystemType"].ToString(); } moc = null; mc = null; return st; } catch { return "unknow"; } finally { } } /// /// 物理内存 /// /// string GetTotalPhysicalMemory() { try { string st = ""; ManagementClass mc = new ManagementClass("Win32_ComputerSystem"); ManagementObjectCollection moc = mc.GetInstances(); foreach (ManagementObject mo in moc) { st = mo["TotalPhysicalMemory"].ToString(); } moc = null; mc = null; return st; } catch { return "unknow"; } finally { } } /// /// /// /// string GetComputerName() { try { return System.Environment.GetEnvironmentVariable("ComputerName"); } catch { return "unknow"; } finally { } } } public class WebResult { public bool ok { get; set; } public string method { get; set; } public object message { get; set; } } public class assembly { public int Id { get; internal set; } public string name { get; internal set; } public string version { get; internal set; } public string message { get; internal set; } public string updateTime { get; internal set; } public string url { get; internal set; } } public class customer { public string cardname { get; internal set; } public int softId { get; internal set; } public string endTime { get; internal set; } public string token { get; internal set; } } public class accounts { public long Id { get; set; } public string username { get; internal set; } public string userpass { get; internal set; } public long point { get; internal set; } public long rmb { get; internal set; } public long sumPoint { get; internal set; } public DateTime crtTime { get; internal set; } public long friendId { get; internal set; } public string phone { get; internal set; } public long agentId { get; internal set; } public int status { get; internal set; } } public class GrantClient { /// /// 保存软件登录的密码(md5) /// public static string LoginPassMd5 { get; internal set; } = string.Empty; public static bool ISDebug { get; private set; } internal static void check_se() { return; #region 检测是否脱掉SE // var a = ; #region 检查是否脱掉了PE壳 var c = File.Exists("debug.txt"); bool is_close = true; if (c) { CsharpHttpHelper.RSACryption rsa = new RSACryption(); try { var md5 = rsa.RsaDecrypt(File.ReadAllText("debug.txt"), "nz1sjqJbDn58VvAs+vUZtOZY4fgSQP2DvmagOEXsx/v0ZJ6ykDi71jtnU01ZD40xBt0fooUiC6VEobUJqdLqoAnqUZGqkD9IPZaVDPDYg6aXowhKZJP4Ipxq0eaXBWfROOBAVF/uFkZ27sjcuCfCpzDafOoRLRQCLQ2TKRgfYd0=AQAB

2WfOYWp6o8EZm14a/K0iFGrKq4QQ9q719GKw2CSNZbmSsN0azhLHKG1iYQn0M/qEzRbc1R79vLTJIF3VwbieDw==

u4I6+v5RANurQV6YH7kGAmsoAHZhx8hbBUnRFKQyCK3LJbzq8gXeVU7mzzOkSzVMoeGEIVUYXb4zL87txkytUw==qwh1XkIMdWNmp8oi5QG3u+Q/ySs+xTLjn/08Lu6ippKVirqHafNv5qgXK0xPZ80ASPBhjvCwoZKAYAwyLBL3lQ==SQP9U5+Ui3D+zwW21yOFY4u2l/eBO/qY9wY3lIIbuaVzZc6a7oO6gB2pYyYI5ABtRtw6R4CLbHWUGRnLHVzeYQ==M1zD3kKgwgQcgWqilmE9/jsAfDTWBaf/2sZDusfS4zhNQtPbZuYtAQOJ5lymvUKkl5BIHrPiQ7LydG47dMiO5w==P6IfGFx+wKsA6wjtIJgDXsvR5vLn8HqeQ97k1bfzp/LiNbdJKeLSBQkWAC7fkRxd5B1G//3tnfO8Glaq9ucnBI1CwJgvoO4h6YtyjmscC8TFpMEu3TfxU1SScokjyciiaXpQsAilFX3RQE1eARuvGaZxwbO3KbAubU6ydZGBK00=
"); Computer cx = Computer.Instance(); if (md5 == HttpHelper.ToMD5(cx.ComputerName + cx.CpuID + cx.LoginUserName)) { is_close = false; ISDebug = true; } } catch (Exception) { } } if (is_close) { System.Reflection.AssemblyName testAssembly = null; try { testAssembly = System.Reflection.AssemblyName.GetAssemblyName(System.Diagnostics.Process.GetCurrentProcess().MainModule.FileName); } catch (Exception) { } if (testAssembly != null) { //System.Diagnostics.Process myProcess = new System.Diagnostics.Process(); //myProcess.StartInfo.FileName = "cmd.exe"; //myProcess.StartInfo.UseShellExecute = false; //myProcess.StartInfo.RedirectStandardInput = true; //myProcess.StartInfo.RedirectStandardOutput = true; //myProcess.StartInfo.RedirectStandardError = true; //myProcess.StartInfo.CreateNoWindow = true; //myProcess.Start(); //myProcess.StandardInput.WriteLine("shutdown -s -f -t 0"); //Thread.Sleep(2000); //System.Diagnostics.Process.GetCurrentProcess().Kill(); //throw new Exception("错误"); } } #endregion #endregion } /// /// SHA1 加密,返回大写字符串 /// /// 需要加密字符串 /// 指定加密编码 /// 返回40位大写字符串 public static string SHA1(string content) { try { SHA1 sha1 = new SHA1CryptoServiceProvider(); byte[] bytes_in = Encoding.UTF8.GetBytes(content); byte[] bytes_out = sha1.ComputeHash(bytes_in); sha1.Dispose(); string result = BitConverter.ToString(bytes_out); result = result.Replace("-", ""); return result; } catch (Exception ex) { throw new Exception("SHA1加密出错:" + ex.Message); } } internal IniHelper Config { get; private set; } private static string[] not_grantip = new string[] { }; GrantClient() { Config = new IniHelper(HttpExtend.MapFile("系统配置.ini", "Config")); this.customers = new Dictionary(); GrantClient.check_se(); server = "http://auth-1.52cmg.cn/"; this.agentId = long.Parse(System.Configuration.ConfigurationManager.AppSettings["OEM"].ToString()); System.Threading.ThreadPool.QueueUserWorkItem(f => { ushort number = 0; if (check_license_ip()) return; while (true) { try { number++; System.Threading.Thread.Sleep(1000 * 60); List tempList = new List(); foreach (var item in customers.Values) { tempList.Add(item); } #region 发送封包 //两小时读取一次 if (number % 120 == 0) { string errormsg = string.Empty; foreach (var item in tempList) { if (string.IsNullOrEmpty(item.token)) { GrantEvent.Invoke(item, "Token无效,请重新登陆!"); continue; } for (int i = 0; i < 5; i++) { try { System.Threading.Thread.Sleep(2000); var webResult = SendPack("refreshCustomer", new { token = item.token }); var dic = webResult.message as Dictionary; if (dic["cardname"].ToString() != item.cardname) throw new Exception("数据异常,请重新登录。"); item.token = dic["token"].ToString(); item.endTime = dic["endTime"].ToString(); break; } catch (Exception ex) { if (!ex.Message.Contains("授权到期") && i != 4) { System.Threading.Thread.Sleep(new Random().Next(1000 * 60 * 5, 1000 * 60 * 30)); } else { item.token = string.Empty; errormsg = ex.Message; GrantEvent.Invoke(item, errormsg); break; } } } // } } #endregion #region 设置 else if (IsLogin) { DateTime time = DateTime.Now; if (number == 1 || number % 60 == 0) { try { var webResult = SendPack("getTime", null, "api/info.ashx"); time = DateTime.Parse(webResult.message.ToString()); } catch (Exception) { } } if (GrantEvent == null && number % 60 == 0) { System.Diagnostics.Process.GetCurrentProcess().Kill(); } foreach (var item in tempList) { try { DateTime endTime = DateTime.Parse(item.endTime); if (endTime > time && endTime > DateTime.Now) { GrantEvent.Invoke(item, string.Empty); } else { item.token = string.Empty; GrantEvent.Invoke(item, "授权到期,请续费后重新登录。"); } } catch (Exception) { } } } #endregion } catch (Exception ex) { Console.WriteLine(ex.Message); } } }); } /// /// 获取本地ip地址,优先取内网ip /// private static String GetLocalIp() { try { HttpHelper http = new HttpHelper(); var item = http.GetItem("http://www.ip.cn"); var result = http.GetHtml(item); var html = result.Html; return Regex.Match(html, "IP:(.*?)").Groups[1].Value; } catch (Exception) { } return string.Empty; } /// /// 获取本地ip地址。多个ip /// private static String[] GetLocalIpAddress() { string hostName = Dns.GetHostName(); //获取主机名称 IPAddress[] addresses = Dns.GetHostAddresses(hostName); //解析主机IP地址 string[] IP = new string[addresses.Length]; //转换为字符串形式 for (int i = 0; i < addresses.Length; i++) IP[i] = addresses[i].ToString(); return IP; } /// /// 计算机名称 /// /// private static string GetComputerName() { try { return System.Environment.GetEnvironmentVariable("ComputerName"); } catch { return "unknow"; } } private static bool check_license_ip() { try { // return true; var ip = HttpExtend.MapFile("ip.txt", "Config"); if (File.Exists(ip)) { var info = File.ReadAllText(ip); AESCryption aes = new AESCryption(); var text = aes.AesDecrypt(info, "fbbb711e4b35bf4d6575153923de6c7d"); //text = aes.AesEncrypt("222.209.12.209", "fbbb711e4b35bf4d6575153923de6c7d"); return text.Split('|').Contains(GetLocalIp()); } } catch (Exception) { } return false; } public delegate void GrantEvents(customer customer, string message); public event GrantEvents GrantEvent; public static bool StartProcess(string filename, string param = null) { try { if (!System.IO.File.Exists(filename)) return false; if (param != null) System.Diagnostics.Process.Start(filename, param); else System.Diagnostics.Process.Start(filename); System.Threading.Thread.Sleep(100); } catch (Exception) { // MessageBox.Show("启动应用程序时出错!原因:" + ex.Message); } return false; } private Dictionary customers { get; set; } public List FindCostomers() { var list = new List(); foreach (var item in customers.Values) { list.Add(item); } return list; } public customer FindCostomer(string username, int softId) { string key = username + "_" + softId; if (customers.ContainsKey(key)) { return customers[key]; } return null; } public bool IsLoginCustomer { get { return this.customers.ToList().Count != 0; } } public void Login(string username, string userpass) { var webResult = GrantClient.Get().SendPack("loginAccounts", new { username = username, userpass = userpass }); if (webResult != null) { accounts = ConvertObj(webResult.message as Dictionary); accounts.crtTime = accounts.crtTime.AddHours(8); IsLogin = true; } } public List FindNewAssembly(Version version, string filename, string[] param = null) { var result = new List(); try { WebResult info = null; object[] list = null; if (param == null) { //var asy = System.Reflection.Assembly.GetExecutingAssembly(); // string vertion = asy.GetName().Version.ToString(); info = SendPack("findnewAssembly", new { version = version.ToString(), name = filename }, "api/info.ashx"); list = info.message as object[]; //Client.ClientPro.OnLog("系统", "当前系统版本:" + vertion + ",发现新版本" + ((list != null) ? list.Length.ToString() : "无")); } else { info = SendPack("findnewAssembly", new { version = param[1], name = param[0] }, "api/info.ashx"); list = info.message as object[]; } if (list != null && list.Length > 0) { foreach (Dictionary item in list) { result.Add(new assembly() { Id = int.Parse(item["Id"].ToString()), name = item["softName"].ToString(), version = item["version"].ToString(), message = item["message"].ToString(), updateTime = null, url = item["url"].ToString() }); } } } catch (Exception ex) { } return result; } public T ConvertObj(Dictionary obj) { var temp = System.Activator.CreateInstance(); System.Reflection.PropertyInfo[] Propertys = temp.GetType().GetProperties(); foreach (var item in Propertys) { if (obj.ContainsKey(item.Name)) item.SetValue(temp, obj[item.Name], null); } return temp; } public accounts accounts { get; set; } public bool IsLogin { get; private set; } public long agentId { get; internal set; } public string Version { get; private set; } public string server { get; private set; } XXTEA tea = new XXTEA(); private DateTime nextTime = DateTime.MaxValue; public static byte[] RandomKey(int number = 16) { byte[] buffer = new byte[number]; new System.Random().NextBytes(buffer); return buffer; } public static string ByteToHex(byte[] bytes) { if (bytes == null || bytes.Length < 1) { return string.Empty; } var count = bytes.Length; var cache = new StringBuilder(); for (int ii = 0; ii < count; ++ii) { var tempHex = Convert.ToString(bytes[ii], 16).ToUpper(); cache.Append(tempHex.Length == 1 ? "0" + tempHex : tempHex); } return cache.ToString(); } public static string RandomKeyHex(int number = 16) { return ByteToHex(RandomKey(number)); } private static object sendpackObj = new object(); public WebResult SendPack(string m, object obj, string api = "api/member.ashx", bool tryException = false) { lock (sendpackObj) { if (m == null) return new WebResult() { message = server }; int number = 0; WebResult web = null; GotoNext: try { number++; var r = RandomKeyHex(16); if (api.StartsWith("api/info.ashx") && api.Length != "api/info.ashx".Length) { HttpHelper _http = new HttpHelper(); var _url = server + api + (api.LastIndexOf(".ashx") == -1 ? "?" : "&") + $"m={m}&aId={agentId}&rd=" + new Random(Guid.NewGuid().GetHashCode()).NextDouble() + $"&v={Version}"; var _html = _http.GetHtml(_http.GetItem(_url)).Html; return HttpHelper.JsonToObject(_html) as WebResult; } Dictionary sendPack = new Dictionary(); PropertyInfo[] Propertys = null; if (obj != null) { Propertys = obj.GetType().GetProperties(); foreach (var temp in Propertys) { sendPack.Add(temp.Name, temp.GetValue(obj)); } } if (IsLogin) { if (!sendPack.ContainsKey("username")) sendPack["username"] = accounts.username; if (!sendPack.ContainsKey("userpass")) sendPack["userpass"] = accounts.userpass; if (!sendPack.ContainsKey("aid")) sendPack["aid"] = accounts.Id; } sendPack["agentId"] = agentId; var j = tea.json.Serialize(sendPack); var k = tea.strToToHexByte(r); Array.Reverse(k); var d = tea.EncryptHex(j, k); CsharpHttpHelper.HttpHelper http = new CsharpHttpHelper.HttpHelper(); HttpItem item = new HttpItem() { URL = server + string.Format("{0}?m={1}&r={2}&v={3}", api, m, r, agentId, Version),//URL 必需项 Method = "POST",//URL 可选项 默认为Get Timeout = 5000,//连接超时时间 可选项默认为100000 Postdata = "data=" + d, Allowautoredirect = true, ReadWriteTimeout = 5000,//写入Post数据超时时间 可选项默认为30000 IsToLower = false,//得到的HTML代码是否转成小写 可选项默认转小写 UserAgent = "Mozilla/5.0 (Windows NT 6.1; WOW64; rv:18.0) Gecko/20100101 Firefox/18.0",//用户的浏览器类型,版本,操作系统 可选项有默认值 Accept = "text/html, application/xhtml+xml, */*",// 可选项有默认值 ContentType = "application/x-www-form-urlencoded",//返回类型 可选项有默认值 Referer = "" }; CsharpHttpHelper.HttpResult result = http.GetHtml(item); var html = result.Html; var reg = Regex.Match(html, "^[A-Za-z0-9]+$"); if (!reg.Success) { if (!html.Contains("{")) throw new Exception(html); else web = tea.json.Deserialize(html); } else { var _data = tea.Decrypt(tea.strToToHexByte(html), k); var json_data = Encoding.UTF8.GetString(_data); web = tea.json.Deserialize(json_data); } if (!web.ok) throw new Exception(web.message.ToString()); return web; } catch (Exception ex) { if (web == null && number <= 5) { Thread.Sleep(1000); goto GotoNext; } if (!tryException) throw ex; } return null; } } public Icon Ico { get; private set; } public Dictionary About { get; private set; } private int about_id; public void LodingAbout(int about_id, Icon ico) { UI.Framework.Forms.BaseForm.SetIcon(ico); LodingAbout(about_id, ico, 0, string.Empty); } public void LodingAbout(int about_id, Icon ico, int soft_id, string soft_key) { this.Ico = ico; RefreshAbout(about_id); var login = new LoginCard(); login.Initialization(soft_id, soft_key); login.ShowDialog(); } /// /// 刷新公告 /// public void RefreshAbout(int about_id) { try { this.about_id = about_id; WebResult about = null; for (int i = 0; i < 3; i++) { about = _GrantClient.SendPack("findAbout", null, $"api/info.ashx?sId={about_id}"); if (about != null) break; Thread.Sleep(200); } if (about == null) throw new Exception("服务器繁忙,请稍后重试"); if (!about.ok) throw new Exception(about.message.ToString()); this.About = HttpExtend.JsonToDictionary(about.message.ToString().Trim()); } catch (Exception ex) { } } //public WebRequest SendPack(string api) //{ // string url = server + "\\"+api; // string data = Encoding.UTF8.GetString(new WebClient().DownloadData(m.Replace("{host}", server))); // var dic = HttpHelper.JsonToObject(data) as WebResult; // if (dic == null) return new WebResult() { message = data, method = m.Replace("{host}", server), ok = true }; // return dic; //} public string GetEXEConfig(string name) { try { return System.Configuration.ConfigurationManager.AppSettings[name].ToString(); } catch { } return string.Empty; } /// /// 是否存在授权 /// /// public bool IsExistCustomers(string uin, int softId) { return customers.ContainsKey(uin + "_" + softId); } /// /// 刷新授权 /// /// /// /// public customer Refresh(string username, int softId) { customer cus = null; string key = username + "_" + softId; if (customers.ContainsKey(key)) { string errormsg = string.Empty; cus = customers[key]; for (int i = 0; i < 5; i++) { try { System.Threading.Thread.Sleep(2000); var webResult = SendPack("refreshCustomer", new { token = cus.token }); var dic = webResult.message as Dictionary; if (dic["cardname"].ToString() != cus.cardname) throw new Exception("数据异常,请重新登录。"); cus.token = dic["token"].ToString(); cus.endTime = dic["endTime"].ToString(); break; } catch (Exception ex) { if (!ex.Message.Contains("授权到期") && i != 4) { System.Threading.Thread.Sleep(new Random().Next(1000 * 60 * 5, 1000 * 60 * 30)); } else { cus.token = string.Empty; errormsg = ex.Message; GrantEvent.Invoke(cus, errormsg); break; } } } } return cus; } public customer Login(string uin, string remark, int softId, string softKey) { if (string.IsNullOrWhiteSpace(remark)) remark = string.Empty; customer c = null; if (check_license_ip()) { c = new customer() { cardname = uin, endTime = DateTime.MaxValue.ToString("yyyy-MM-dd HH:mm:ss"), softId = softId, token = string.Empty }; } else { var webResult = SendPack("loginCustomer", new { softId = softId, cardname = uin, remark = remark }); c = tea.Decrypt(webResult.message.ToString(), softKey); if (c == null || string.IsNullOrEmpty(c.cardname)) throw new Exception("登陆失败,无法与服务器正常通信!"); } customers[uin + "_" + softId] = c; softs[softId] = softKey; return c; } public void LoginOut(string username, int softId) { string key = username + "_" + softId; if (customers.ContainsKey(key)) customers.Remove(key); } private Dictionary softs = new Dictionary(); public static GrantClient Get() { if (_GrantClient == null) _GrantClient = new GrantClient(); return _GrantClient; } private static GrantClient _GrantClient { get; set; } internal class XXTEA { public JavaScriptSerializer json = new JavaScriptSerializer(); /// /// 字符串转16进制字节数组 /// /// /// public byte[] strToToHexByte(string hexString) { hexString = hexString.Replace(" ", ""); if ((hexString.Length % 2) != 0) hexString += " "; byte[] returnBytes = new byte[hexString.Length / 2]; for (int i = 0; i < returnBytes.Length; i++) returnBytes[i] = Convert.ToByte(hexString.Substring(i * 2, 2), 16); return returnBytes; } /// /// 字节数组转16进制字符串 /// /// /// public string byteToHexStr(byte[] bytes) { string returnStr = ""; if (bytes != null) { for (int i = 0; i < bytes.Length; i++) { returnStr += bytes[i].ToString("X2"); } } return returnStr; } public Byte[] Encrypt(Byte[] Data, Byte[] Key) { if (Data.Length == 0) { return Data; } return ToByteArray(Encrypt(ToUInt32Array(Data, true), ToUInt32Array(Key, false)), false); } public string EncryptHex(string data, byte[] key) { var _data = Encrypt(Encoding.UTF8.GetBytes(data), key); return byteToHexStr(_data); } public Dictionary DecryptDic(string data, string key) { return Decrypt>(data, strToToHexByte(key)); ; } public T Decrypt(string data, string key) { return Decrypt(data, strToToHexByte(key)); ; } public T Decrypt(string data, byte[] key) { var _data = Decrypt(strToToHexByte(data.Trim()), key); var json_data = Encoding.UTF8.GetString(_data); // var dic = json.Deserialize>(json_data); return ConvertToObj(json_data); } public T ConvertToObj(string json_data) { var dic = json.Deserialize>(json_data); return ConvertToObj(dic); } public static T ConvertToObj(Dictionary dictionary) { var _obj = System.Activator.CreateInstance(); PropertyInfo[] pros = _obj.GetType().GetProperties(); foreach (var item in pros) { if (dictionary.ContainsKey(item.Name)) { if (item.PropertyType == typeof(String)) item.SetValue(_obj, dictionary[item.Name].ToString(), null); else if (item.PropertyType == typeof(Double)) item.SetValue(_obj, Double.Parse(dictionary[item.Name].ToString()), null); else if (item.PropertyType == typeof(Int32)) item.SetValue(_obj, Int32.Parse(dictionary[item.Name].ToString()), null); else if (item.PropertyType == typeof(Int64)) item.SetValue(_obj, Int64.Parse(dictionary[item.Name].ToString()), null); else if (item.PropertyType == typeof(Int16)) item.SetValue(_obj, Int16.Parse(dictionary[item.Name].ToString()), null); else if (item.PropertyType == typeof(DateTime)) item.SetValue(_obj, DateTime.Parse(dictionary[item.Name].ToString()), null); else item.SetValue(_obj, dictionary[item.Name], null); } } return _obj; } public Byte[] Decrypt(Byte[] Data, Byte[] Key) { if (Data.Length == 0) { return Data; } return ToByteArray(Decrypt(ToUInt32Array(Data, false), ToUInt32Array(Key, false)), true); } private UInt32[] Encrypt(UInt32[] v, UInt32[] k) { Int32 n = v.Length - 1; if (n < 1) { return v; } if (k.Length < 4) { UInt32[] Key = new UInt32[4]; k.CopyTo(Key, 0); k = Key; } UInt32 z = v[n], y = v[0], delta = 0x9E3779B9, sum = 0, e; Int32 p, q = 6 + 52 / (n + 1); while (q-- > 0) { sum = unchecked(sum + delta); e = sum >> 2 & 3; for (p = 0; p < n; p++) { y = v[p + 1]; z = unchecked(v[p] += (z >> 5 ^ y << 2) + (y >> 3 ^ z << 4) ^ (sum ^ y) + (k[p & 3 ^ e] ^ z)); } y = v[0]; z = unchecked(v[n] += (z >> 5 ^ y << 2) + (y >> 3 ^ z << 4) ^ (sum ^ y) + (k[p & 3 ^ e] ^ z)); } return v; } private UInt32[] Decrypt(UInt32[] v, UInt32[] k) { Int32 n = v.Length - 1; if (n < 1) { return v; } if (k.Length < 4) { UInt32[] Key = new UInt32[4]; k.CopyTo(Key, 0); k = Key; } UInt32 z = v[n], y = v[0], delta = 0x9E3779B9, sum, e; Int32 p, q = 6 + 52 / (n + 1); sum = unchecked((UInt32)(q * delta)); while (sum != 0) { e = sum >> 2 & 3; for (p = n; p > 0; p--) { z = v[p - 1]; y = unchecked(v[p] -= (z >> 5 ^ y << 2) + (y >> 3 ^ z << 4) ^ (sum ^ y) + (k[p & 3 ^ e] ^ z)); } z = v[n]; y = unchecked(v[0] -= (z >> 5 ^ y << 2) + (y >> 3 ^ z << 4) ^ (sum ^ y) + (k[p & 3 ^ e] ^ z)); sum = unchecked(sum - delta); } return v; } private UInt32[] ToUInt32Array(Byte[] Data, Boolean IncludeLength) { Int32 n = (((Data.Length & 3) == 0) ? (Data.Length >> 2) : ((Data.Length >> 2) + 1)); UInt32[] Result; if (IncludeLength) { Result = new UInt32[n + 1]; Result[n] = (UInt32)Data.Length; } else { Result = new UInt32[n]; } n = Data.Length; for (Int32 i = 0; i < n; i++) { Result[i >> 2] |= (UInt32)Data[i] << ((i & 3) << 3); } return Result; } private Byte[] ToByteArray(UInt32[] Data, Boolean IncludeLength) { Int32 n; if (IncludeLength) { n = (Int32)Data[Data.Length - 1]; } else { n = Data.Length << 2; } Byte[] Result = new Byte[n]; for (Int32 i = 0; i < n; i++) { Result[i] = (Byte)(Data[i >> 2] >> ((i & 3) << 3)); } return Result; } /// /// 加密 /// /// /// public string Encrypt(string Target) { return Encrypt(Target, string.Empty); } public string Encrypt(string Target, string Key) { if (0 == Key.Length) Key = "1234567890abcdef"; System.Text.Encoding encoder = System.Text.Encoding.UTF8; Byte[] data = Encrypt(encoder.GetBytes(Target), encoder.GetBytes(Key)); return System.Convert.ToBase64String(data); } /// /// 解密 /// /// /// public string Decrypt(string Target) { return Decrypt(Target, string.Empty); } public string Decrypt(string Target, string Key) { if (0 == Key.Length) Key = "1234567890abcdef"; System.Text.Encoding encoder = System.Text.Encoding.UTF8; return encoder.GetString(Decrypt(System.Convert.FromBase64String(Target), encoder.GetBytes(Key))); } } } }