C#之各加解密算法

 

  1     using System.Security.Cryptography;
  2     class Algorithm
  3     {
  4         /// <summary>  
  5         /// AES加密(无向量)-128位
  6         /// </summary>  
  7         /// <param name="plainBytes">被加密的明文</param>  
  8         /// <param name="key">密钥</param>  
  9         /// <returns>密文</returns>  
 10         public static string AESEncrypt(String Data, String Key)
 11         {
 12             MemoryStream mStream = new MemoryStream();
 13             RijndaelManaged aes = new RijndaelManaged();
 14 
 15             byte[] plainBytes = Encoding.UTF8.GetBytes(Data);
 16             Byte[] bKey = new Byte[32];
 17             Array.Copy(Encoding.UTF8.GetBytes(Key.PadRight(bKey.Length)), bKey, bKey.Length);
 18 
 19             aes.Mode = CipherMode.ECB;
 20             aes.Padding = PaddingMode.PKCS7;
 21             aes.KeySize = 128;
 22             //aes.Key = _key;  
 23             aes.Key = bKey;
 24             //aes.IV = _iV;  
 25             CryptoStream cryptoStream = new CryptoStream(mStream, aes.CreateEncryptor(), CryptoStreamMode.Write);
 26             try
 27             {
 28                 cryptoStream.Write(plainBytes, 0, plainBytes.Length);
 29                 cryptoStream.FlushFinalBlock();
 30                 return Convert.ToBase64String(mStream.ToArray());
 31             }
 32             finally
 33             {
 34                 cryptoStream.Close();
 35                 mStream.Close();
 36                 aes.Clear();
 37             }
 38         }
 39         /// <summary>
 40         /// AES解密(无向量)-128位 
 41         /// </summary>  
 42         /// <param name="encryptedBytes">被加密的明文</param>  
 43         /// <param name="key">密钥</param>  
 44         /// <returns>明文</returns>  
 45         public static string AESDecrypt(String Data, String Key)
 46         {
 47             Byte[] encryptedBytes = Convert.FromBase64String(Data);
 48             Byte[] bKey = new Byte[32];
 49             Array.Copy(Encoding.UTF8.GetBytes(Key.PadRight(bKey.Length)), bKey, bKey.Length);
 50 
 51             MemoryStream mStream = new MemoryStream(encryptedBytes);
 52             //mStream.Write( encryptedBytes, 0, encryptedBytes.Length );  
 53             //mStream.Seek( 0, SeekOrigin.Begin );  
 54             RijndaelManaged aes = new RijndaelManaged();
 55             aes.Mode = CipherMode.ECB;
 56             aes.Padding = PaddingMode.PKCS7;
 57             aes.KeySize = 128;
 58             aes.Key = bKey;
 59             //aes.IV = _iV;  
 60             CryptoStream cryptoStream = new CryptoStream(mStream, aes.CreateDecryptor(), CryptoStreamMode.Read);
 61             try
 62             {
 63                 byte[] tmp = new byte[encryptedBytes.Length + 32];
 64                 int len = cryptoStream.Read(tmp, 0, encryptedBytes.Length + 32);
 65                 byte[] ret = new byte[len];
 66                 Array.Copy(tmp, 0, ret, 0, len);
 67                 return Encoding.UTF8.GetString(ret);
 68             }
 69             finally
 70             {
 71                 cryptoStream.Close();
 72                 mStream.Close();
 73                 aes.Clear();
 74             }
 75         }
 76         /// <summary>
 77         ///  AES 加密-256位
 78         /// </summary>
 79         /// <param name="str"></param>
 80         /// <param name="key"></param>
 81         /// <returns></returns>
 82         public static string AesEncrypt(string str, string key)
 83         {
 84             if (string.IsNullOrEmpty(str)) return null;
 85             Byte[] toEncryptArray = Encoding.UTF8.GetBytes(str);
 86             RijndaelManaged rm = new RijndaelManaged
 87             {
 88                 Key = Encoding.UTF8.GetBytes(key),
 89                 Mode = CipherMode.ECB,
 90                 Padding = PaddingMode.PKCS7
 91             };
 92             ICryptoTransform cTransform = rm.CreateEncryptor();
 93             Byte[] resultArray = cTransform.TransformFinalBlock(toEncryptArray, 0, toEncryptArray.Length);
 94             return Convert.ToBase64String(resultArray, 0, resultArray.Length);
 95         }
 96         /// <summary>
 97         ///  AES 解密-256位
 98         /// </summary>
 99         /// <param name="str"></param>
100         /// <param name="key"></param>
101         /// <returns></returns>
102         public static string AesDecrypt(string str, string key)
103         {
104             if (string.IsNullOrEmpty(str)) return null;
105             Byte[] toEncryptArray = Convert.FromBase64String(str);
106             RijndaelManaged rm = new RijndaelManaged
107             {
108                 Key = Encoding.UTF8.GetBytes(key),
109                 Mode = CipherMode.ECB,
110                 Padding = PaddingMode.PKCS7
111             };
112             ICryptoTransform cTransform = rm.CreateDecryptor();
113             Byte[] resultArray = cTransform.TransformFinalBlock(toEncryptArray, 0, toEncryptArray.Length);
114             return Encoding.UTF8.GetString(resultArray);
115         }
116 
117         //默认密钥向量
118         private static byte[] Keys = { 0x12, 0x34, 0x56, 0x78, 0x90, 0xAB, 0xCD, 0xEF };        
119         /// <summary>
120         /// DES加密字符串
121         /// </summary>
122         /// <param name="encryptString">待加密的字符串</param>
123         /// <param name="encryptKey">加密密钥,要求为8位</param>
124         /// <returns>加密成功返回加密后的字符串,失败返回源串</returns>
125         public static string EncryptDES(string encryptString, string encryptKey)
126         {
127             try
128             {
129                 byte[] rgbKey = Encoding.UTF8.GetBytes(encryptKey.Substring(0, 8));
130                 byte[] rgbIV = Keys;
131                 byte[] inputByteArray = Encoding.UTF8.GetBytes(encryptString);
132                 DESCryptoServiceProvider dCSP = new DESCryptoServiceProvider();
133                 MemoryStream mStream = new MemoryStream();
134                 CryptoStream cStream = new CryptoStream(mStream, dCSP.CreateEncryptor(rgbKey, rgbIV), CryptoStreamMode.Write);
135                 cStream.Write(inputByteArray, 0, inputByteArray.Length);
136                 cStream.FlushFinalBlock();
137                 return Convert.ToBase64String(mStream.ToArray());
138             }
139             catch
140             {
141                 return encryptString;
142             }
143         }
144         /// <summary>
145         /// DES解密字符串
146         /// </summary>
147         /// <param name="decryptString">待解密的字符串</param>
148         /// <param name="decryptKey">解密密钥,要求为8位,和加密密钥相同</param>
149         /// <returns>解密成功返回解密后的字符串,失败返源串</returns>
150         public static string DecryptDES(string decryptString, string decryptKey)
151         {
152             try
153             {
154                 byte[] rgbKey = Encoding.UTF8.GetBytes(decryptKey);
155                 byte[] rgbIV = Keys;
156                 byte[] inputByteArray = Convert.FromBase64String(decryptString);
157                 DESCryptoServiceProvider DCSP = new DESCryptoServiceProvider();
158                 MemoryStream mStream = new MemoryStream();
159                 CryptoStream cStream = new CryptoStream(mStream, DCSP.CreateDecryptor(rgbKey, rgbIV), CryptoStreamMode.Write);
160                 cStream.Write(inputByteArray, 0, inputByteArray.Length);
161                 cStream.FlushFinalBlock();
162                 return Encoding.UTF8.GetString(mStream.ToArray());
163             }
164             catch
165             {
166                 return decryptString;
167             }
168         }
169         /// <summary>
170         /// DES-BASE64 加密
171         /// </summary>
172         /// <param name="enStr">明文</param>
173         /// <param name="key">密钥</param>
174         /// <param name="iv">向量</param>
175         /// <returns>密文</returns>
176         public static string Des64Encrypt(string enStr, string key, string iv)
177         {
178             byte[] byKey = System.Text.ASCIIEncoding.ASCII.GetBytes(key);
179             byte[] byIV = System.Text.ASCIIEncoding.ASCII.GetBytes(iv);
180             DESCryptoServiceProvider cryptoProvider = new DESCryptoServiceProvider();
181             int i = cryptoProvider.KeySize;
182             MemoryStream ms = new MemoryStream();
183             CryptoStream cst = new CryptoStream(ms, cryptoProvider.CreateEncryptor(byKey, byIV), CryptoStreamMode.Write);
184 
185             StreamWriter sw = new StreamWriter(cst);
186             sw.Write(enStr);
187             sw.Flush();
188             cst.FlushFinalBlock();
189             sw.Flush();
190             return Convert.ToBase64String(ms.GetBuffer(), 0, (int)ms.Length);
191         }
192         /// <summary>
193         /// DES-BASE64 解密
194         /// </summary>
195         /// <param name="deStr">密文</param>
196         /// <param name="key">密钥</param>
197         /// <param name="iv">向量</param>
198         /// <returns>明文</returns>
199         public static string Des64Decrypt(string deStr, string key, string iv)
200         {
201             byte[] byKey = System.Text.ASCIIEncoding.ASCII.GetBytes(key);
202             byte[] byIV = System.Text.ASCIIEncoding.ASCII.GetBytes(iv);
203 
204             byte[] byEnc;
205             try
206             {
207                 byEnc = Convert.FromBase64String(deStr);
208             }
209             catch
210             {
211                 return null;
212             }
213 
214             DESCryptoServiceProvider cryptoProvider = new DESCryptoServiceProvider();
215             MemoryStream ms = new MemoryStream(byEnc);
216             CryptoStream cst = new CryptoStream(ms, cryptoProvider.CreateDecryptor(byKey, byIV), CryptoStreamMode.Read);
217             StreamReader sr = new StreamReader(cst);
218             return sr.ReadToEnd();
219 
220         }
221         /// <summary>
222         /// 与ASP兼容的MD5加密算法-不可逆
223         /// </summary>
224         /// <param name="str"></param>
225         /// <param name="charset">字符集</param>
226         /// <returns>密文</returns>
227         public string GetMD5(string str, string charset)
228         {
229             MD5 md5 = new MD5CryptoServiceProvider();
230             byte[] t = md5.ComputeHash(Encoding.GetEncoding(charset).GetBytes(str));
231             StringBuilder sb = new StringBuilder(32);
232             for (int i = 0; i < t.Length; i++)
233             {
234                 sb.Append(t[i].ToString("x").PadLeft(2, '0'));
235             }
236             return sb.ToString();
237         }
238 
239         /// <summary>
240         /// DES加密文件
241         /// </summary>
242         /// <param name="inName">明文件</param>
243         /// <param name="outName">密文件</param>
244         /// <param name="deskey">密钥</param>
245         /// <param name="desiv">向量</param>
246         private static void EncryptData(String inName, String outName,string deskey , string desiv)
247         {
248             byte[] desKey= System.Text.ASCIIEncoding.ASCII.GetBytes(deskey);
249             byte[] desIV = System.Text.ASCIIEncoding.ASCII.GetBytes(desiv);
250             //Create the file streams to handle the input and output files.
251             FileStream fin = new FileStream(inName, FileMode.Open, FileAccess.Read);
252             FileStream fout = new FileStream(outName, FileMode.OpenOrCreate, FileAccess.Write);
253             fout.SetLength(0);
254 
255             //Create variables to help with read and write.
256             byte[] bin = new byte[100]; //This is intermediate storage for the encryption.
257             long rdlen = 0;              //This is the total number of bytes written.
258             long totlen = fin.Length;    //This is the total length of the input file.
259             int len;                     //This is the number of bytes to be written at a time.
260 
261             DES des = new DESCryptoServiceProvider();
262             CryptoStream encStream = new CryptoStream(fout, des.CreateEncryptor(desKey, desIV), CryptoStreamMode.Write);
263 
264             //Read from the input file, then encrypt and write to the output file.
265             while (rdlen < totlen)
266             {
267                 len = fin.Read(bin, 0, 100);
268                 encStream.Write(bin, 0, len);
269                 rdlen = rdlen + len;
270             }
271 
272             encStream.Close();
273             fout.Close();
274             fin.Close();
275         }
276         /// <summary>
277         /// DES解密文件
278         /// </summary>
279         /// <param name="inName">密文件</param>
280         /// <param name="outName">明文件</param>
281         /// <param name="deskey">密钥</param>
282         /// <param name="desiv">向量</param>
283         private static void DecryptData(String inName, String outName, string deskey, string desiv)
284         {
285             byte[] desKey = System.Text.ASCIIEncoding.ASCII.GetBytes(deskey);
286             byte[] desIV = System.Text.ASCIIEncoding.ASCII.GetBytes(desiv);
287             //Create the file streams to handle the input and output files.
288             FileStream fin = new FileStream(inName, FileMode.Open, FileAccess.Read);
289             FileStream fout = new FileStream(outName, FileMode.OpenOrCreate, FileAccess.Write);
290             fout.SetLength(0);
291 
292             //Create variables to help with read and write.
293             byte[] bin = new byte[100]; //This is intermediate storage for the encryption.
294             long rdlen = 0;              //This is the total number of bytes written.
295             long totlen = fin.Length;    //This is the total length of the input file.
296             int len;                     //This is the number of bytes to be written at a time.
297 
298             DES des = new DESCryptoServiceProvider();
299             CryptoStream encStream = new CryptoStream(fout, des.CreateDecryptor(desKey, desIV), CryptoStreamMode.Write);
300 
301             //Read from the input file, then encrypt and write to the output file.
302             while (rdlen < totlen)
303             {
304                 len = fin.Read(bin, 0, 100);
305                 encStream.Write(bin, 0, len);
306                 rdlen = rdlen + len;
307             }
308 
309             encStream.Close();
310             fout.Close();
311             fin.Close();
312         }
313     }
View Code

 

posted @ 2017-03-23 17:31  ShawSir  阅读(82)  评论(0编辑  收藏  举报