123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627 |
- using System;
- using System.Collections.Generic;
- using System.Text;
- using System.Security;
- using System.Security.Cryptography;
- using System.IO;
- namespace SysSecLibs
- {
- public class SysSecurity
- {
- private static string _Key = "HaiTingA";
- public static string Encrypt4CPlus(string pToEncrypt)
- {
- return Encrypt4CPlus(pToEncrypt, _Key);
- }
- public static string Decrypt4CPlus(string pToDecrypt)
- {
- return Decrypt4CPlus(pToDecrypt, _Key);
- }
- /// <summary>
- /// DES加密算法
- /// </summary>
- /// <param name="pToEncrypt"></param>
- /// <param name="sKey"></param>
- /// <returns></returns>
- public static string Encrypt4CPlus(string pToEncrypt, string sKey)
- {
- if (pToEncrypt.Length == 0)
- return "";
- byte[] KeyIVs = { 0x80, 0x40, 0x20, 0x10, 0x08, 0x04, 0x02, 0x01 };
- try
- {
- DESCryptoServiceProvider des = new DESCryptoServiceProvider();
- byte[] inputByteArray = Encoding.UTF8.GetBytes(pToEncrypt);
- /*des.Key = ASCIIEncoding.ASCII.GetBytes(sKey);
- des.IV = ASCIIEncoding.ASCII.GetBytes(sKey);*/
- des.Key = Encoding.UTF8.GetBytes(sKey);
- des.IV = KeyIVs;
- //加密模式/填充方式
- des.Mode = CipherMode.ECB;
- des.Padding = PaddingMode.Zeros;
- 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);
- }
- return ret.ToString();
- }
- catch (Exception e)
- {
- throw e;
- }
- }
- /// <summary>
- /// DES解密算法
- /// </summary>
- /// <param name="pToDecrypt"></param>
- /// <param name="sKey"></param>
- /// <returns></returns>
- public static string Decrypt4CPlus(string pToDecrypt, string sKey)
- {
- if (pToDecrypt.Length == 0)
- return "";
- try
- {
- byte[] KeyIVs = { 0x80, 0x40, 0x20, 0x10, 0x08, 0x04, 0x02, 0x01 };
- DESCryptoServiceProvider des = new DESCryptoServiceProvider();
- byte[] inputByteArray = new byte[pToDecrypt.Length / 2];
- for (int x = 0; x < pToDecrypt.Length / 2; x++)
- {
- int i = (Convert.ToInt32(pToDecrypt.Substring(x * 2, 2), 16));
- inputByteArray[x] = (byte)i;
- }
- des.Key = Encoding.UTF8.GetBytes(sKey);
- des.IV = KeyIVs;
- des.Mode = CipherMode.ECB;
- des.Padding = PaddingMode.Zeros;
- 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());
- }
- catch (Exception e)
- {
- throw e;
- }
- }
- public static string Encrypt(string pToEncrypt)
- {
- return Encrypt(pToEncrypt, _Key);
- }
- //加密方法
- /// <summary>
- /// 加密一个字符串
- /// </summary>
- /// <param name="pToEncrypt">要加密的字符串</param>
- /// <param name="sKey">密约</param>
- /// <returns></returns>
- public static string Encrypt(string pToEncrypt, string sKey)
- {
- if (pToEncrypt.Length == 0)
- return "";
- try
- {
- DESCryptoServiceProvider des = new DESCryptoServiceProvider();
- byte[] inputByteArray = Encoding.Default.GetBytes(pToEncrypt);
- des.Key = ASCIIEncoding.ASCII.GetBytes(sKey);
- des.IV = ASCIIEncoding.ASCII.GetBytes(sKey);
- 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);
- }
- return ret.ToString();
- }
- catch (Exception e)
- {
- throw e;
- }
- }
- public static string Decrypt(string pToDecrypt)
- {
- return Decrypt(pToDecrypt, _Key);
- }
- //解密方法
- /// <summary>
- /// 解密一个字符串
- /// </summary>
- /// <param name="pToDecrypt">要解密的字符串</param>
- /// <param name="sKey">解密钥</param>
- /// <returns></returns>
- public static string Decrypt(string pToDecrypt, string sKey)
- {
- if (pToDecrypt.Length == 0)
- return "";
- try
- {
- DESCryptoServiceProvider des = new DESCryptoServiceProvider();
- byte[] inputByteArray = new byte[pToDecrypt.Length / 2];
- for (int x = 0; x < pToDecrypt.Length / 2; x++)
- {
- int i = (Convert.ToInt32(pToDecrypt.Substring(x * 2, 2), 16));
- inputByteArray[x] = (byte)i;
- }
- des.Key = ASCIIEncoding.ASCII.GetBytes(sKey);
- des.IV = ASCIIEncoding.ASCII.GetBytes(sKey);
- 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());
- }
- catch (Exception e)
- {
- throw e;
- }
- }
- public static string Encrypt3DES(string strString, string strKey, Encoding encoding)
- {
- TripleDESCryptoServiceProvider DES = new TripleDESCryptoServiceProvider();
- MD5CryptoServiceProvider hashMD5 = new MD5CryptoServiceProvider();
- DES.Key = hashMD5.ComputeHash(encoding.GetBytes(strKey));
- DES.Mode = CipherMode.ECB;
- ICryptoTransform DESEncrypt = DES.CreateEncryptor();
- byte[] Buffer = encoding.GetBytes(strString);
- return Convert.ToBase64String(DESEncrypt.TransformFinalBlock(Buffer, 0, Buffer.Length));
- }
- /// <summary>
- /// 解密
- /// </summary>
- /// <param name="strString"></param>
- /// <param name="strKey"></param>
- /// <returns></returns>
- public static string Decrypt3DES(string strString, string strKey)
- {
- TripleDESCryptoServiceProvider DES = new TripleDESCryptoServiceProvider();
- MD5CryptoServiceProvider hashMD5 = new MD5CryptoServiceProvider();
- DES.Key = hashMD5.ComputeHash(ASCIIEncoding.ASCII.GetBytes(strKey));
- DES.Mode = CipherMode.ECB;
- ICryptoTransform DESDecrypt = DES.CreateDecryptor();
- string result = "";
- try
- {
- byte[] Buffer = Convert.FromBase64String(strString);
- result = ASCIIEncoding.ASCII.GetString(DESDecrypt.TransformFinalBlock(Buffer, 0, Buffer.Length));
- }
- catch (System.Exception e)
- {
- throw (new System.Exception("null", e));
- }
- return result;
- }
- /// <summary>
- /// 解密base64 串
- /// </summary>
- /// <param name="Message"></param>
- /// <returns></returns>
- public static string Base64Decode(string Message)
- {
- if ((Message.Length % 4) != 0)
- {
- throw new ArgumentException("不是正确的BASE64编码,请检查。", "Message");
- }
- if (!System.Text.RegularExpressions.Regex.IsMatch(Message, "^[A-Z0-9/+=]*$", System.Text.RegularExpressions.RegexOptions.IgnoreCase))
- {
- throw new ArgumentException("包含不正确的BASE64编码,请检查。", "Message");
- }
- string Base64Code = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
- int page = Message.Length / 4;
- System.Collections.ArrayList outMessage = new System.Collections.ArrayList(page * 3);
- char[] message = Message.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 System.Text.Encoding.Default.GetString(outbyte);
- }
- }
- //===================================================
- /// <summary>
- /// 此处定义的是DES加密,为了便于今后的管理和维护
- /// 请不要随便改动密码,或者改变了密码后请一定要
- /// 牢记先前的密码,否则将会照成不可预料的损失
- /// </summary>
- public class DESEncrypt
- {
- #region "member fields"
- private string iv = "HaitingA";//SongHongSongHaitingA
- private string key = "YouYouBB";//SongHongYouYouBaoBei
- private Encoding encoding = new UnicodeEncoding();
- private DES des;
- #endregion
- /// <summary>
- /// 构造函数
- /// </summary>
- public DESEncrypt()
- {
- des = new DESCryptoServiceProvider();
- }
- #region "propertys"
- /// <summary>
- /// 设置加密密钥
- /// </summary>
- public string EncryptKey
- {
- get { return this.key; }
- set
- {
- this.key = value;
- }
- }
- /// <summary>
- /// 要加密字符的编码模式
- /// </summary>
- public Encoding EncodingMode
- {
- get { return this.encoding; }
- set { this.encoding = value; }
- }
- #endregion
- #region "methods"
- /// <summary>
- /// 加密字符串并返回加密后的结果
- /// </summary>
- /// <param name="str"></param>
- /// <returns></returns>
- public string EncryptString(string str)
- {
- try
- {
- byte[] ivb = Encoding.ASCII.GetBytes(this.iv);
- byte[] keyb = Encoding.ASCII.GetBytes(this.EncryptKey);//得到加密密钥
- byte[] toEncrypt = this.EncodingMode.GetBytes(str);//得到要加密的内容
- byte[] encrypted;
- ICryptoTransform encryptor = des.CreateEncryptor(keyb, ivb);
- MemoryStream msEncrypt = new MemoryStream();
- CryptoStream csEncrypt = new CryptoStream(msEncrypt, encryptor, CryptoStreamMode.Write);
- csEncrypt.Write(toEncrypt, 0, toEncrypt.Length);
- csEncrypt.FlushFinalBlock();
- encrypted = msEncrypt.ToArray();
- csEncrypt.Close();
- msEncrypt.Close();
- return this.EncodingMode.GetString(encrypted);
- }
- catch (Exception e)
- {
- throw e;
- }
- }
- /// <summary>
- /// 加密指定的文件,如果成功返回True,否则false
- /// </summary>
- /// <param name="filePath">要加密的文件路径</param>
- /// <param name="outPath">加密后的文件输出路径</param>
- public void EncryptFile(string filePath, string outPath)
- {
- bool isExist = File.Exists(filePath);
- if (isExist)//如果存在
- {
- byte[] ivb = Encoding.ASCII.GetBytes(this.iv);
- byte[] keyb = Encoding.ASCII.GetBytes(this.EncryptKey);
- //得到要加密文件的字节流
- FileStream fin = new FileStream(filePath, FileMode.Open, FileAccess.Read);
- StreamReader reader = new StreamReader(fin, this.EncodingMode);
- string dataStr = reader.ReadToEnd();
- byte[] toEncrypt = this.EncodingMode.GetBytes(dataStr);
- fin.Close();
- FileStream fout = new FileStream(outPath, FileMode.Create, FileAccess.Write);
- ICryptoTransform encryptor = des.CreateEncryptor(keyb, ivb);
- CryptoStream csEncrypt = new CryptoStream(fout, encryptor, CryptoStreamMode.Write);
- try
- {
- //加密得到的文件字节流
- csEncrypt.Write(toEncrypt, 0, toEncrypt.Length);
- csEncrypt.FlushFinalBlock();
- }
- catch (Exception err)
- {
- throw new ApplicationException(err.Message);
- }
- finally
- {
- try
- {
- fout.Close();
- csEncrypt.Close();
- }
- catch
- {
- ;
- }
- }
- }
- else
- {
- throw new FileNotFoundException("没有找到指定的文件");
- }
- }
- /// <summary>
- /// 文件加密函数的重载版本,如果不指定输出路径,
- /// 那么原来的文件将被加密后的文件覆盖
- /// </summary>
- /// <param name="filePath"></param>
- public void EncryptFile(string filePath)
- {
- this.EncryptFile(filePath, filePath);
- }
- /// <summary>
- /// 解密给定的字符串
- /// </summary>
- /// <param name="str">要解密的字符</param>
- /// <returns></returns>
- public string DecryptString(string str)
- {
- byte[] ivb = Encoding.ASCII.GetBytes(this.iv);
- byte[] keyb = Encoding.ASCII.GetBytes(this.EncryptKey);
- byte[] toDecrypt = this.EncodingMode.GetBytes(str);
- byte[] deCrypted = new byte[toDecrypt.Length];
- ICryptoTransform deCryptor = des.CreateDecryptor(keyb, ivb);
- MemoryStream msDecrypt = new MemoryStream(toDecrypt);
- CryptoStream csDecrypt = new CryptoStream(msDecrypt, deCryptor, CryptoStreamMode.Read);
- try
- {
- csDecrypt.Read(deCrypted, 0, deCrypted.Length);
- }
- catch (Exception err)
- {
- throw new ApplicationException(err.Message);
- }
- finally
- {
- try
- {
- msDecrypt.Close();
- csDecrypt.Close();
- }
- catch { ;}
- }
- return this.EncodingMode.GetString(deCrypted);
- }
- /// <summary>
- /// 解密指定的文件
- /// </summary>
- /// <param name="filePath">要解密的文件路径</param>
- /// <param name="outPath">解密后的文件输出路径</param>
- public void DecryptFile(string filePath, string outPath)
- {
- bool isExist = File.Exists(filePath);
- if (isExist)//如果存在
- {
- byte[] ivb = Encoding.ASCII.GetBytes(this.iv);
- byte[] keyb = Encoding.ASCII.GetBytes(this.EncryptKey);
- FileInfo file = new FileInfo(filePath);
- byte[] deCrypted = new byte[file.Length];
- //得到要解密文件的字节流
- FileStream fin = new FileStream(filePath, FileMode.Open, FileAccess.Read);
- //解密文件
- try
- {
- ICryptoTransform decryptor = des.CreateDecryptor(keyb, ivb);
- CryptoStream csDecrypt = new CryptoStream(fin, decryptor, CryptoStreamMode.Read);
- csDecrypt.Read(deCrypted, 0, deCrypted.Length);
- }
- catch (Exception err)
- {
- throw new ApplicationException(err.Message);
- }
- finally
- {
- try
- {
- fin.Close();
- }
- catch { ;}
- }
- FileStream fout = new FileStream(outPath, FileMode.Create, FileAccess.Write);
- fout.Write(deCrypted, 0, deCrypted.Length);
- fout.Close();
- }
- else
- {
- throw new FileNotFoundException("指定的解密文件没有找到");
- }
- }
- /// <summary>
- /// 解密文件的重载版本,如果没有给出解密后文件的输出路径,
- /// 则解密后的文件将覆盖先前的文件
- /// </summary>
- /// <param name="filePath"></param>
- public void DecryptFile(string filePath)
- {
- this.DecryptFile(filePath, filePath);
- }
- #endregion
- }
- //===============================================================
- /// <summary>
- /// MD5加密类,注意经MD5加密过的信息是不能转换回原始数据的
- /// ,请不要在用户敏感的信息中使用此加密技术,比如用户的密码,
- /// 请尽量使用对称加密
- /// </summary>
- public class MD5Encrypt
- {
- private MD5 md5;
- public MD5Encrypt()
- {
- md5 = new MD5CryptoServiceProvider();
- }
- /// <summary>
- /// 从字符串中获取散列值
- /// </summary>
- /// <param name="str">要计算散列值的字符串</param>
- /// <returns></returns>
- public string GetMD5FromString(string str)
- {
- byte[] toCompute = Encoding.Unicode.GetBytes(str);
- byte[] hashed = md5.ComputeHash(toCompute, 0, toCompute.Length);
- return Encoding.ASCII.GetString(hashed);
- }
- /// <summary>
- /// 根据文件来计算散列值
- /// </summary>
- /// <param name="filePath">要计算散列值的文件路径</param>
- /// <returns></returns>
- public string GetMD5FromFile(string filePath)
- {
- bool isExist = File.Exists(filePath);
- if (isExist)//如果文件存在
- {
- FileStream stream = new FileStream(filePath, FileMode.Open, FileAccess.Read);
- StreamReader reader = new StreamReader(stream, Encoding.Unicode);
- string str = reader.ReadToEnd();
- byte[] toHash = Encoding.Unicode.GetBytes(str);
- byte[] hashed = md5.ComputeHash(toHash, 0, toHash.Length);
- stream.Close();
- return Encoding.ASCII.GetString(hashed);
- }
- else//文件不存在
- {
- throw new FileNotFoundException("指定的文件没有找到");
- }
- }
- }
- //================================================================
- /// <summary>
- /// 用于数字签名的hash类
- /// </summary>
- public class MACTripleDESEncrypt
- {
- private MACTripleDES mact;
- private string __key = "ksn168ch";
- private byte[] __data = null;
- public MACTripleDESEncrypt()
- {
- mact = new MACTripleDES();
- }
- /// <summary>
- /// 获取或设置用于数字签名的密钥
- /// </summary>
- public string Key
- {
- get { return this.__key; }
- set
- {
- int keyLength = value.Length;
- int[] keyAllowLengths = new int[] { 8, 16, 24 };
- bool isRight = false;
- foreach (int i in keyAllowLengths)
- {
- if (keyLength == keyAllowLengths[i])
- {
- isRight = true;
- break;
- }
- }
- if (!isRight)
- throw new ApplicationException("用于数字签名的密钥长度必须是8,16,24值之一");
- else
- this.__key = value;
- }
- }
- /// <summary>
- /// 获取或设置用于数字签名的用户数据
- /// </summary>
- public byte[] Data
- {
- get { return this.__data; }
- set { this.__data = value; }
- }
- /// <summary>
- /// 得到签名后的hash值
- /// </summary>
- /// <returns></returns>
- public string GetHashValue()
- {
- if (this.Data == null)
- throw new Exception("没有设置要进行数字签名的用户" + "数据(property:Data)");
- byte[] key = Encoding.ASCII.GetBytes(this.Key);
- this.mact.Key = key;
- byte[] hash_b = this.mact.ComputeHash(this.mact.ComputeHash(this.Data));
- return Encoding.ASCII.GetString(hash_b);
- }
- }
- }
|