C#安全加密类
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Security.Cryptography; using System.IO; using System.Data; using System.Data.SQLite; using System.Web; using System.Runtime.InteropServices; namespace AiXinTang.User { public static class DbSafe { public static DataTable GetNewDataTable(DataTable dt, string condition, string sortstr) { DataTable newdt = new DataTable(); newdt = dt.Clone(); DataRow[] dr = dt.Select(condition, sortstr); for (int i = 0; i < dr.Length; i++) { newdt.ImportRow((DataRow)dr[i]); } return newdt;//返回的查询结果 } public static string md5(string str, int code) { string mymd5 = string.Empty; if (code == 16) //16位MD5加密(取32位加密的9~25字符) { mymd5 = System.Web.Security.FormsAuthentication.HashPasswordForStoringInConfigFile(str, "MD5").ToLower().Substring(8, 16); } if (code == 32) //32位加密 { mymd5 = System.Web.Security.FormsAuthentication.HashPasswordForStoringInConfigFile(str, "MD5").ToLower(); } return mymd5; } public static string myChar = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789~!@#$%^&*()_+,./;'|:?-={}"; /// <summary> /// 根据制定位数获取不同随机字符串 /// </summary> /// <param name="num"></param> /// <returns></returns> public static string GetStr(int num) { int n = myChar.Length; string str = string.Empty; if (num < n) { Random _currenRandom = new Random(Guid.NewGuid().GetHashCode()); for (int i = 0; i < num; i++) { int _n = _currenRandom.Next(0, n - 1); str += myChar.Substring(_n, 1); } } return str; } /// <summary> /// 生成AES密钥32位 /// </summary> public static string GetAESKey { get { return GetStr(32); } } /// <summary> /// 生成AES常量16位 /// </summary> public static string GetAESIV { get { return GetStr(16); } } /// <summary> /// 生成DES密钥32位 /// </summary> public static string GetDESKey { get { return GetStr(8); } } /// <summary> /// 生成DES常量16位 /// </summary> public static string GetDESIV { get { return GetStr(16); } } } /// <summary> /// DES加密解密 KEY-8 IV-16 /// </summary> public static class DES { /// <summary> /// DES加密 KEY-8 IV-16 /// </summary> /// <param name="plainStr">明文字符串</param> /// <returns>密文</returns> public static string DESEncrypt(string Key, string IV, string plainStr) { byte[] bKey = Encoding.UTF8.GetBytes(Key); byte[] bIV = Encoding.UTF8.GetBytes(IV); byte[] byteArray = Encoding.UTF8.GetBytes(plainStr); string encrypt = null; DESCryptoServiceProvider des = new DESCryptoServiceProvider(); try { using (MemoryStream mStream = new MemoryStream()) { using (CryptoStream cStream = new CryptoStream(mStream, des.CreateEncryptor(bKey, bIV), CryptoStreamMode.Write)) { cStream.Write(byteArray, 0, byteArray.Length); cStream.FlushFinalBlock(); encrypt = Convert.ToBase64String(mStream.ToArray()); } } } catch { } des.Clear(); return encrypt; } /// <summary> /// DES解密 KEY-8 IV-16 /// </summary> /// <param name="encryptStr">密文字符串</param> /// <returns>明文</returns> public static string DESDecrypt(string Key, string IV, string encryptStr) { byte[] bKey = Encoding.UTF8.GetBytes(Key); byte[] bIV = Encoding.UTF8.GetBytes(IV); byte[] byteArray = Convert.FromBase64String(encryptStr); string decrypt = null; DESCryptoServiceProvider des = new DESCryptoServiceProvider(); try { using (MemoryStream mStream = new MemoryStream()) { using (CryptoStream cStream = new CryptoStream(mStream, des.CreateDecryptor(bKey, bIV), CryptoStreamMode.Write)) { cStream.Write(byteArray, 0, byteArray.Length); cStream.FlushFinalBlock(); decrypt = Encoding.UTF8.GetString(mStream.ToArray()); } } } catch { } des.Clear(); return decrypt; } } /// <summary> /// AES加密解密 KEY-32 IV-16 /// </summary> public static class AES { /// <summary> /// AES加密 KEY-32 IV-16 /// </summary> /// <param name="plainStr">明文字符串</param> /// <returns>密文</returns> public static string AESEncrypt(string Key, string IV, string plainStr) { byte[] bKey = Encoding.UTF8.GetBytes(Key); byte[] bIV = Encoding.UTF8.GetBytes(IV); byte[] byteArray = Encoding.UTF8.GetBytes(plainStr); string encrypt = null; Rijndael aes = Rijndael.Create(); try { using (MemoryStream mStream = new MemoryStream()) { using (CryptoStream cStream = new CryptoStream(mStream, aes.CreateEncryptor(bKey, bIV), CryptoStreamMode.Write)) { cStream.Write(byteArray, 0, byteArray.Length); cStream.FlushFinalBlock(); encrypt = Convert.ToBase64String(mStream.ToArray()); } } } catch { } aes.Clear(); return encrypt; } /// <summary> /// AES解密 KEY-32 VI-IV /// </summary> /// <param name="encryptStr">密文字符串</param> /// <returns>明文</returns> public static string AESDecrypt(string Key, string IV, string encryptStr) { byte[] bKey = Encoding.UTF8.GetBytes(Key); byte[] bIV = Encoding.UTF8.GetBytes(IV); byte[] byteArray = Convert.FromBase64String(encryptStr); string decrypt = null; Rijndael aes = Rijndael.Create(); try { using (MemoryStream mStream = new MemoryStream()) { using (CryptoStream cStream = new CryptoStream(mStream, aes.CreateDecryptor(bKey, bIV), CryptoStreamMode.Write)) { cStream.Write(byteArray, 0, byteArray.Length); cStream.FlushFinalBlock(); decrypt = Encoding.UTF8.GetString(mStream.ToArray()); } } } catch { } aes.Clear(); return decrypt; } } /// <summary> /// SQLITE操作 /// </summary> public static class Sqlite { /// <summary> /// 是否链接成功 /// </summary> /// <param name="path"></param> /// <param name="pwd"></param> /// <returns></returns> public static bool IfConn(string path, string pwd) { bool r = false; if (!string.IsNullOrEmpty(path)) { var con = new SQLiteConnection(); if (!string.IsNullOrEmpty(pwd)) { con.ConnectionString = String.Format("Data Source={0};Version=3;Password={1}", path.Trim(), pwd.Trim()); } else { con.ConnectionString = String.Format("Data Source={0};Version=3;", path.Trim()); } try { con.Open(); r = true; } catch { r = false; } finally { con.Close(); } } return r; } /// <summary> /// 重置数据库链接密码 /// </summary> /// <param name="path"></param> /// <param name="pwdold"></param> /// <param name="pwdnew"></param> /// <returns></returns> public static bool SetPwd(string path, string pwdold, string pwdnew) { bool r = false; var con = new SQLiteConnection(); if (!string.IsNullOrEmpty(pwdold)) { con.ConnectionString = String.Format("Data Source={0};Version=3;Password={1}", path.Trim(), pwdold.Trim()); } else { con.ConnectionString = String.Format("Data Source={0};Version=3;", path.Trim()); } try { con.Open(); if (!string.IsNullOrEmpty(pwdnew.Trim())) { con.ChangePassword(pwdnew.Trim()); } r = true; } catch { r = false; } finally { con.Close(); } return r; } [DllImport("kernel32.dll")] public static extern IntPtr _lopen(string lpPathName, int iReadWrite); [DllImport("kernel32.dll")] public static extern bool CloseHandle(IntPtr hObject); /// <summary> /// 创建新的用户数据库 /// </summary> /// <param name="name"></param> /// <returns></returns> public static bool DbNew(string name,string pwd) { bool r = false; string path = HttpContext.Current.Server.MapPath(HttpContext.Current.Request.ApplicationPath.TrimEnd('\\')+@"\app_data\"); if (File.Exists(path + "AXT.User.Demo.config") && !File.Exists(path + name + ".config")) { File.Copy(path + "AXT.User.Demo.config", path + name+".config"); if (File.Exists(path + name + ".config")) { const int OF_READWRITE = 2; const int OF_SHARE_DENY_NONE = 0x40; IntPtr HFILE_ERROR = new IntPtr(-1); IntPtr vHandle = _lopen(path + name + ".config", OF_READWRITE | OF_SHARE_DENY_NONE); CloseHandle(vHandle); if (SetPwd(path + name + ".config", "", pwd)) { r = true; } } } return r; } public static bool IsFileInUse(string fileName) { bool inUse = true; FileStream fs = null; try { fs = new FileStream(fileName, FileMode.Open, FileAccess.Read, FileShare.None); inUse = false; } catch { } finally { if (fs != null) fs.Close(); } return inUse; } } }