C#工具:加密解密帮助类
using System; using System.IO; using System.Security.Cryptography; using System.Text; //加密字符串,注意strEncrKey的长度为8位(如果要增加或者减少key长度,调整IV的长度就是了) //public string DesEncrypt(string strText, string strEncrKey) //解密字符串,注意strEncrKey的长度为8位(如果要增加或者减少key长度,调整IV的长度就是了) //public string DesDecrypt(string strText,string sDecrKey) //加密数据文件,注意strEncrKey的长度为8位(如果要增加或者减少key长度,调整IV的长度就是了) //public void DesEncrypt(string m_InFilePath,string m_OutFilePath,string strEncrKey) //解密数据文件,注意strEncrKey的长度为8位(如果要增加或者减少key长度,调整IV的长度就是了) //public void DesDecrypt(string m_InFilePath,string m_OutFilePath,string sDecrKey) //MD5加密 //public string MD5Encrypt(string strText) using Common; namespace Commons { /// <summary> /// DES对称加解密、AES RijndaelManaged加解密、Base64加密解密、MD5加密等操作辅助类 /// </summary> public sealed class EncodeHelper { #region DES对称加密解密 public const string DEFAULT_ENCRYPT_KEY = "12345678"; /// <summary> /// 使用默认加密 /// </summary> /// <param name="strText"></param> /// <returns></returns> public static string DesEncrypt(string strText) { try { return DesEncrypt(strText, DEFAULT_ENCRYPT_KEY); } catch { return ""; } } /// <summary> /// 使用默认解密 /// </summary> /// <param name="strText"></param> /// <returns></returns> public static string DesDecrypt(string strText) { try { return DesDecrypt(strText, DEFAULT_ENCRYPT_KEY); } catch { return ""; } } /// <summary> /// Encrypt the string /// Attention:key must be 8 bits /// </summary> /// <param name="strText">string</param> /// <param name="strEncrKey">key</param> /// <returns></returns> public static string DesEncrypt(string strText, string strEncrKey) { byte[] byKey = null; byte[] IV = { 0x12, 0x34, 0x56, 0x78, 0x90, 0xAB, 0xCD, 0xEF }; byKey = Encoding.UTF8.GetBytes(strEncrKey.Substring(0, 8)); DESCryptoServiceProvider des = new DESCryptoServiceProvider(); byte[] inputByteArray = Encoding.UTF8.GetBytes(strText); MemoryStream ms = new MemoryStream(); CryptoStream cs = new CryptoStream(ms, des.CreateEncryptor(byKey, IV), CryptoStreamMode.Write); cs.Write(inputByteArray, 0, inputByteArray.Length); cs.FlushFinalBlock(); return Convert.ToBase64String(ms.ToArray()); } /// <summary> /// Decrypt string /// Attention:key must be 8 bits /// </summary> /// <param name="strText">Decrypt string</param> /// <param name="sDecrKey">key</param> /// <returns>output string</returns> public static string DesDecrypt(string strText, string sDecrKey) { byte[] byKey = null; byte[] IV = { 0x12, 0x34, 0x56, 0x78, 0x90, 0xAB, 0xCD, 0xEF }; byte[] inputByteArray = new Byte[strText.Length]; byKey = Encoding.UTF8.GetBytes(sDecrKey.Substring(0, 8)); DESCryptoServiceProvider des = new DESCryptoServiceProvider(); inputByteArray = Convert.FromBase64String(strText); MemoryStream ms = new MemoryStream(); CryptoStream cs = new CryptoStream(ms, des.CreateDecryptor(byKey, IV), CryptoStreamMode.Write); cs.Write(inputByteArray, 0, inputByteArray.Length); cs.FlushFinalBlock(); Encoding encoding = new UTF8Encoding(); return encoding.GetString(ms.ToArray()); } /// <summary> /// Encrypt files /// Attention:key must be 8 bits /// </summary> /// <param name="m_InFilePath">Encrypt file path</param> /// <param name="m_OutFilePath">output file</param> /// <param name="strEncrKey">key</param> public static void DesEncrypt(string m_InFilePath, string m_OutFilePath, string strEncrKey) { byte[] byKey = null; byte[] IV = { 0x12, 0x34, 0x56, 0x78, 0x90, 0xAB, 0xCD, 0xEF }; byKey = Encoding.UTF8.GetBytes(strEncrKey.Substring(0, 8)); FileStream fin = new FileStream(m_InFilePath, FileMode.Open, FileAccess.Read); FileStream fout = new FileStream(m_OutFilePath, FileMode.OpenOrCreate, FileAccess.Write); fout.SetLength(0); //Create variables to help with read and write. byte[] bin = new byte[100]; //This is intermediate storage for the encryption. long rdlen = 0; //This is the total number of bytes written. long totlen = fin.Length; //This is the total length of the input file. int len; //This is the number of bytes to be written at a time. DES des = new DESCryptoServiceProvider(); CryptoStream encStream = new CryptoStream(fout, des.CreateEncryptor(byKey, IV), CryptoStreamMode.Write); //Read from the input file, then encrypt and write to the output file. while (rdlen < totlen) { len = fin.Read(bin, 0, 100); encStream.Write(bin, 0, len); rdlen = rdlen + len; } encStream.Close(); fout.Close(); fin.Close(); } /// <summary> /// Decrypt files /// Attention:key must be 8 bits /// </summary> /// <param name="m_InFilePath">Decrypt filepath</param> /// <param name="m_OutFilePath">output filepath</param> /// <param name="sDecrKey">key</param> public static void DesDecrypt(string m_InFilePath, string m_OutFilePath, string sDecrKey) { byte[] byKey = null; byte[] IV = { 0x12, 0x34, 0x56, 0x78, 0x90, 0xAB, 0xCD, 0xEF }; byKey = Encoding.UTF8.GetBytes(sDecrKey.Substring(0, 8)); FileStream fin = new FileStream(m_InFilePath, FileMode.Open, FileAccess.Read); FileStream fout = new FileStream(m_OutFilePath, FileMode.OpenOrCreate, FileAccess.Write); fout.SetLength(0); //Create variables to help with read and write. byte[] bin = new byte[100]; //This is intermediate storage for the encryption. long rdlen = 0; //This is the total number of bytes written. long totlen = fin.Length; //This is the total length of the input file. int len; //This is the number of bytes to be written at a time. DES des = new DESCryptoServiceProvider(); CryptoStream encStream = new CryptoStream(fout, des.CreateDecryptor(byKey, IV), CryptoStreamMode.Write); //Read from the input file, then encrypt and write to the output file. while (rdlen < totlen) { len = fin.Read(bin, 0, 100); encStream.Write(bin, 0, len); rdlen = rdlen + len; } encStream.Close(); fout.Close(); fin.Close(); } #endregion #region 对称加密算法AES RijndaelManaged加密解密 private static readonly string Default_AES_Key = "@#kim123"; private static byte[] Keys = { 0x41, 0x72, 0x65, 0x79, 0x6F, 0x75, 0x6D, 0x79, 0x53,0x6E, 0x6F, 0x77, 0x6D, 0x61, 0x6E, 0x3F }; /// <summary> /// 对称加密算法AES RijndaelManaged加密(RijndaelManaged(AES)算法是块式加密算法) /// </summary> /// <param name="encryptString">待加密字符串</param> /// <returns>加密结果字符串</returns> public static string AES_Encrypt(string encryptString) { return AES_Encrypt(encryptString, Default_AES_Key); } /// <summary> /// 对称加密算法AES RijndaelManaged加密(RijndaelManaged(AES)算法是块式加密算法) /// </summary> /// <param name="encryptString">待加密字符串</param> /// <param name="encryptKey">加密密钥,须半角字符</param> /// <returns>加密结果字符串</returns> public static string AES_Encrypt(string encryptString, string encryptKey) { encryptKey = GetSubString(encryptKey, 32, ""); encryptKey = encryptKey.PadRight(32, ' '); RijndaelManaged rijndaelProvider = new RijndaelManaged(); rijndaelProvider.Key = Encoding.UTF8.GetBytes(encryptKey.Substring(0, 32)); rijndaelProvider.IV = Keys; ICryptoTransform rijndaelEncrypt = rijndaelProvider.CreateEncryptor(); byte[] inputData = Encoding.UTF8.GetBytes(encryptString); byte[] encryptedData = rijndaelEncrypt.TransformFinalBlock(inputData, 0, inputData.Length); return Convert.ToBase64String(encryptedData); } /// <summary> /// 对称加密算法AES RijndaelManaged解密字符串 /// </summary> /// <param name="decryptString">待解密的字符串</param> /// <returns>解密成功返回解密后的字符串,失败返源串</returns> public static string AES_Decrypt(string decryptString) { return AES_Decrypt(decryptString, Default_AES_Key); } /// <summary> /// 对称加密算法AES RijndaelManaged解密字符串 /// </summary> /// <param name="decryptString">待解密的字符串</param> /// <param name="decryptKey">解密密钥,和加密密钥相同</param> /// <returns>解密成功返回解密后的字符串,失败返回空</returns> public static string AES_Decrypt(string decryptString, string decryptKey) { try { decryptKey = GetSubString(decryptKey, 32, ""); decryptKey = decryptKey.PadRight(32, ' '); RijndaelManaged rijndaelProvider = new RijndaelManaged(); rijndaelProvider.Key = Encoding.UTF8.GetBytes(decryptKey); rijndaelProvider.IV = Keys; ICryptoTransform rijndaelDecrypt = rijndaelProvider.CreateDecryptor(); byte[] inputData = Convert.FromBase64String(decryptString); byte[] decryptedData = rijndaelDecrypt.TransformFinalBlock(inputData, 0, inputData.Length); return Encoding.UTF8.GetString(decryptedData); } catch { return string.Empty; } } /// <summary> /// 按字节长度(按字节,一个汉字为2个字节)取得某字符串的一部分 /// </summary> /// <param name="sourceString">源字符串</param> /// <param name="length">所取字符串字节长度</param> /// <param name="tailString">附加字符串(当字符串不够长时,尾部所添加的字符串,一般为"...")</param> /// <returns>某字符串的一部分</returns> private static string GetSubString(string sourceString, int length, string tailString) { return GetSubString(sourceString, 0, length, tailString); } /// <summary> /// 按字节长度(按字节,一个汉字为2个字节)取得某字符串的一部分 /// </summary> /// <param name="sourceString">源字符串</param> /// <param name="startIndex">索引位置,以0开始</param> /// <param name="length">所取字符串字节长度</param> /// <param name="tailString">附加字符串(当字符串不够长时,尾部所添加的字符串,一般为"...")</param> /// <returns>某字符串的一部分</returns> private static string GetSubString(string sourceString, int startIndex, int length, string tailString) { string myResult = sourceString; //当是日文或韩文时(注:中文的范围:\u4e00 - \u9fa5, 日文在\u0800 - \u4e00, 韩文为\xAC00-\xD7A3) if (System.Text.RegularExpressions.Regex.IsMatch(sourceString, "[\u0800-\u4e00]+") || System.Text.RegularExpressions.Regex.IsMatch(sourceString, "[\xAC00-\xD7A3]+")) { //当截取的起始位置超出字段串长度时 if (startIndex >= sourceString.Length) { return string.Empty; } else { return sourceString.Substring(startIndex, ((length + startIndex) > sourceString.Length) ? (sourceString.Length - startIndex) : length); } } //中文字符,如"中国人民abcd123" if (length <= 0) { return string.Empty; } byte[] bytesSource = Encoding.Default.GetBytes(sourceString); //当字符串长度大于起始位置 if (bytesSource.Length > startIndex) { int endIndex = bytesSource.Length; //当要截取的长度在字符串的有效长度范围内 if (bytesSource.Length > (startIndex + length)) { endIndex = length + startIndex; } else { //当不在有效范围内时,只取到字符串的结尾 length = bytesSource.Length - startIndex; tailString = ""; } int[] anResultFlag = new int[length]; int nFlag = 0; //字节大于127为双字节字符 for (int i = startIndex; i < endIndex; i++) { if (bytesSource[i] > 127) { nFlag++; if (nFlag == 3) { nFlag = 1; } } else { nFlag = 0; } anResultFlag[i] = nFlag; } //最后一个字节为双字节字符的一半 if ((bytesSource[endIndex - 1] > 127) && (anResultFlag[length - 1] == 1)) { length = length + 1; } byte[] bsResult = new byte[length]; Array.Copy(bytesSource, startIndex, bsResult, 0, length); myResult = Encoding.Default.GetString(bsResult); myResult = myResult + tailString; return myResult; } return string.Empty; } /// <summary> /// 加密文件流 /// </summary> /// <param name="fs"></param> /// <returns></returns> public static CryptoStream AES_EncryptStrream(FileStream fs, string decryptKey) { decryptKey = GetSubString(decryptKey, 32, ""); decryptKey = decryptKey.PadRight(32, ' '); RijndaelManaged rijndaelProvider = new RijndaelManaged(); rijndaelProvider.Key = Encoding.UTF8.GetBytes(decryptKey); rijndaelProvider.IV = Keys; ICryptoTransform encrypto = rijndaelProvider.CreateEncryptor(); CryptoStream cytptostreamEncr = new CryptoStream(fs, encrypto, CryptoStreamMode.Write); return cytptostreamEncr; } /// <summary> /// 解密文件流 /// </summary> /// <param name="fs"></param> /// <returns></returns> public static CryptoStream AES_DecryptStream(FileStream fs, string decryptKey) { decryptKey = GetSubString(decryptKey, 32, ""); decryptKey = decryptKey.PadRight(32, ' '); RijndaelManaged rijndaelProvider = new RijndaelManaged(); rijndaelProvider.Key = Encoding.UTF8.GetBytes(decryptKey); rijndaelProvider.IV = Keys; ICryptoTransform Decrypto = rijndaelProvider.CreateDecryptor(); CryptoStream cytptostreamDecr = new CryptoStream(fs, Decrypto, CryptoStreamMode.Read); return cytptostreamDecr; } /// <summary> /// 对指定文件加密 /// </summary> /// <param name="InputFile"></param> /// <param name="OutputFile"></param> /// <returns></returns> public static bool AES_EncryptFile(string InputFile, string OutputFile) { try { string decryptKey = "www.iqidi.com"; FileStream fr = new FileStream(InputFile, FileMode.Open); FileStream fren = new FileStream(OutputFile, FileMode.Create); CryptoStream Enfr = AES_EncryptStrream(fren, decryptKey); byte[] bytearrayinput = new byte[fr.Length]; fr.Read(bytearrayinput, 0, bytearrayinput.Length); Enfr.Write(bytearrayinput, 0, bytearrayinput.Length); Enfr.Close(); fr.Close(); fren.Close(); } catch { //文件异常 return false; } return true; } /// <summary> /// 对指定的文件解压缩 /// </summary> /// <param name="InputFile"></param> /// <param name="OutputFile"></param> /// <returns></returns> public static bool AES_DecryptFile(string InputFile, string OutputFile) { try { string decryptKey = "www.iqidi.com"; FileStream fr = new FileStream(InputFile, FileMode.Open); FileStream frde = new FileStream(OutputFile, FileMode.Create); CryptoStream Defr = AES_DecryptStream(fr, decryptKey); byte[] bytearrayoutput = new byte[1024]; int m_count = 0; do { m_count = Defr.Read(bytearrayoutput, 0, bytearrayoutput.Length); frde.Write(bytearrayoutput, 0, m_count); if (m_count < bytearrayoutput.Length) break; } while (true); Defr.Close(); fr.Close(); frde.Close(); } catch { //文件异常 return false; } return true; } #endregion #region Base64加密解密 /// <summary> /// Base64是一種使用64基的位置計數法。它使用2的最大次方來代表僅可列印的ASCII 字元。 /// 這使它可用來作為電子郵件的傳輸編碼。在Base64中的變數使用字元A-Z、a-z和0-9 , /// 這樣共有62個字元,用來作為開始的64個數字,最後兩個用來作為數字的符號在不同的 /// 系統中而不同。 /// Base64加密 /// </summary> /// <param name="str"></param> /// <returns></returns> public static string Base64Encrypt(string str) { byte[] encbuff = System.Text.Encoding.UTF8.GetBytes(str); return Convert.ToBase64String(encbuff); } /// <summary> /// Base64解密 /// </summary> /// <param name="str"></param> /// <returns></returns> public static string Base64Decrypt(string str) { byte[] decbuff = Convert.FromBase64String(str); return System.Text.Encoding.UTF8.GetString(decbuff); } #endregion #region MD5加密 /// <summary> /// MD5 Encrypt /// </summary> /// <param name="strText">text</param> /// <returns>md5 Encrypt string</returns> public static string MD5Encrypt(string strText) { MD5 md5 = new MD5CryptoServiceProvider(); byte[] result = md5.ComputeHash(Encoding.Default.GetBytes(strText)); return Encoding.Default.GetString(result); } public static string MD5EncryptHash(String input) { MD5 md5 = new MD5CryptoServiceProvider(); //the GetBytes method returns byte array equavalent of a string byte[] res = md5.ComputeHash(Encoding.Default.GetBytes(input), 0, input.Length); char[] temp = new char[res.Length]; //copy to a char array which can be passed to a String constructor Array.Copy(res, temp, res.Length); //return the result as a string return new String(temp); } public static string MD5EncryptHashHex(String input) { MD5 md5 = new MD5CryptoServiceProvider(); //the GetBytes method returns byte array equavalent of a string byte[] res = md5.ComputeHash(Encoding.Default.GetBytes(input), 0, input.Length); String returnThis = string.Empty; for (int i = 0; i < res.Length; i++) { returnThis += Uri.HexEscape((char)res[i]); } returnThis = returnThis.Replace("%", ""); returnThis = returnThis.ToLower(); return returnThis; } /// <summary> /// MD5 三次加密算法.计算过程: (QQ使用) /// 1. 验证码转为大写 /// 2. 将密码使用这个方法进行三次加密后,与验证码进行叠加 /// 3. 然后将叠加后的内容再次MD5一下,得到最终验证码的值 /// </summary> /// <param name="s"></param> /// <returns></returns> public static string EncyptMD5_3_16(string s) { MD5 md5 = MD5CryptoServiceProvider.Create(); byte[] bytes = System.Text.Encoding.ASCII.GetBytes(s); byte[] bytes1 = md5.ComputeHash(bytes); byte[] bytes2 = md5.ComputeHash(bytes1); byte[] bytes3 = md5.ComputeHash(bytes2); StringBuilder sb = new StringBuilder(); foreach (var item in bytes3) { sb.Append(item.ToString("x").PadLeft(2, '0')); } return sb.ToString().ToUpper(); } #endregion /// <summary> /// SHA256函数 /// </summary> /// <param name="str">原始字符串</param> /// <returns>SHA256结果(返回长度为44字节的字符串)</returns> public static string SHA256(string str) { byte[] SHA256Data = Encoding.UTF8.GetBytes(str); SHA256Managed Sha256 = new SHA256Managed(); byte[] Result = Sha256.ComputeHash(SHA256Data); return Convert.ToBase64String(Result); //返回长度为44字节的字符串 } /// <summary> /// 加密字符串 /// </summary> /// <param name="input"></param> /// <returns></returns> public static string EncryptString(string input) { return MD5Util.AddMD5Profix(Base64Util.Encrypt(MD5Util.AddMD5Profix(input))); //return Base64.Encrypt(MD5.AddMD5Profix(Base64.Encrypt(input))); } /// <summary> /// 解密加过密的字符串 /// </summary> /// <param name="input"></param> /// <param name="throwException">解密失败是否抛异常</param> /// <returns></returns> public static string DecryptString(string input, bool throwException) { string res = ""; try { res = input;// Base64.Decrypt(input); if (MD5Util.ValidateValue(res)) { return MD5Util.RemoveMD5Profix(Base64Util.Decrypt(MD5Util.RemoveMD5Profix(res))); } else { throw new Exception("字符串无法转换成功!"); } } catch { if (throwException) { throw; } else { return ""; } } } } }
using System; using System.Collections.Generic; using System.Text; namespace Common { /// <summary> /// 基于Base64的加密编码, /// 可以设置不同的密码表来获取不同的编码合解码 /// </summary> public class Base64Util { public Base64Util() { this.InitDict(); } protected static Base64Util s_b64 = new Base64Util(); #region Base64加密解密 /// <summary> /// Base64是一種使用64基的位置計數法。它使用2的最大次方來代表僅可列印的ASCII 字元。 /// 這使它可用來作為電子郵件的傳輸編碼。在Base64中的變數使用字元A-Z、a-z和0-9 , /// 這樣共有62個字元,用來作為開始的64個數字,最後兩個用來作為數字的符號在不同的 /// 系統中而不同。 /// Base64加密 /// </summary> /// <param name="str"></param> /// <returns></returns> public static string Base64Encrypt(string str) { byte[] encbuff = System.Text.Encoding.UTF8.GetBytes(str); return Convert.ToBase64String(encbuff); } /// <summary> /// Base64解密 /// </summary> /// <param name="str"></param> /// <returns></returns> public static string Base64Decrypt(string str) { byte[] decbuff = Convert.FromBase64String(str); return System.Text.Encoding.UTF8.GetString(decbuff); } #endregion /// <summary> /// 使用默认的密码表加密字符串 /// </summary> /// <param name="input"></param> /// <returns></returns> public static string Encrypt(string input) { return s_b64.Encode(input); } /// <summary> /// 使用默认的密码表解密字符串 /// </summary> /// <param name="input"></param> /// <returns></returns> public static string Decrypt(string input) { return s_b64.Decode(input); } /// <summary> /// 获取具有标准的Base64密码表的加密类 /// </summary> /// <returns></returns> public static Base64Util GetStandardBase64() { Base64Util b64 = new Base64Util(); b64.Pad = "="; b64.CodeTable = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; return b64; } protected string m_codeTable = @"ABCDEFGHIJKLMNOPQRSTUVWXYZbacdefghijklmnopqrstu_wxyz0123456789*-"; protected string m_pad = "v"; protected Dictionary<int, char> m_t1 = new Dictionary<int, char>(); protected Dictionary<char, int> m_t2 = new Dictionary<char, int>(); /// <summary> /// 密码表 /// </summary> public string CodeTable { get { return m_codeTable; } set { if (value == null) { throw new Exception("密码表不能为null"); } else if (value.Length < 64) { throw new Exception("密码表长度必须至少为64"); } else { this.ValidateRepeat(value); this.ValidateEqualPad(value, m_pad); m_codeTable = value; this.InitDict(); } } } /// <summary> /// 补码 /// </summary> public string Pad { get { return m_pad; } set { if (value == null) { throw new Exception("密码表的补码不能为null"); } else if (value.Length != 1) { throw new Exception("密码表的补码长度必须为1"); } else { this.ValidateEqualPad(m_codeTable, value); m_pad = value; this.InitDict(); } } } /// <summary> /// 返回编码后的字符串 /// </summary> /// <param name="source"></param> /// <returns></returns> public string Encode(string source) { if (source == null || source == "") { return ""; } else { StringBuilder sb = new StringBuilder(); byte[] tmp = System.Text.UTF8Encoding.UTF8.GetBytes(source); int remain = tmp.Length % 3; int patch = 3 - remain; if (remain != 0) { Array.Resize(ref tmp, tmp.Length + patch); } int cnt = (int)Math.Ceiling(tmp.Length * 1.0 / 3); for (int i = 0; i < cnt; i++) { sb.Append(this.EncodeUnit(tmp[i * 3], tmp[i * 3 + 1], tmp[i * 3 + 2])); } if (remain != 0) { sb.Remove(sb.Length - patch, patch); for (int i = 0; i < patch; i++) { sb.Append(m_pad); } } return sb.ToString(); } } protected string EncodeUnit(params byte[] unit) { int[] obj = new int[4]; obj[0] = (unit[0] & 0xfc) >> 2; obj[1] = ((unit[0] & 0x03) << 4) + ((unit[1] & 0xf0) >> 4); obj[2] = ((unit[1] & 0x0f) << 2) + ((unit[2] & 0xc0) >> 6); obj[3] = unit[2] & 0x3f; StringBuilder sb = new StringBuilder(); for (int i = 0; i < obj.Length; i++) { sb.Append(this.GetEC((int)obj[i])); } return sb.ToString(); } protected char GetEC(int code) { return m_t1[code];//m_codeTable[code]; } /// <summary> /// 获得解码字符串 /// </summary> /// <param name="source"></param> /// <returns></returns> public string Decode(string source) { if (source == null || source == "") { return ""; } else { List<byte> list = new List<byte>(); char[] tmp = source.ToCharArray(); int remain = tmp.Length % 4; if (remain != 0) { Array.Resize(ref tmp, tmp.Length - remain); } int patch = source.IndexOf(m_pad); if (patch != -1) { patch = source.Length - patch; } int cnt = tmp.Length / 4; for (int i = 0; i < cnt; i++) { this.DecodeUnit(list, tmp[i * 4], tmp[i * 4 + 1], tmp[i * 4 + 2], tmp[i * 4 + 3]); } for (int i = 0; i < patch; i++) { list.RemoveAt(list.Count - 1); } return System.Text.Encoding.UTF8.GetString(list.ToArray()); } } protected void DecodeUnit(List<byte> byteArr, params char[] chArray) { int[] res = new int[3]; byte[] unit = new byte[chArray.Length]; for (int i = 0; i < chArray.Length; i++) { unit[i] = this.FindChar(chArray[i]); } res[0] = (unit[0] << 2) + ((unit[1] & 0x30) >> 4); res[1] = ((unit[1] & 0xf) << 4) + ((unit[2] & 0x3c) >> 2); res[2] = ((unit[2] & 0x3) << 6) + unit[3]; for (int i = 0; i < res.Length; i++) { byteArr.Add((byte)res[i]); } } protected byte FindChar(char ch) { int pos = m_t2[ch];//m_codeTable.IndexOf(ch); return (byte)pos; } /// <summary> /// 初始化双向哈西字典 /// </summary> protected void InitDict() { m_t1.Clear(); m_t2.Clear(); m_t2.Add(m_pad[0], -1); for (int i = 0; i < m_codeTable.Length; i++) { m_t1.Add(i, m_codeTable[i]); m_t2.Add(m_codeTable[i], i); } } /// <summary> /// 检查字符串中的字符是否有重复 /// </summary> /// <param name="input"></param> /// <returns></returns> protected void ValidateRepeat(string input) { for (int i = 0; i < input.Length; i++) { if (input.LastIndexOf(input[i]) > i) { throw new Exception("密码表中含有重复字符:" + input[i]); } } } /// <summary> /// 检查字符串是否包含补码字符 /// </summary> /// <param name="input"></param> /// <param name="pad"></param> protected void ValidateEqualPad(string input, string pad) { if (input.IndexOf(pad) > -1) { throw new Exception("密码表中包含了补码字符:" + pad); } } protected void Test() { //m_codeTable = @"STUVWXYZbacdefghivklABCDEFGHIJKLMNOPQRmnopqrstu!wxyz0123456789+/"; //m_pad = "j"; this.InitDict(); string test = "abc ABC 你好!◎#¥%……!@#$%^"; string encode = this.Encode("false"); string decode = this.Decode(encode); Console.WriteLine(encode); Console.WriteLine(test == decode); } } }
using System; using System.Security.Cryptography; using System.Text; namespace Maticsoft.Common.DEncrypt { /// <summary> /// Encrypt 的摘要说明。 /// LiTianPing /// </summary> public class DEncrypt { /// <summary> /// 构造方法 /// </summary> public DEncrypt() { } #region 使用 缺省密钥字符串 加密/解密string /// <summary> /// 使用缺省密钥字符串加密string /// </summary> /// <param name="original">明文</param> /// <returns>密文</returns> public static string Encrypt(string original) { return Encrypt(original,"MATICSOFT"); } /// <summary> /// 使用缺省密钥字符串解密string /// </summary> /// <param name="original">密文</param> /// <returns>明文</returns> public static string Decrypt(string original) { return Decrypt(original,"MATICSOFT",System.Text.Encoding.Default); } #endregion #region 使用 给定密钥字符串 加密/解密string /// <summary> /// 使用给定密钥字符串加密string /// </summary> /// <param name="original">原始文字</param> /// <param name="key">密钥</param> /// <param name="encoding">字符编码方案</param> /// <returns>密文</returns> public static string Encrypt(string original, string key) { byte[] buff = System.Text.Encoding.Default.GetBytes(original); byte[] kb = System.Text.Encoding.Default.GetBytes(key); return Convert.ToBase64String(Encrypt(buff,kb)); } /// <summary> /// 使用给定密钥字符串解密string /// </summary> /// <param name="original">密文</param> /// <param name="key">密钥</param> /// <returns>明文</returns> public static string Decrypt(string original, string key) { return Decrypt(original,key,System.Text.Encoding.Default); } /// <summary> /// 使用给定密钥字符串解密string,返回指定编码方式明文 /// </summary> /// <param name="encrypted">密文</param> /// <param name="key">密钥</param> /// <param name="encoding">字符编码方案</param> /// <returns>明文</returns> public static string Decrypt(string encrypted, string key,Encoding encoding) { byte[] buff = Convert.FromBase64String(encrypted); byte[] kb = System.Text.Encoding.Default.GetBytes(key); return encoding.GetString(Decrypt(buff,kb)); } #endregion #region 使用 缺省密钥字符串 加密/解密/byte[] /// <summary> /// 使用缺省密钥字符串解密byte[] /// </summary> /// <param name="encrypted">密文</param> /// <param name="key">密钥</param> /// <returns>明文</returns> public static byte[] Decrypt(byte[] encrypted) { byte[] key = System.Text.Encoding.Default.GetBytes("MATICSOFT"); return Decrypt(encrypted,key); } /// <summary> /// 使用缺省密钥字符串加密 /// </summary> /// <param name="original">原始数据</param> /// <param name="key">密钥</param> /// <returns>密文</returns> public static byte[] Encrypt(byte[] original) { byte[] key = System.Text.Encoding.Default.GetBytes("MATICSOFT"); return Encrypt(original,key); } #endregion #region 使用 给定密钥 加密/解密/byte[] /// <summary> /// 生成MD5摘要 /// </summary> /// <param name="original">数据源</param> /// <returns>摘要</returns> public static byte[] MakeMD5(byte[] original) { MD5CryptoServiceProvider hashmd5 = new MD5CryptoServiceProvider(); byte[] keyhash = hashmd5.ComputeHash(original); hashmd5 = null; return keyhash; } /// <summary> /// 使用给定密钥加密 /// </summary> /// <param name="original">明文</param> /// <param name="key">密钥</param> /// <returns>密文</returns> public static byte[] Encrypt(byte[] original, byte[] key) { TripleDESCryptoServiceProvider des = new TripleDESCryptoServiceProvider(); des.Key = MakeMD5(key); des.Mode = CipherMode.ECB; return des.CreateEncryptor().TransformFinalBlock(original, 0, original.Length); } /// <summary> /// 使用给定密钥解密数据 /// </summary> /// <param name="encrypted">密文</param> /// <param name="key">密钥</param> /// <returns>明文</returns> public static byte[] Decrypt(byte[] encrypted, byte[] key) { TripleDESCryptoServiceProvider des = new TripleDESCryptoServiceProvider(); des.Key = MakeMD5(key); des.Mode = CipherMode.ECB; return des.CreateDecryptor().TransformFinalBlock(encrypted, 0, encrypted.Length); } #endregion } }
using System; using System.Security.Cryptography; using System.Text; namespace Maticsoft.Common.DEncrypt { /// <summary> /// DES加密/解密类。 /// LiTianPing /// </summary> public class DESEncrypt { public DESEncrypt() { } #region ========加密======== /// <summary> /// 加密 /// </summary> /// <param name="Text"></param> /// <returns></returns> public static string Encrypt(string Text) { return Encrypt(Text,"MATICSOFT"); } /// <summary> /// 加密数据 /// </summary> /// <param name="Text"></param> /// <param name="sKey"></param> /// <returns></returns> public static string Encrypt(string Text,string sKey) { DESCryptoServiceProvider des = new DESCryptoServiceProvider(); byte[] inputByteArray; inputByteArray=Encoding.Default.GetBytes(Text); des.Key = ASCIIEncoding.ASCII.GetBytes(System.Web.Security.FormsAuthentication.HashPasswordForStoringInConfigFile(sKey, "md5").Substring(0, 8)); des.IV = ASCIIEncoding.ASCII.GetBytes(System.Web.Security.FormsAuthentication.HashPasswordForStoringInConfigFile(sKey, "md5").Substring(0, 8)); System.IO.MemoryStream ms=new System.IO.MemoryStream(); CryptoStream cs=new CryptoStream(ms,des.CreateEncryptor(),CryptoStreamMode.Write); cs.Write(inputByteArray,0,inputByteArray.Length); cs.FlushFinalBlock(); StringBuilder ret=new StringBuilder(); foreach( byte b in ms.ToArray()) { ret.AppendFormat("{0:X2}",b); } return ret.ToString(); } #endregion #region ========解密======== /// <summary> /// 解密 /// </summary> /// <param name="Text"></param> /// <returns></returns> public static string Decrypt(string Text) { return Decrypt(Text,"MATICSOFT"); } /// <summary> /// 解密数据 /// </summary> /// <param name="Text"></param> /// <param name="sKey"></param> /// <returns></returns> public static string Decrypt(string Text,string sKey) { DESCryptoServiceProvider des = new DESCryptoServiceProvider(); int len; len=Text.Length/2; byte[] inputByteArray = new byte[len]; int x,i; for(x=0;x<len;x++) { i = Convert.ToInt32(Text.Substring(x * 2, 2), 16); inputByteArray[x]=(byte)i; } des.Key = ASCIIEncoding.ASCII.GetBytes(System.Web.Security.FormsAuthentication.HashPasswordForStoringInConfigFile(sKey, "md5").Substring(0, 8)); des.IV = ASCIIEncoding.ASCII.GetBytes(System.Web.Security.FormsAuthentication.HashPasswordForStoringInConfigFile(sKey, "md5").Substring(0, 8)); System.IO.MemoryStream ms=new System.IO.MemoryStream(); CryptoStream cs=new CryptoStream(ms,des.CreateDecryptor(),CryptoStreamMode.Write); cs.Write(inputByteArray,0,inputByteArray.Length); cs.FlushFinalBlock(); return Encoding.Default.GetString(ms.ToArray()); } #endregion } }
using System; using System.Security.Cryptography; using System.Text; using System.IO; namespace Common { public class Encrypt { public Encrypt() { } //密钥 private static byte[] arrDESKey = new byte[] {42, 16, 93, 156, 78, 4, 218, 32}; private static byte[] arrDESIV = new byte[] {55, 103, 246, 79, 36, 99, 167, 3}; /// <summary> /// 加密。 /// </summary> /// <param name="m_Need_Encode_String"></param> /// <returns></returns> public static string Encode(string m_Need_Encode_String) { if (m_Need_Encode_String == null) { throw new Exception("Error: \n源字符串为空!!"); } DESCryptoServiceProvider objDES = new DESCryptoServiceProvider(); MemoryStream objMemoryStream = new MemoryStream(); CryptoStream objCryptoStream = new CryptoStream(objMemoryStream, objDES.CreateEncryptor(arrDESKey, arrDESIV), CryptoStreamMode.Write); StreamWriter objStreamWriter = new StreamWriter(objCryptoStream); objStreamWriter.Write(m_Need_Encode_String); objStreamWriter.Flush(); objCryptoStream.FlushFinalBlock(); objMemoryStream.Flush(); return Convert.ToBase64String(objMemoryStream.GetBuffer(), 0, (int) objMemoryStream.Length); } /// <summary> /// 解密。 /// </summary> /// <param name="m_Need_Encode_String"></param> /// <returns></returns> public static string Decode(string m_Need_Encode_String) { if (m_Need_Encode_String == null) { throw new Exception("Error: \n源字符串为空!!"); } DESCryptoServiceProvider objDES = new DESCryptoServiceProvider(); byte[] arrInput = Convert.FromBase64String(m_Need_Encode_String); MemoryStream objMemoryStream = new MemoryStream(arrInput); CryptoStream objCryptoStream = new CryptoStream(objMemoryStream, objDES.CreateDecryptor(arrDESKey, arrDESIV), CryptoStreamMode.Read); StreamReader objStreamReader = new StreamReader(objCryptoStream); return objStreamReader.ReadToEnd(); } /// <summary> /// md5 /// </summary> /// <param name="encypStr"></param> /// <returns></returns> public static string Md5(string encypStr) { string retStr; MD5CryptoServiceProvider m5 = new MD5CryptoServiceProvider(); byte[] inputBye; byte[] outputBye; inputBye = System.Text.Encoding.ASCII.GetBytes(encypStr); outputBye = m5.ComputeHash(inputBye); retStr = Convert.ToBase64String(outputBye); return (retStr); } #region TripleDES加密 /// <summary> /// TripleDES加密 /// </summary> public static string TripleDESEncrypting(string strSource) { try { byte[] bytIn = Encoding.Default.GetBytes(strSource); byte[] key = { 42, 16, 93, 156, 78, 4, 218, 32, 15, 167, 44, 80, 26, 20, 155, 112, 2, 94, 11, 204, 119, 35, 184, 197 }; //定义密钥 byte[] IV = {55, 103, 246, 79, 36, 99, 167, 3}; //定义偏移量 TripleDESCryptoServiceProvider TripleDES = new TripleDESCryptoServiceProvider(); TripleDES.IV = IV; TripleDES.Key = key; ICryptoTransform encrypto = TripleDES.CreateEncryptor(); System.IO.MemoryStream ms = new System.IO.MemoryStream(); CryptoStream cs = new CryptoStream(ms, encrypto, CryptoStreamMode.Write); cs.Write(bytIn, 0, bytIn.Length); cs.FlushFinalBlock(); byte[] bytOut = ms.ToArray(); return System.Convert.ToBase64String(bytOut); } catch (Exception ex) { throw new Exception("加密时候出现错误!错误提示:\n" + ex.Message); } } #endregion #region TripleDES解密 /// <summary> /// TripleDES解密 /// </summary> public static string TripleDESDecrypting(string Source) { try { byte[] bytIn = System.Convert.FromBase64String(Source); byte[] key = { 42, 16, 93, 156, 78, 4, 218, 32, 15, 167, 44, 80, 26, 20, 155, 112, 2, 94, 11, 204, 119, 35, 184, 197 }; //定义密钥 byte[] IV = {55, 103, 246, 79, 36, 99, 167, 3}; //定义偏移量 TripleDESCryptoServiceProvider TripleDES = new TripleDESCryptoServiceProvider(); TripleDES.IV = IV; TripleDES.Key = key; ICryptoTransform encrypto = TripleDES.CreateDecryptor(); System.IO.MemoryStream ms = new System.IO.MemoryStream(bytIn, 0, bytIn.Length); CryptoStream cs = new CryptoStream(ms, encrypto, CryptoStreamMode.Read); StreamReader strd = new StreamReader(cs, Encoding.Default); return strd.ReadToEnd(); } catch (Exception ex) { throw new Exception("解密时候出现错误!错误提示:\n" + ex.Message); } } #endregion } }
using System; using System.Text; using System.Security.Cryptography; namespace Maticsoft.Common.DEncrypt { /// <summary> /// 得到随机安全码(哈希加密)。 /// </summary> public class HashEncode { public HashEncode() { // // TODO: 在此处添加构造函数逻辑 // } /// <summary> /// 得到随机哈希加密字符串 /// </summary> /// <returns></returns> public static string GetSecurity() { string Security = HashEncoding(GetRandomValue()); return Security; } /// <summary> /// 得到一个随机数值 /// </summary> /// <returns></returns> public static string GetRandomValue() { Random Seed = new Random(); string RandomVaule = Seed.Next(1, int.MaxValue).ToString(); return RandomVaule; } /// <summary> /// 哈希加密一个字符串 /// </summary> /// <param name="Security"></param> /// <returns></returns> public static string HashEncoding(string Security) { byte[] Value; UnicodeEncoding Code = new UnicodeEncoding(); byte[] Message = Code.GetBytes(Security); SHA512Managed Arithmetic = new SHA512Managed(); Value = Arithmetic.ComputeHash(Message); Security = ""; foreach(byte o in Value) { Security += (int) o + "O"; } return Security; } } }
using System; using System.IO; using System.Collections.Generic; using System.Text; namespace Commons { /// <summary> /// MD5各种长度加密字符、验证MD5等操作辅助类 /// </summary> public class MD5Util { public MD5Util() { } /// <summary> /// 获得32位的MD5加密 /// </summary> /// <param name="input"></param> /// <returns></returns> public static string GetMD5_32(string input) { System.Security.Cryptography.MD5 md5 = System.Security.Cryptography.MD5.Create(); byte[] data = md5.ComputeHash(System.Text.Encoding.Default.GetBytes(input)); StringBuilder sb = new StringBuilder(); for (int i = 0; i < data.Length; i++) { sb.Append(data[i].ToString("x2")); } return sb.ToString(); } /// <summary> /// 获得16位的MD5加密 /// </summary> /// <param name="input"></param> /// <returns></returns> public static string GetMD5_16(string input) { return GetMD5_32(input).Substring(8, 16); } /// <summary> /// 获得8位的MD5加密 /// </summary> /// <param name="input"></param> /// <returns></returns> public static string GetMD5_8(string input) { return GetMD5_32(input).Substring(8, 8); } /// <summary> /// 获得4位的MD5加密 /// </summary> /// <param name="input"></param> /// <returns></returns> public static string GetMD5_4(string input) { return GetMD5_32(input).Substring(8, 4); } /// <summary> /// 添加MD5的前缀,便于检查有无篡改 /// </summary> /// <param name="input"></param> /// <returns></returns> public static string AddMD5Profix(string input) { return GetMD5_4(input) + input; } /// <summary> /// 移除MD5的前缀 /// </summary> /// <param name="input"></param> /// <returns></returns> public static string RemoveMD5Profix(string input) { return input.Substring(4); } /// <summary> /// 验证MD5前缀处理的字符串有无被篡改 /// </summary> /// <param name="input"></param> /// <returns></returns> public static bool ValidateValue(string input) { bool res = false; if (input.Length >= 4) { string tmp = input.Substring(4); if (input.Substring(0, 4) == GetMD5_4(tmp)) { res = true; } } return res; } #region MD5签名验证 /// <summary> /// 对给定文件路径的文件加上标签 /// </summary> /// <param name="path">要加密的文件的路径</param> /// <returns>标签的值</returns> public static bool AddMD5(string path) { bool IsNeed = true; if (CheckMD5(path)) //已进行MD5处理 IsNeed = false; try { FileStream fsread = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.Read); byte[] md5File = new byte[fsread.Length]; fsread.Read(md5File, 0, (int)fsread.Length); // 将文件流读取到Buffer中 fsread.Close(); if (IsNeed) { string result = MD5Buffer(md5File, 0, md5File.Length); // 对Buffer中的字节内容算MD5 byte[] md5 = System.Text.Encoding.ASCII.GetBytes(result); // 将字符串转换成字节数组以便写人到文件中 FileStream fsWrite = new FileStream(path, FileMode.Open, FileAccess.ReadWrite); fsWrite.Write(md5File, 0, md5File.Length); // 将文件,MD5值 重新写入到文件中。 fsWrite.Write(md5, 0, md5.Length); fsWrite.Close(); } else { FileStream fsWrite = new FileStream(path, FileMode.Open, FileAccess.ReadWrite); fsWrite.Write(md5File, 0, md5File.Length); fsWrite.Close(); } } catch { return false; } return true; } /// <summary> /// 对给定路径的文件进行验证 /// </summary> /// <param name="path"></param> /// <returns>是否加了标签或是否标签值与内容值一致</returns> public static bool CheckMD5(string path) { try { FileStream get_file = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.Read); byte[] md5File = new byte[get_file.Length]; // 读入文件 get_file.Read(md5File, 0, (int)get_file.Length); get_file.Close(); string result = MD5Buffer(md5File, 0, md5File.Length - 32); // 对文件除最后32位以外的字节计算MD5,这个32是因为标签位为32位。 string md5 = System.Text.Encoding.ASCII.GetString(md5File, md5File.Length - 32, 32); //读取文件最后32位,其中保存的就是MD5值 return result == md5; } catch { return false; } } /// <summary> /// 计算文件的MD5值 /// </summary> /// <param name="MD5File">MD5签名文件字符数组</param> /// <param name="index">计算起始位置</param> /// <param name="count">计算终止位置</param> /// <returns>计算结果</returns> private static string MD5Buffer(byte[] MD5File, int index, int count) { System.Security.Cryptography.MD5CryptoServiceProvider get_md5 = new System.Security.Cryptography.MD5CryptoServiceProvider(); byte[] hash_byte = get_md5.ComputeHash(MD5File, index, count); string result = System.BitConverter.ToString(hash_byte); result = result.Replace("-", ""); return result; } #endregion private void Test() { string o = "i love u"; o = AddMD5Profix(o); //o += " "; Console.WriteLine(o); Console.WriteLine(ValidateValue(o)); o = RemoveMD5Profix(o); Console.WriteLine(o); } } }
using System; using System.Text; using System.Security.Cryptography; using System.IO; using System.Text.RegularExpressions; using System.Collections; using Core.Common; namespace Common { /// <summary> /// MySecurity(安全类) 的摘要说明。 /// </summary> public class MySecurity { /// <summary> /// 初始化安全类 /// </summary> public MySecurity() { ///默认密码 key = "0123456789"; } private string key; //默认密钥 private byte[] sKey; private byte[] sIV; #region 加密字符串 /// <summary> /// 加密字符串 /// </summary> /// <param name="inputStr">输入字符串</param> /// <param name="keyStr">密码,可以为“”</param> /// <returns>输出加密后字符串</returns> public static string SEncryptString(string inputStr, string keyStr) { MySecurity ws = new MySecurity(); return ws.EncryptString(inputStr, keyStr); } /// <summary> /// 加密字符串 /// </summary> /// <param name="inputStr">输入字符串</param> /// <param name="keyStr">密码,可以为“”</param> /// <returns>输出加密后字符串</returns> public string EncryptString(string inputStr, string keyStr) { DESCryptoServiceProvider des = new DESCryptoServiceProvider(); if (keyStr == "") keyStr = key; byte[] inputByteArray = Encoding.Default.GetBytes(inputStr); byte[] keyByteArray = Encoding.Default.GetBytes(keyStr); SHA1 ha = new SHA1Managed(); byte[] hb = ha.ComputeHash(keyByteArray); sKey = new byte[8]; sIV = new byte[8]; for (int i = 0; i < 8; i++) sKey[i] = hb[i]; for (int i = 8; i < 16; i++) sIV[i - 8] = hb[i]; des.Key = sKey; des.IV = sIV; MemoryStream ms = new MemoryStream(); CryptoStream cs = new CryptoStream(ms, des.CreateEncryptor(), CryptoStreamMode.Write); cs.Write(inputByteArray, 0, inputByteArray.Length); cs.FlushFinalBlock(); StringBuilder ret = new StringBuilder(); foreach (byte b in ms.ToArray()) { ret.AppendFormat("{0:X2}", b); } cs.Close(); ms.Close(); return ret.ToString(); } #endregion #region 加密字符串 密钥为系统默认 0123456789 /// <summary> /// 加密字符串 密钥为系统默认 /// </summary> /// <param name="inputStr">输入字符串</param> /// <returns>输出加密后字符串</returns> static public string SEncryptString(string inputStr) { MySecurity ws = new MySecurity(); return ws.EncryptString(inputStr, ""); } #endregion #region 加密文件 /// <summary> /// 加密文件 /// </summary> /// <param name="filePath">输入文件路径</param> /// <param name="savePath">加密后输出文件路径</param> /// <param name="keyStr">密码,可以为“”</param> /// <returns></returns> public bool EncryptFile(string filePath, string savePath, string keyStr) { DESCryptoServiceProvider des = new DESCryptoServiceProvider(); if (keyStr == "") keyStr = key; FileStream fs = File.OpenRead(filePath); byte[] inputByteArray = new byte[fs.Length]; fs.Read(inputByteArray, 0, (int)fs.Length); fs.Close(); byte[] keyByteArray = Encoding.Default.GetBytes(keyStr); SHA1 ha = new SHA1Managed(); byte[] hb = ha.ComputeHash(keyByteArray); sKey = new byte[8]; sIV = new byte[8]; for (int i = 0; i < 8; i++) sKey[i] = hb[i]; for (int i = 8; i < 16; i++) sIV[i - 8] = hb[i]; des.Key = sKey; des.IV = sIV; MemoryStream ms = new MemoryStream(); CryptoStream cs = new CryptoStream(ms, des.CreateEncryptor(), CryptoStreamMode.Write); cs.Write(inputByteArray, 0, inputByteArray.Length); cs.FlushFinalBlock(); fs = File.OpenWrite(savePath); foreach (byte b in ms.ToArray()) { fs.WriteByte(b); } fs.Close(); cs.Close(); ms.Close(); return true; } #endregion #region 解密字符串 /// <summary> /// 解密字符串 /// </summary> /// <param name="inputStr">要解密的字符串</param> /// <param name="keyStr">密钥</param> /// <returns>解密后的结果</returns> static public string SDecryptString(string inputStr, string keyStr) { MySecurity ws = new MySecurity(); return ws.DecryptString(inputStr, keyStr); } /// <summary> /// 解密字符串 密钥为系统默认 /// </summary> /// <param name="inputStr">要解密的字符串</param> /// <returns>解密后的结果</returns> static public string SDecryptString(string inputStr) { MySecurity ws = new MySecurity(); return ws.DecryptString(inputStr, ""); } /// <summary> /// 解密字符串 /// </summary> /// <param name="inputStr">要解密的字符串</param> /// <param name="keyStr">密钥</param> /// <returns>解密后的结果</returns> public string DecryptString(string inputStr, string keyStr) { DESCryptoServiceProvider des = new DESCryptoServiceProvider(); if (keyStr == "") keyStr = key; byte[] inputByteArray = new byte[inputStr.Length / 2]; for (int x = 0; x < inputStr.Length / 2; x++) { int i = (Convert.ToInt32(inputStr.Substring(x * 2, 2), 16)); inputByteArray[x] = (byte)i; } byte[] keyByteArray = Encoding.Default.GetBytes(keyStr); SHA1 ha = new SHA1Managed(); byte[] hb = ha.ComputeHash(keyByteArray); sKey = new byte[8]; sIV = new byte[8]; for (int i = 0; i < 8; i++) sKey[i] = hb[i]; for (int i = 8; i < 16; i++) sIV[i - 8] = hb[i]; des.Key = sKey; des.IV = sIV; MemoryStream ms = new MemoryStream(); CryptoStream cs = new CryptoStream(ms, des.CreateDecryptor(), CryptoStreamMode.Write); cs.Write(inputByteArray, 0, inputByteArray.Length); cs.FlushFinalBlock(); StringBuilder ret = new StringBuilder(); return System.Text.Encoding.Default.GetString(ms.ToArray()); } #endregion #region 解密文件 /// <summary> /// 解密文件 /// </summary> /// <param name="filePath">输入文件路径</param> /// <param name="savePath">解密后输出文件路径</param> /// <param name="keyStr">密码,可以为“”</param> /// <returns></returns> public bool DecryptFile(string filePath, string savePath, string keyStr) { DESCryptoServiceProvider des = new DESCryptoServiceProvider(); if (keyStr == "") keyStr = key; FileStream fs = File.OpenRead(filePath); byte[] inputByteArray = new byte[fs.Length]; fs.Read(inputByteArray, 0, (int)fs.Length); fs.Close(); byte[] keyByteArray = Encoding.Default.GetBytes(keyStr); SHA1 ha = new SHA1Managed(); byte[] hb = ha.ComputeHash(keyByteArray); sKey = new byte[8]; sIV = new byte[8]; for (int i = 0; i < 8; i++) sKey[i] = hb[i]; for (int i = 8; i < 16; i++) sIV[i - 8] = hb[i]; des.Key = sKey; des.IV = sIV; MemoryStream ms = new MemoryStream(); CryptoStream cs = new CryptoStream(ms, des.CreateDecryptor(), CryptoStreamMode.Write); cs.Write(inputByteArray, 0, inputByteArray.Length); cs.FlushFinalBlock(); fs = File.OpenWrite(savePath); foreach (byte b in ms.ToArray()) { fs.WriteByte(b); } fs.Close(); cs.Close(); ms.Close(); return true; } #endregion #region Base64加密 /// <summary> /// Base64加密 /// </summary> /// <param name="text">要加密的字符串</param> /// <returns></returns> public static string EncodeBase64(string text) { //如果字符串为空,则返回 if (StringHelper.IsNullOrEmpty<string>(text)) { return ""; } try { char[] Base64Code = new char[]{'A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T', 'U','V','W','X','Y','Z','a','b','c','d','e','f','g','h','i','j','k','l','m','n', 'o','p','q','r','s','t','u','v','w','x','y','z','0','1','2','3','4','5','6','7', '8','9','+','/','='}; byte empty = (byte)0; ArrayList byteMessage = new ArrayList(Encoding.Default.GetBytes(text)); StringBuilder outmessage; int messageLen = byteMessage.Count; int page = messageLen / 3; int use = 0; if ((use = messageLen % 3) > 0) { for (int i = 0; i < 3 - use; i++) byteMessage.Add(empty); page++; } outmessage = new System.Text.StringBuilder(page * 4); for (int i = 0; i < page; i++) { byte[] instr = new byte[3]; instr[0] = (byte)byteMessage[i * 3]; instr[1] = (byte)byteMessage[i * 3 + 1]; instr[2] = (byte)byteMessage[i * 3 + 2]; int[] outstr = new int[4]; outstr[0] = instr[0] >> 2; outstr[1] = ((instr[0] & 0x03) << 4) ^ (instr[1] >> 4); if (!instr[1].Equals(empty)) outstr[2] = ((instr[1] & 0x0f) << 2) ^ (instr[2] >> 6); else outstr[2] = 64; if (!instr[2].Equals(empty)) outstr[3] = (instr[2] & 0x3f); else outstr[3] = 64; outmessage.Append(Base64Code[outstr[0]]); outmessage.Append(Base64Code[outstr[1]]); outmessage.Append(Base64Code[outstr[2]]); outmessage.Append(Base64Code[outstr[3]]); } return outmessage.ToString(); } catch (Exception ex) { throw ex; } } #endregion #region Base64解密 /// <summary> /// Base64解密 /// </summary> /// <param name="text">要解密的字符串</param> public static string DecodeBase64(string text) { //如果字符串为空,则返回 if (StringHelper.IsNullOrEmpty<string>(text)) { return ""; } //将空格替换为加号 text = text.Replace(" ", "+"); try { if ((text.Length % 4) != 0) { return "包含不正确的BASE64编码"; } if (!Regex.IsMatch(text, "^[A-Z0-9/+=]*$", RegexOptions.IgnoreCase)) { return "包含不正确的BASE64编码"; } string Base64Code = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/="; int page = text.Length / 4; ArrayList outMessage = new ArrayList(page * 3); char[] message = text.ToCharArray(); for (int i = 0; i < page; i++) { byte[] instr = new byte[4]; instr[0] = (byte)Base64Code.IndexOf(message[i * 4]); instr[1] = (byte)Base64Code.IndexOf(message[i * 4 + 1]); instr[2] = (byte)Base64Code.IndexOf(message[i * 4 + 2]); instr[3] = (byte)Base64Code.IndexOf(message[i * 4 + 3]); byte[] outstr = new byte[3]; outstr[0] = (byte)((instr[0] << 2) ^ ((instr[1] & 0x30) >> 4)); if (instr[2] != 64) { outstr[1] = (byte)((instr[1] << 4) ^ ((instr[2] & 0x3c) >> 2)); } else { outstr[2] = 0; } if (instr[3] != 64) { outstr[2] = (byte)((instr[2] << 6) ^ instr[3]); } else { outstr[2] = 0; } outMessage.Add(outstr[0]); if (outstr[1] != 0) outMessage.Add(outstr[1]); if (outstr[2] != 0) outMessage.Add(outstr[2]); } byte[] outbyte = (byte[])outMessage.ToArray(Type.GetType("System.Byte")); return Encoding.Default.GetString(outbyte); } catch (Exception ex) { throw ex; } } #endregion } }
using System; using System.Text; using System.Security.Cryptography; namespace Maticsoft.Common.DEncrypt { /// <summary> /// RSA加密解密及RSA签名和验证 /// </summary> public class RSACryption { public RSACryption() { } #region RSA 加密解密 #region RSA 的密钥产生 /// <summary> /// RSA 的密钥产生 产生私钥 和公钥 /// </summary> /// <param name="xmlKeys"></param> /// <param name="xmlPublicKey"></param> public void RSAKey(out string xmlKeys,out string xmlPublicKey) { System.Security.Cryptography.RSACryptoServiceProvider rsa=new RSACryptoServiceProvider(); xmlKeys=rsa.ToXmlString(true); xmlPublicKey = rsa.ToXmlString(false); } #endregion #region RSA的加密函数 //############################################################################## //RSA 方式加密 //说明KEY必须是XML的行式,返回的是字符串 //在有一点需要说明!!该加密方式有 长度 限制的!! //############################################################################## //RSA的加密函数 string public string RSAEncrypt(string xmlPublicKey,string m_strEncryptString ) { byte[] PlainTextBArray; byte[] CypherTextBArray; string Result; RSACryptoServiceProvider rsa=new RSACryptoServiceProvider(); rsa.FromXmlString(xmlPublicKey); PlainTextBArray = (new UnicodeEncoding()).GetBytes(m_strEncryptString); CypherTextBArray = rsa.Encrypt(PlainTextBArray, false); Result=Convert.ToBase64String(CypherTextBArray); return Result; } //RSA的加密函数 byte[] public string RSAEncrypt(string xmlPublicKey,byte[] EncryptString ) { byte[] CypherTextBArray; string Result; RSACryptoServiceProvider rsa=new RSACryptoServiceProvider(); rsa.FromXmlString(xmlPublicKey); CypherTextBArray = rsa.Encrypt(EncryptString, false); Result=Convert.ToBase64String(CypherTextBArray); return Result; } #endregion #region RSA的解密函数 //RSA的解密函数 string public string RSADecrypt(string xmlPrivateKey, string m_strDecryptString ) { byte[] PlainTextBArray; byte[] DypherTextBArray; string Result; System.Security.Cryptography.RSACryptoServiceProvider rsa=new RSACryptoServiceProvider(); rsa.FromXmlString(xmlPrivateKey); PlainTextBArray =Convert.FromBase64String(m_strDecryptString); DypherTextBArray=rsa.Decrypt(PlainTextBArray, false); Result=(new UnicodeEncoding()).GetString(DypherTextBArray); return Result; } //RSA的解密函数 byte public string RSADecrypt(string xmlPrivateKey, byte[] DecryptString ) { byte[] DypherTextBArray; string Result; System.Security.Cryptography.RSACryptoServiceProvider rsa=new RSACryptoServiceProvider(); rsa.FromXmlString(xmlPrivateKey); DypherTextBArray=rsa.Decrypt(DecryptString, false); Result=(new UnicodeEncoding()).GetString(DypherTextBArray); return Result; } #endregion #endregion #region RSA数字签名 #region 获取Hash描述表 //获取Hash描述表 public bool GetHash(string m_strSource, ref byte[] HashData) { //从字符串中取得Hash描述 byte[] Buffer; System.Security.Cryptography.HashAlgorithm MD5 = System.Security.Cryptography.HashAlgorithm.Create("MD5"); Buffer = System.Text.Encoding.GetEncoding("GB2312").GetBytes(m_strSource); HashData = MD5.ComputeHash(Buffer); return true; } //获取Hash描述表 public bool GetHash(string m_strSource, ref string strHashData) { //从字符串中取得Hash描述 byte[] Buffer; byte[] HashData; System.Security.Cryptography.HashAlgorithm MD5 = System.Security.Cryptography.HashAlgorithm.Create("MD5"); Buffer = System.Text.Encoding.GetEncoding("GB2312").GetBytes(m_strSource); HashData = MD5.ComputeHash(Buffer); strHashData = Convert.ToBase64String(HashData); return true; } //获取Hash描述表 public bool GetHash(System.IO.FileStream objFile, ref byte[] HashData) { //从文件中取得Hash描述 System.Security.Cryptography.HashAlgorithm MD5 = System.Security.Cryptography.HashAlgorithm.Create("MD5"); HashData = MD5.ComputeHash(objFile); objFile.Close(); return true; } //获取Hash描述表 public bool GetHash(System.IO.FileStream objFile, ref string strHashData) { //从文件中取得Hash描述 byte[] HashData; System.Security.Cryptography.HashAlgorithm MD5 = System.Security.Cryptography.HashAlgorithm.Create("MD5"); HashData = MD5.ComputeHash(objFile); objFile.Close(); strHashData = Convert.ToBase64String(HashData); return true; } #endregion #region RSA签名 //RSA签名 public bool SignatureFormatter(string p_strKeyPrivate, byte[] HashbyteSignature, ref byte[] EncryptedSignatureData) { System.Security.Cryptography.RSACryptoServiceProvider RSA = new System.Security.Cryptography.RSACryptoServiceProvider(); RSA.FromXmlString(p_strKeyPrivate); System.Security.Cryptography.RSAPKCS1SignatureFormatter RSAFormatter = new System.Security.Cryptography.RSAPKCS1SignatureFormatter(RSA); //设置签名的算法为MD5 RSAFormatter.SetHashAlgorithm("MD5"); //执行签名 EncryptedSignatureData = RSAFormatter.CreateSignature(HashbyteSignature); return true; } //RSA签名 public bool SignatureFormatter(string p_strKeyPrivate, byte[] HashbyteSignature, ref string m_strEncryptedSignatureData) { byte[] EncryptedSignatureData; System.Security.Cryptography.RSACryptoServiceProvider RSA = new System.Security.Cryptography.RSACryptoServiceProvider(); RSA.FromXmlString(p_strKeyPrivate); System.Security.Cryptography.RSAPKCS1SignatureFormatter RSAFormatter = new System.Security.Cryptography.RSAPKCS1SignatureFormatter(RSA); //设置签名的算法为MD5 RSAFormatter.SetHashAlgorithm("MD5"); //执行签名 EncryptedSignatureData = RSAFormatter.CreateSignature(HashbyteSignature); m_strEncryptedSignatureData = Convert.ToBase64String(EncryptedSignatureData); return true; } //RSA签名 public bool SignatureFormatter(string p_strKeyPrivate, string m_strHashbyteSignature, ref byte[] EncryptedSignatureData) { byte[] HashbyteSignature; HashbyteSignature = Convert.FromBase64String(m_strHashbyteSignature); System.Security.Cryptography.RSACryptoServiceProvider RSA = new System.Security.Cryptography.RSACryptoServiceProvider(); RSA.FromXmlString(p_strKeyPrivate); System.Security.Cryptography.RSAPKCS1SignatureFormatter RSAFormatter = new System.Security.Cryptography.RSAPKCS1SignatureFormatter(RSA); //设置签名的算法为MD5 RSAFormatter.SetHashAlgorithm("MD5"); //执行签名 EncryptedSignatureData = RSAFormatter.CreateSignature(HashbyteSignature); return true; } //RSA签名 public bool SignatureFormatter(string p_strKeyPrivate, string m_strHashbyteSignature, ref string m_strEncryptedSignatureData) { byte[] HashbyteSignature; byte[] EncryptedSignatureData; HashbyteSignature = Convert.FromBase64String(m_strHashbyteSignature); System.Security.Cryptography.RSACryptoServiceProvider RSA = new System.Security.Cryptography.RSACryptoServiceProvider(); RSA.FromXmlString(p_strKeyPrivate); System.Security.Cryptography.RSAPKCS1SignatureFormatter RSAFormatter = new System.Security.Cryptography.RSAPKCS1SignatureFormatter(RSA); //设置签名的算法为MD5 RSAFormatter.SetHashAlgorithm("MD5"); //执行签名 EncryptedSignatureData = RSAFormatter.CreateSignature(HashbyteSignature); m_strEncryptedSignatureData = Convert.ToBase64String(EncryptedSignatureData); return true; } #endregion #region RSA 签名验证 public bool SignatureDeformatter(string p_strKeyPublic, byte[] HashbyteDeformatter, byte[] DeformatterData) { System.Security.Cryptography.RSACryptoServiceProvider RSA = new System.Security.Cryptography.RSACryptoServiceProvider(); RSA.FromXmlString(p_strKeyPublic); System.Security.Cryptography.RSAPKCS1SignatureDeformatter RSADeformatter = new System.Security.Cryptography.RSAPKCS1SignatureDeformatter(RSA); //指定解密的时候HASH算法为MD5 RSADeformatter.SetHashAlgorithm("MD5"); if(RSADeformatter.VerifySignature(HashbyteDeformatter,DeformatterData)) { return true; } else { return false; } } public bool SignatureDeformatter(string p_strKeyPublic, string p_strHashbyteDeformatter, byte[] DeformatterData) { byte[] HashbyteDeformatter; HashbyteDeformatter = Convert.FromBase64String(p_strHashbyteDeformatter); System.Security.Cryptography.RSACryptoServiceProvider RSA = new System.Security.Cryptography.RSACryptoServiceProvider(); RSA.FromXmlString(p_strKeyPublic); System.Security.Cryptography.RSAPKCS1SignatureDeformatter RSADeformatter = new System.Security.Cryptography.RSAPKCS1SignatureDeformatter(RSA); //指定解密的时候HASH算法为MD5 RSADeformatter.SetHashAlgorithm("MD5"); if(RSADeformatter.VerifySignature(HashbyteDeformatter,DeformatterData)) { return true; } else { return false; } } public bool SignatureDeformatter(string p_strKeyPublic, byte[] HashbyteDeformatter, string p_strDeformatterData) { byte[] DeformatterData; System.Security.Cryptography.RSACryptoServiceProvider RSA = new System.Security.Cryptography.RSACryptoServiceProvider(); RSA.FromXmlString(p_strKeyPublic); System.Security.Cryptography.RSAPKCS1SignatureDeformatter RSADeformatter = new System.Security.Cryptography.RSAPKCS1SignatureDeformatter(RSA); //指定解密的时候HASH算法为MD5 RSADeformatter.SetHashAlgorithm("MD5"); DeformatterData =Convert.FromBase64String(p_strDeformatterData); if(RSADeformatter.VerifySignature(HashbyteDeformatter,DeformatterData)) { return true; } else { return false; } } public bool SignatureDeformatter(string p_strKeyPublic, string p_strHashbyteDeformatter, string p_strDeformatterData) { byte[] DeformatterData; byte[] HashbyteDeformatter; HashbyteDeformatter = Convert.FromBase64String(p_strHashbyteDeformatter); System.Security.Cryptography.RSACryptoServiceProvider RSA = new System.Security.Cryptography.RSACryptoServiceProvider(); RSA.FromXmlString(p_strKeyPublic); System.Security.Cryptography.RSAPKCS1SignatureDeformatter RSADeformatter = new System.Security.Cryptography.RSAPKCS1SignatureDeformatter(RSA); //指定解密的时候HASH算法为MD5 RSADeformatter.SetHashAlgorithm("MD5"); DeformatterData =Convert.FromBase64String(p_strDeformatterData); if(RSADeformatter.VerifySignature(HashbyteDeformatter,DeformatterData)) { return true; } else { return false; } } #endregion #endregion } }
using System; using System.Security.Cryptography; using System.Text; namespace Core.Common { /// <summary> /// 非对称加密验证辅助类 /// </summary> public class RSASecurityHelper { /// <summary> /// 对注册信息数据采用非对称加密的方式加密 /// </summary> /// <param name="originalString">未加密的文本,如机器码</param> /// <param name="encrytedString">加密后的文本,如注册序列号</param> /// <returns>如果验证成功返回True,否则为False</returns> public static bool Validate(string originalString, string encrytedString) { bool bPassed = false; using (RSACryptoServiceProvider rsa = new RSACryptoServiceProvider()) { try { rsa.FromXmlString(UIConstants.PublicKey); //公钥 RSAPKCS1SignatureDeformatter formatter = new RSAPKCS1SignatureDeformatter(rsa); formatter.SetHashAlgorithm("SHA1"); byte[] key = Convert.FromBase64String(encrytedString); //验证 SHA1Managed sha = new SHA1Managed(); byte[] name = sha.ComputeHash(ASCIIEncoding.ASCII.GetBytes(originalString)); if (formatter.VerifySignature(name, key)) { bPassed = true; } } catch { } } return bPassed; } } }
using System; using System.Collections.Generic; using System.Text; using System.Web; using System.Text.RegularExpressions; namespace hic.Common { public class SecurityHelper { /// <summary> /// MD5字符串加密 /// </summary> /// <param name="source">待加密字符串</param> /// <returns></returns> public static string MD5(string source) { return MD5(source, true); } /// <summary> /// MD5字符串加密 /// </summary> /// <param name="source">待加密字符串</param> /// <param name="ishalf">加密是16位还是32位,如果为true则是16位。</param> /// <returns></returns> public static string MD5(string source, bool ishalf) { string outputStr = System.Web.Security.FormsAuthentication.HashPasswordForStoringInConfigFile(source, "MD5").ToLower(); if (ishalf)//16位MD5加密(取32位加密的9~25字符) outputStr = outputStr.Substring(8, 16); return outputStr; } /// <summary> /// 对字符串进行Base64编码 /// </summary> /// <param name="source">待编码字符串</param> /// <returns></returns> public static string EncodeBase64(string source) { UnicodeEncoding code = new UnicodeEncoding(); byte[] bytes = code.GetBytes(source); return Convert.ToBase64String(bytes); } /// <summary> /// 对字符串进行Base64解码 /// </summary> /// <param name="source">待解码字符串</param> /// <returns></returns> public static string DecodeBase64(string source) { UnicodeEncoding code = new UnicodeEncoding(); byte[] bytes = Convert.FromBase64String(source); return code.GetString(bytes); } /// <summary> /// 检查当前IP是否是受限IP /// </summary> /// <param name="LimitedIP">受限的IP,格式如:192.168.1.110|212.235.*.*|232.*.*.*</param> /// <returns>返回true表示IP未受到限制</returns> public static bool CheckIPIsLimited(string limitedIP) { string currentIP = GetUserIP(); if (limitedIP == null || limitedIP.Trim() == string.Empty) return true; limitedIP.Replace(".", @"\."); limitedIP.Replace("*", @"[^\.]{1,3}"); Regex reg = new Regex(limitedIP, RegexOptions.Compiled); Match match = reg.Match(currentIP); return !match.Success; } /// <summary> /// 得到用户IP /// </summary> /// <returns></returns> public static string GetUserIP() { return HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"].ToString(); } } }