C#加密算法汇总

来源:互联网 发布:docker alpine java 编辑:程序博客网 时间:2024/05/10 01:16

本文转至: http://blog.csdn.net/fengyarongaa/article/details/6745453

[csharp] view plaincopyprint?
  1. 方法一: 
  2.     //须添加对System.Web的引用  
  3.     using System.Web.Security;  
  4.      
  5.     ...  
  6.      
  7.     /// <summary>  
  8.     /// SHA1加密字符串  
  9.     /// </summary>  
  10.     /// <param name="source">源字符串</param>  
  11.     /// <returns>加密后的字符串</returns>  
  12.     public string SHA1(string source)  
  13.     {  
  14.         return FormsAuthentication.HashPasswordForStoringInConfigFile(source,"SHA1");  
  15.     }  
  16.  
  17.  
  18.     /// <summary>  
  19.     /// MD5加密字符串  
  20.     /// </summary>  
  21.     /// <param name="source">源字符串</param> 
  22.     /// <returns>加密后的字符串</returns>  
  23.     public string MD5(string source)  
  24.     {  
  25.         return FormsAuthentication.HashPasswordForStoringInConfigFile(source,"MD5");;  
  26.     }  

[csharp] view plaincopyprint?
  1. 方法二(可逆加密解密): 
  2.     using System.Security.Cryptography;  
  3.      
  4.     ...  
  5.      
  6.     public string Encode(string data)  
  7.     {  
  8.         byte[] byKey = System.Text.ASCIIEncoding.ASCII.GetBytes(KEY_64);  
  9.         byte[] byIV = System.Text.ASCIIEncoding.ASCII.GetBytes(IV_64);  
  10.      
  11.         DESCryptoServiceProvider cryptoProvider = new DESCryptoServiceProvider();  
  12.         int i = cryptoProvider.KeySize;  
  13.         MemoryStream ms = new MemoryStream();  
  14.         CryptoStream cst = new CryptoStream(ms, cryptoProvider.CreateEncryptor(byKey, byIV), CryptoStreamMode.Write);  
  15.      
  16.         StreamWriter sw = new StreamWriter(cst);  
  17.         sw.Write(data);  
  18.         sw.Flush();  
  19.         cst.FlushFinalBlock();  
  20.         sw.Flush();  
  21.         return Convert.ToBase64String(ms.GetBuffer(), 0, (int)ms.Length);  
  22.      
  23.     }  
  24.      
  25.     public string Decode(string data)  
  26.     {  
  27.         byte[] byKey = System.Text.ASCIIEncoding.ASCII.GetBytes(KEY_64);  
  28.         byte[] byIV = System.Text.ASCIIEncoding.ASCII.GetBytes(IV_64);  
  29.      
  30.         byte[] byEnc;  
  31.         try  
  32.         {  
  33.             byEnc = Convert.FromBase64String(data);  
  34.         }  
  35.         catch  
  36.         {  
  37.             return null;  
  38.         }  
  39.      
  40.         DESCryptoServiceProvider cryptoProvider = new DESCryptoServiceProvider();  
  41.         MemoryStream ms = new MemoryStream(byEnc);  
  42.         CryptoStream cst = new CryptoStream(ms, cryptoProvider.CreateDecryptor(byKey, byIV), CryptoStreamMode.Read);  
  43.         StreamReader sr = new StreamReader(cst);  
  44.         return sr.ReadToEnd();  
  45.     }  

[csharp] view plaincopyprint?
  1. 方法三(MD5不可逆): 
  2.     using System.Security.Cryptography;  
  3.      
  4.     ...  
  5.      
  6.     //MD5不可逆加密  
  7.      
  8.     //32位加密  
  9.      
  10.     public string GetMD5_32(string s,string _input_charset)  
  11.     {  
  12.         MD5 md5 = new MD5CryptoServiceProvider();  
  13.         byte[] t = md5.ComputeHash(Encoding.GetEncoding(_input_charset).GetBytes(s));  
  14.         StringBuilder sb = new StringBuilder(32);  
  15.         for (int i = 0; i < t.Length; i++)  
  16.         {  
  17.             sb.Append(t[i].ToString("x").PadLeft(2,'0'));  
  18.         }  
  19.         return sb.ToString();  
  20.     }  
  21.      
  22.     //16位加密  
  23.     public staticstring GetMd5_16(string ConvertString)  
  24.     {  
  25.         MD5CryptoServiceProvider md5 = new MD5CryptoServiceProvider();  
  26.         string t2 = BitConverter.ToString(md5.ComputeHash(UTF8Encoding.Default.GetBytes(ConvertString)), 4, 8);  
  27.         t2 = t2.Replace("-","");  
  28.         return t2;  
  29.     }  

[csharp] view plaincopyprint?
  1. 方法四(对称加密): 
  2.     using System.IO;  
  3.     using System.Security.Cryptography;  
  4.      
  5.     ...  
  6.      
  7.     private SymmetricAlgorithm mobjCryptoService;  
  8.     private string Key;  
  9.     /// <summary>     
  10.     /// 对称加密类的构造函数     
  11.     /// </summary>     
  12.     public SymmetricMethod()  
  13.     {  
  14.         mobjCryptoService = new RijndaelManaged();  
  15.         Key = "Guz(%&hj7x89H$yuBI0456FtmaT5&fvHUFCy76*h%(HilJ$lhj!y6&(*jkP87jH7";  
  16.     }  
  17.     /// <summary>     
  18.     /// 获得密钥     
  19.     /// </summary>     
  20.     /// <returns>密钥</returns>     
  21.     private byte[] GetLegalKey()  
  22.     {  
  23.         string sTemp = Key;  
  24.         mobjCryptoService.GenerateKey();  
  25.         byte[] bytTemp = mobjCryptoService.Key;  
  26.         int KeyLength = bytTemp.Length;  
  27.         if (sTemp.Length > KeyLength)  
  28.             sTemp = sTemp.Substring(0, KeyLength);  
  29.         else if (sTemp.Length < KeyLength)  
  30.             sTemp = sTemp.PadRight(KeyLength, ' ');  
  31.         return ASCIIEncoding.ASCII.GetBytes(sTemp);  
  32.     }  
  33.     /// <summary>     
  34.     /// 获得初始向量IV     
  35.     /// </summary>     
  36.     /// <returns>初试向量IV</returns>     
  37.     private byte[] GetLegalIV()  
  38.     {  
  39.         string sTemp = "E4ghj*Ghg7!rNIfb&95GUY86GfghUb#er57HBh(u%g6HJ($jhWk7&!hg4ui%$hjk";  
  40.         mobjCryptoService.GenerateIV();  
  41.         byte[] bytTemp = mobjCryptoService.IV;  
  42.         int IVLength = bytTemp.Length;  
  43.         if (sTemp.Length > IVLength)  
  44.             sTemp = sTemp.Substring(0, IVLength);  
  45.         else if (sTemp.Length < IVLength)  
  46.             sTemp = sTemp.PadRight(IVLength, ' ');  
  47.         return ASCIIEncoding.ASCII.GetBytes(sTemp);  
  48.     }  
  49.     /// <summary>     
  50.     /// 加密方法     
  51.     /// </summary>     
  52.     /// <param name="Source">待加密的串</param>     
  53.     /// <returns>经过加密的串</returns>     
  54.     public string Encrypto(string Source)  
  55.     {  
  56.         byte[] bytIn = UTF8Encoding.UTF8.GetBytes(Source);  
  57.         MemoryStream ms = new MemoryStream();  
  58.         mobjCryptoService.Key = GetLegalKey();  
  59.         mobjCryptoService.IV = GetLegalIV();  
  60.         ICryptoTransform encrypto = mobjCryptoService.CreateEncryptor();  
  61.         CryptoStream cs = new CryptoStream(ms, encrypto, CryptoStreamMode.Write);  
  62.         cs.Write(bytIn, 0, bytIn.Length);  
  63.         cs.FlushFinalBlock();  
  64.         ms.Close();  
  65.         byte[] bytOut = ms.ToArray();  
  66.         return Convert.ToBase64String(bytOut);  
  67.     }  
  68.     /// <summary>     
  69.     /// 解密方法     
  70.     /// </summary>     
  71.     /// <param name="Source">待解密的串</param>    
  72.     /// <returns>经过解密的串</returns>     
  73.     public string Decrypto(string Source)  
  74.     {  
  75.         byte[] bytIn = Convert.FromBase64String(Source);  
  76.         MemoryStream ms = new MemoryStream(bytIn, 0, bytIn.Length);  
  77.         mobjCryptoService.Key = GetLegalKey();  
  78.         mobjCryptoService.IV = GetLegalIV();  
  79.         ICryptoTransform encrypto = mobjCryptoService.CreateDecryptor();  
  80.         CryptoStream cs = new CryptoStream(ms, encrypto, CryptoStreamMode.Read);  
  81.         StreamReader sr = new StreamReader(cs);  
  82.         return sr.ReadToEnd();  
  83.     }  

[csharp] view plaincopyprint?
  1. 方法五: 
  2.     using System.IO;  
  3.     using System.Security.Cryptography;  
  4.     using System.Text;  
  5.      
  6.     ...  
  7.      
  8.     //默认密钥向量  
  9.     private staticbyte[] Keys = { 0x12, 0x34, 0x56, 0x78, 0x90, 0xAB, 0xCD, 0xEF };  
  10.     /// <summary>  
  11.     /// DES加密字符串  
  12.     /// </summary>  
  13.     /// <param name="encryptString">待加密的字符串</param> 
  14.     /// <param name="encryptKey">加密密钥,要求为8位</param> 
  15.     /// <returns>加密成功返回加密后的字符串,失败返回源串</returns> 
  16.     public staticstring EncryptDES(string encryptString,string encryptKey)  
  17.     {  
  18.         try  
  19.         {  
  20.             byte[] rgbKey = Encoding.UTF8.GetBytes(encryptKey.Substring(0, 8));  
  21.             byte[] rgbIV = Keys;  
  22.             byte[] inputByteArray = Encoding.UTF8.GetBytes(encryptString);  
  23.             DESCryptoServiceProvider dCSP = new DESCryptoServiceProvider();  
  24.             MemoryStream mStream = new MemoryStream();  
  25.             CryptoStream cStream = new CryptoStream(mStream, dCSP.CreateEncryptor(rgbKey, rgbIV), CryptoStreamMode.Write);  
  26.             cStream.Write(inputByteArray, 0, inputByteArray.Length);  
  27.             cStream.FlushFinalBlock();  
  28.             return Convert.ToBase64String(mStream.ToArray());  
  29.         }  
  30.         catch  
  31.         {  
  32.             return encryptString;  
  33.         }  
  34.     }  
  35.      
  36.     /// <summary>  
  37.     /// DES解密字符串  
  38.     /// </summary>  
  39.     /// <param name="decryptString">待解密的字符串</param> 
  40.     /// <param name="decryptKey">解密密钥,要求为8位,和加密密钥相同</param> 
  41.     /// <returns>解密成功返回解密后的字符串,失败返源串</returns> 
  42.     public staticstring DecryptDES(string decryptString,string decryptKey)  
  43.     {  
  44.         try  
  45.         {  
  46.             byte[] rgbKey = Encoding.UTF8.GetBytes(decryptKey);  
  47.             byte[] rgbIV = Keys;  
  48.             byte[] inputByteArray = Convert.FromBase64String(decryptString);  
  49.             DESCryptoServiceProvider DCSP = new DESCryptoServiceProvider();  
  50.             MemoryStream mStream = new MemoryStream();  
  51.             CryptoStream cStream = new CryptoStream(mStream, DCSP.CreateDecryptor(rgbKey, rgbIV), CryptoStreamMode.Write);  
  52.             cStream.Write(inputByteArray, 0, inputByteArray.Length);  
  53.             cStream.FlushFinalBlock();  
  54.             return Encoding.UTF8.GetString(mStream.ToArray());  
  55.         }  
  56.         catch  
  57.         {  
  58.             return decryptString;  
  59.         }  
  60.     }   

[csharp] view plaincopyprint?
  1. 方法六(文件加密): 
  2.     using System.IO;  
  3.     using System.Security.Cryptography;  
  4.     using System.Text;  
  5.      
  6.     ...  
  7.      
  8.     //加密文件  
  9.     private staticvoid EncryptData(String inName, String outName,byte[] desKey, byte[] desIV)  
  10.     {  
  11.         //Create the file streams to handle the input and output files. 
  12.         FileStream fin = new FileStream(inName, FileMode.Open, FileAccess.Read);  
  13.         FileStream fout = new FileStream(outName, FileMode.OpenOrCreate, FileAccess.Write);  
  14.         fout.SetLength(0);  
  15.      
  16.         //Create variables to help with read and write. 
  17.         byte[] bin = new byte[100];//This is intermediate storage for the encryption.  
  18.         long rdlen = 0;             //This is the total number of bytes written.  
  19.         long totlen = fin.Length;   //This is the total length of the input file.  
  20.         int len;                    //This is the number of bytes to be written at a time. 
  21.      
  22.         DES des = new DESCryptoServiceProvider();  
  23.         CryptoStream encStream = new CryptoStream(fout, des.CreateEncryptor(desKey, desIV), CryptoStreamMode.Write);  
  24.      
  25.         //Read from the input file, then encrypt and write to the output file. 
  26.         while (rdlen < totlen)  
  27.         {  
  28.             len = fin.Read(bin, 0, 100);  
  29.             encStream.Write(bin, 0, len);  
  30.             rdlen = rdlen + len;  
  31.         }  
  32.      
  33.         encStream.Close();  
  34.         fout.Close();  
  35.         fin.Close();  
  36.     }  
  37.      
  38.     //解密文件  
  39.     private staticvoid DecryptData(String inName, String outName,byte[] desKey, byte[] desIV)  
  40.     {  
  41.         //Create the file streams to handle the input and output files. 
  42.         FileStream fin = new FileStream(inName, FileMode.Open, FileAccess.Read);  
  43.         FileStream fout = new FileStream(outName, FileMode.OpenOrCreate, FileAccess.Write);  
  44.         fout.SetLength(0);  
  45.      
  46.         //Create variables to help with read and write. 
  47.         byte[] bin = new byte[100];//This is intermediate storage for the encryption.  
  48.         long rdlen = 0;             //This is the total number of bytes written.  
  49.         long totlen = fin.Length;   //This is the total length of the input file.  
  50.         int len;                    //This is the number of bytes to be written at a time. 
  51.      
  52.         DES des = new DESCryptoServiceProvider();  
  53.         CryptoStream encStream = new CryptoStream(fout, des.CreateDecryptor(desKey, desIV), CryptoStreamMode.Write);  
  54.      
  55.         //Read from the input file, then encrypt and write to the output file. 
  56.         while (rdlen < totlen)  
  57.         {  
  58.             len = fin.Read(bin, 0, 100);  
  59.             encStream.Write(bin, 0, len);  
  60.             rdlen = rdlen + len;  
  61.         }  
  62.      
  63.         encStream.Close();  
  64.         fout.Close();  
  65.         fin.Close();  
  66.  


[csharp] view plaincopyprint?
  1. using System; 
  2. using System.Security.Cryptography;//这个是处理文字编码的前提 
  3. using System.Text; 
  4. using System.IO; 
  5. /// <summary> 
  6. /// DES加密方法 
  7. /// </summary> 
  8. /// <param name="strPlain">明文</param> 
  9. /// <param name="strDESKey">密钥</param> 
  10. /// <param name="strDESIV">向量</param> 
  11. /// <returns>密文</returns> 
  12. public string DESEncrypt(string strPlain,string strDESKey,string strDESIV) 
  13. //把密钥转换成字节数组 
  14. byte[] bytesDESKey=ASCIIEncoding.ASCII.GetBytes(strDESKey); 
  15. //把向量转换成字节数组 
  16. byte[] bytesDESIV=ASCIIEncoding.ASCII.GetBytes(strDESIV); 
  17. //声明1个新的DES对象 
  18. DESCryptoServiceProvider desEncrypt=new DESCryptoServiceProvider(); 
  19. //开辟一块内存流 
  20. MemoryStream msEncrypt=new MemoryStream(); 
  21. //把内存流对象包装成加密流对象 
  22. CryptoStream csEncrypt=new CryptoStream(msEncrypt,desEncrypt.CreateEncryptor(bytesDESKey,bytesDESIV),CryptoStreamMode.Write); 
  23. //把加密流对象包装成写入流对象 
  24. StreamWriter swEncrypt=new StreamWriter(csEncrypt); 
  25. //写入流对象写入明文 
  26. swEncrypt.WriteLine(strPlain); 
  27. //写入流关闭 
  28. swEncrypt.Close(); 
  29. //加密流关闭 
  30. csEncrypt.Close(); 
  31. //把内存流转换成字节数组,内存流现在已经是密文了 
  32. byte[] bytesCipher=msEncrypt.ToArray(); 
  33. //内存流关闭 
  34. msEncrypt.Close(); 
  35. //把密文字节数组转换为字符串,并返回 
  36. return UnicodeEncoding.Unicode.GetString(bytesCipher); 
  37.  
  38.  
  39.  
  40.  
  41. /// <summary> 
  42. /// DES解密方法 
  43. /// </summary> 
  44. /// <param name="strCipher">密文</param> 
  45. /// <param name="strDESKey">密钥</param> 
  46. /// <param name="strDESIV">向量</param> 
  47. /// <returns>明文</returns> 
  48. public string DESDecrypt(string strCipher,string strDESKey,string strDESIV) 
  49. //把密钥转换成字节数组 
  50. byte[] bytesDESKey=ASCIIEncoding.ASCII.GetBytes(strDESKey); 
  51. //把向量转换成字节数组 
  52. byte[] bytesDESIV=ASCIIEncoding.ASCII.GetBytes(strDESIV); 
  53. //把密文转换成字节数组 
  54. byte[] bytesCipher=UnicodeEncoding.Unicode.GetBytes(strCipher); 
  55. //声明1个新的DES对象 
  56. DESCryptoServiceProvider desDecrypt=new DESCryptoServiceProvider(); 
  57. //开辟一块内存流,并存放密文字节数组 
  58. MemoryStream msDecrypt=new MemoryStream(bytesCipher); 
  59. //把内存流对象包装成解密流对象 
  60. CryptoStream csDecrypt=new CryptoStream(msDecrypt,desDecrypt.CreateDecryptor(bytesDESKey,bytesDESIV),CryptoStreamMode.Read); 
  61. //把解密流对象包装成读出流对象 
  62. StreamReader srDecrypt=new StreamReader(csDecrypt); 
  63. //明文=读出流的读出内容 
  64. string strPlainText=srDecrypt.ReadLine(); 
  65. //读出流关闭 
  66. srDecrypt.Close(); 
  67. //解密流关闭 
  68. csDecrypt.Close(); 
  69. //内存流关闭 
  70. msDecrypt.Close(); 
  71. //返回明文 
  72. return strPlainText; 

 

原创粉丝点击