C# 五种加密方式

  1. //须添加对System.Web的引用  
  2.   
  3. using System.Web.Security;  
  4.   
  5.    
  6.   
  7. ...  
  8.   
  9.    
  10.   
  11. /// <summary>  
  12.   
  13. /// SHA1加密字符串  
  14.   
  15. /// </summary>  
  16.   
  17. /// <param name="source">源字符串</param>  
  18.   
  19. /// <returns>加密后的字符串</returns>  
  20.   
  21. public string SHA1(string source)  
  22.   
  23. {  
  24.   
  25.     return FormsAuthentication.HashPasswordForStoringInConfigFile(source, "SHA1");  
  26.   
  27. }  
  28.   
  29. /// <summary>  
  30.   
  31. /// MD5加密字符串  
  32.   
  33. /// </summary>  
  34.   
  35. /// <param name="source">源字符串</param>  
  36.   
  37. /// <returns>加密后的字符串</returns>  
  38.   
  39. public string MD5(string source)  
  40.   
  41. {  
  42.   
  43.     return FormsAuthentication.HashPasswordForStoringInConfigFile(source, "MD5");;  
  44.   
  45. }  
  46.   
  47. 方法二(可逆加密解密):  
  48.   
  49. using System.Security.Cryptography;  
  50.   
  51.    
  52.   
  53. ...  
  54.   
  55.    
  56.   
  57. public string Encode(string data)  
  58.   
  59. {  
  60.   
  61.     byte[] byKey = System.Text.ASCIIEncoding.ASCII.GetBytes(KEY_64);  
  62.   
  63.     byte[] byIV = System.Text.ASCIIEncoding.ASCII.GetBytes(IV_64);  
  64.   
  65.    
  66.   
  67.     DESCryptoServiceProvider cryptoProvider = new DESCryptoServiceProvider();  
  68.   
  69.     int i = cryptoProvider.KeySize;  
  70.   
  71.     MemoryStream ms = new MemoryStream();  
  72.   
  73.     CryptoStream cst = new CryptoStream(ms, cryptoProvider.CreateEncryptor(byKey, byIV), CryptoStreamMode.Write);  
  74.   
  75.    
  76.   
  77.     StreamWriter sw = new StreamWriter(cst);  
  78.   
  79.     sw.Write(data);  
  80.   
  81.     sw.Flush();  
  82.   
  83.     cst.FlushFinalBlock();  
  84.   
  85.     sw.Flush();  
  86.   
  87.     return Convert.ToBase64String(ms.GetBuffer(), 0, (int)ms.Length);  
  88.   
  89.    
  90.   
  91. }  
  92.   
  93.    
  94.   
  95. public string Decode(string data)  
  96.   
  97. {  
  98.   
  99.     byte[] byKey = System.Text.ASCIIEncoding.ASCII.GetBytes(KEY_64);  
  100.   
  101.     byte[] byIV = System.Text.ASCIIEncoding.ASCII.GetBytes(IV_64);  
  102.   
  103.    
  104.   
  105.     byte[] byEnc;  
  106.   
  107.     try  
  108.   
  109.     {  
  110.   
  111.         byEnc = Convert.FromBase64String(data);  
  112.   
  113.     }  
  114.   
  115.     catch  
  116.   
  117.     {  
  118.   
  119.         return null;  
  120.   
  121.     }  
  122.   
  123.    
  124.   
  125.     DESCryptoServiceProvider cryptoProvider = new DESCryptoServiceProvider();  
  126.   
  127.     MemoryStream ms = new MemoryStream(byEnc);  
  128.   
  129.     CryptoStream cst = new CryptoStream(ms, cryptoProvider.CreateDecryptor(byKey, byIV), CryptoStreamMode.Read);  
  130.   
  131.     StreamReader sr = new StreamReader(cst);  
  132.   
  133.     return sr.ReadToEnd();  
  134.   
  135. }  
  136.   
  137. 方法三(MD5不可逆):  
  138.   
  139. using System.Security.Cryptography;  
  140.   
  141.    
  142.   
  143. ...  
  144.   
  145.    
  146.   
  147. //MD5不可逆加密  
  148.   
  149.    
  150.   
  151. //32位加密  
  152.   
  153.    
  154.   
  155. public string GetMD5_32(string s, string _input_charset)  
  156.   
  157. {  
  158.   
  159.     MD5 md5 = new MD5CryptoServiceProvider();  
  160.   
  161.     byte[] t = md5.ComputeHash(Encoding.GetEncoding(_input_charset).GetBytes(s));  
  162.   
  163.     StringBuilder sb = new StringBuilder(32);  
  164.   
  165.     for (int i = 0; i < t.Length; i++)  
  166.   
  167.     {  
  168.   
  169.         sb.Append(t[i].ToString("x").PadLeft(2, '0'));  
  170.   
  171.     }  
  172.   
  173.     return sb.ToString();  
  174.   
  175. }  
  176.   
  177.    
  178.   
  179. //16位加密  
  180.   
  181. public static string GetMd5_16(string ConvertString)  
  182.   
  183. {  
  184.   
  185.     MD5CryptoServiceProvider md5 = new MD5CryptoServiceProvider();  
  186.   
  187.     string t2 = BitConverter.ToString(md5.ComputeHash(UTF8Encoding.Default.GetBytes(ConvertString)), 4, 8);  
  188.   
  189.     t2 = t2.Replace("-""");  
  190.   
  191.     return t2;  
  192.   
  193. }  
  194.   
  195. 方法四(对称加密):  
  196.   
  197. using System.IO;  
  198.   
  199. using System.Security.Cryptography;  
  200.   
  201.    
  202.   
  203. ...  
  204.   
  205.    
  206.   
  207. private SymmetricAlgorithm mobjCryptoService;  
  208.   
  209. private string Key;  
  210.   
  211. /// <summary>     
  212.   
  213. /// 对称加密类的构造函数     
  214.   
  215. /// </summary>     
  216.   
  217. public SymmetricMethod()  
  218.   
  219. {  
  220.   
  221.     mobjCryptoService = new RijndaelManaged();  
  222.   
  223.     Key = "Guz(%&hj7x89H$yuBI0456FtmaT5&fvHUFCy76*h%(HilJ$lhj!y6&(*jkP87jH7";  
  224.   
  225. }  
  226.   
  227. /// <summary>     
  228.   
  229. /// 获得密钥     
  230.   
  231. /// </summary>     
  232.   
  233. /// <returns>密钥</returns>     
  234.   
  235. private byte[] GetLegalKey()  
  236.   
  237. {  
  238.   
  239.     string sTemp = Key;  
  240.   
  241.     mobjCryptoService.GenerateKey();  
  242.   
  243.     byte[] bytTemp = mobjCryptoService.Key;  
  244.   
  245.     int KeyLength = bytTemp.Length;  
  246.   
  247.     if (sTemp.Length > KeyLength)  
  248.   
  249.         sTemp = sTemp.Substring(0, KeyLength);  
  250.   
  251.     else if (sTemp.Length < KeyLength)  
  252.   
  253.         sTemp = sTemp.PadRight(KeyLength, ' ');  
  254.   
  255.     return ASCIIEncoding.ASCII.GetBytes(sTemp);  
  256.   
  257. }  
  258.   
  259. /// <summary>     
  260.   
  261. /// 获得初始向量IV     
  262.   
  263. /// </summary>     
  264.   
  265. /// <returns>初试向量IV</returns>     
  266.   
  267. private byte[] GetLegalIV()  
  268.   
  269. {  
  270.   
  271.     string sTemp = "E4ghj*Ghg7!rNIfb&95GUY86GfghUb#er57HBh(u%g6HJ($jhWk7&!hg4ui%$hjk";  
  272.   
  273.     mobjCryptoService.GenerateIV();  
  274.   
  275.     byte[] bytTemp = mobjCryptoService.IV;  
  276.   
  277.     int IVLength = bytTemp.Length;  
  278.   
  279.     if (sTemp.Length > IVLength)  
  280.   
  281.         sTemp = sTemp.Substring(0, IVLength);  
  282.   
  283.     else if (sTemp.Length < IVLength)  
  284.   
  285.         sTemp = sTemp.PadRight(IVLength, ' ');  
  286.   
  287.     return ASCIIEncoding.ASCII.GetBytes(sTemp);  
  288.   
  289. }  
  290.   
  291. /// <summary>     
  292.   
  293. /// 加密方法     
  294.   
  295. /// </summary>     
  296.   
  297. /// <param name="Source">待加密的串</param>     
  298.   
  299. /// <returns>经过加密的串</returns>     
  300.   
  301. public string Encrypto(string Source)  
  302.   
  303. {  
  304.   
  305.     byte[] bytIn = UTF8Encoding.UTF8.GetBytes(Source);  
  306.   
  307.     MemoryStream ms = new MemoryStream();  
  308.   
  309.     mobjCryptoService.Key = GetLegalKey();  
  310.   
  311.     mobjCryptoService.IV = GetLegalIV();  
  312.   
  313.     ICryptoTransform encrypto = mobjCryptoService.CreateEncryptor();  
  314.   
  315.     CryptoStream cs = new CryptoStream(ms, encrypto, CryptoStreamMode.Write);  
  316.   
  317.     cs.Write(bytIn, 0, bytIn.Length);  
  318.   
  319.     cs.FlushFinalBlock();  
  320.   
  321.     ms.Close();  
  322.   
  323.     byte[] bytOut = ms.ToArray();  
  324.   
  325.     return Convert.ToBase64String(bytOut);  
  326.   
  327. }  
  328.   
  329. /// <summary>     
  330.   
  331. /// 解密方法     
  332.   
  333. /// </summary>     
  334.   
  335. /// <param name="Source">待解密的串</param>     
  336.   
  337. /// <returns>经过解密的串</returns>     
  338.   
  339. public string Decrypto(string Source)  
  340.   
  341. {  
  342.   
  343.     byte[] bytIn = Convert.FromBase64String(Source);  
  344.   
  345.     MemoryStream ms = new MemoryStream(bytIn, 0, bytIn.Length);  
  346.   
  347.     mobjCryptoService.Key = GetLegalKey();  
  348.   
  349.     mobjCryptoService.IV = GetLegalIV();  
  350.   
  351.     ICryptoTransform encrypto = mobjCryptoService.CreateDecryptor();  
  352.   
  353.     CryptoStream cs = new CryptoStream(ms, encrypto, CryptoStreamMode.Read);  
  354.   
  355.     StreamReader sr = new StreamReader(cs);  
  356.   
  357.     return sr.ReadToEnd();  
  358.   
  359. }  
  360.   
  361. 方法五:  
  362.   
  363. using System.IO;  
  364.   
  365. using System.Security.Cryptography;  
  366.   
  367. using System.Text;  
  368.   
  369.    
  370.   
  371. ...  
  372.   
  373.    
  374.   
  375. //默认密钥向量  
  376.   
  377. private static byte[] Keys = { 0x12, 0x34, 0x56, 0x78, 0x90, 0xAB, 0xCD, 0xEF };  
  378.   
  379. /**//**//**//// <summary>  
  380.   
  381. /// DES加密字符串  
  382.   
  383. /// </summary>  
  384.   
  385. /// <param name="encryptString">待加密的字符串</param>  
  386.   
  387. /// <param name="encryptKey">加密密钥,要求为8位</param>  
  388.   
  389. /// <returns>加密成功返回加密后的字符串,失败返回源串</returns>  
  390.   
  391. public static string EncryptDES(string encryptString, string encryptKey)  
  392.   
  393. {  
  394.   
  395.     try  
  396.   
  397.     {  
  398.   
  399.         byte[] rgbKey = Encoding.UTF8.GetBytes(encryptKey.Substring(0, 8));  
  400.   
  401.         byte[] rgbIV = Keys;  
  402.   
  403.         byte[] inputByteArray = Encoding.UTF8.GetBytes(encryptString);  
  404.   
  405.         DESCryptoServiceProvider dCSP = new DESCryptoServiceProvider();  
  406.   
  407.         MemoryStream mStream = new MemoryStream();  
  408.   
  409.         CryptoStream cStream = new CryptoStream(mStream, dCSP.CreateEncryptor(rgbKey, rgbIV), CryptoStreamMode.Write);  
  410.   
  411.         cStream.Write(inputByteArray, 0, inputByteArray.Length);  
  412.   
  413.         cStream.FlushFinalBlock();  
  414.   
  415.         return Convert.ToBase64String(mStream.ToArray());  
  416.   
  417.     }  
  418.   
  419.     catch  
  420.   
  421.     {  
  422.   
  423.         return encryptString;  
  424.   
  425.     }  
  426.   
  427. }  
  428.   
  429.    
  430.   
  431. /**//**//**//// <summary>  
  432.   
  433. /// DES解密字符串  
  434.   
  435. /// </summary>  
  436.   
  437. /// <param name="decryptString">待解密的字符串</param>  
  438.   
  439. /// <param name="decryptKey">解密密钥,要求为8位,和加密密钥相同</param>  
  440.   
  441. /// <returns>解密成功返回解密后的字符串,失败返源串</returns>  
  442.   
  443. public static string DecryptDES(string decryptString, string decryptKey)  
  444.   
  445. {  
  446.   
  447.     try  
  448.   
  449.     {  
  450.   
  451.         byte[] rgbKey = Encoding.UTF8.GetBytes(decryptKey);  
  452.   
  453.         byte[] rgbIV = Keys;  
  454.   
  455.         byte[] inputByteArray = Convert.FromBase64String(decryptString);  
  456.   
  457.         DESCryptoServiceProvider DCSP = new DESCryptoServiceProvider();  
  458.   
  459.         MemoryStream mStream = new MemoryStream();  
  460.   
  461.         CryptoStream cStream = new CryptoStream(mStream, DCSP.CreateDecryptor(rgbKey, rgbIV), CryptoStreamMode.Write);  
  462.   
  463.         cStream.Write(inputByteArray, 0, inputByteArray.Length);  
  464.   
  465.         cStream.FlushFinalBlock();  
  466.   
  467.         return Encoding.UTF8.GetString(mStream.ToArray());  
  468.   
  469.     }  
  470.   
  471.     catch  
  472.   
  473.     {  
  474.   
  475.         return decryptString;  
  476.   
  477.     }  
  478.   
  479. }   
  480.   
  481. 方法六(文件加密):  
  482.   
  483. using System.IO;  
  484.   
  485. using System.Security.Cryptography;  
  486.   
  487. using System.Text;  
  488.   
  489.    
  490.   
  491. ...  
  492.   
  493.    
  494.   
  495. //加密文件  
  496.   
  497. private static void EncryptData(String inName, String outName, byte[] desKey, byte[] desIV)  
  498.   
  499. {  
  500.   
  501.     //Create the file streams to handle the input and output files.  
  502.   
  503.     FileStream fin = new FileStream(inName, FileMode.Open, FileAccess.Read);  
  504.   
  505.     FileStream fout = new FileStream(outName, FileMode.OpenOrCreate, FileAccess.Write);  
  506.   
  507.     fout.SetLength(0);  
  508.   
  509.    
  510.   
  511.     //Create variables to help with read and write.  
  512.   
  513.     byte[] bin = new byte[100]; //This is intermediate storage for the encryption.  
  514.   
  515.     long rdlen = 0;              //This is the total number of bytes written.  
  516.   
  517.     long totlen = fin.Length;    //This is the total length of the input file.  
  518.   
  519.     int len;                     //This is the number of bytes to be written at a time.  
  520.   
  521.    
  522.   
  523.     DES des = new DESCryptoServiceProvider();  
  524.   
  525.     CryptoStream encStream = new CryptoStream(fout, des.CreateEncryptor(desKey, desIV), CryptoStreamMode.Write);  
  526.   
  527.    
  528.   
  529.     //Read from the input file, then encrypt and write to the output file.  
  530.   
  531.     while (rdlen < totlen)  
  532.   
  533.     {  
  534.   
  535.         len = fin.Read(bin, 0, 100);  
  536.   
  537.         encStream.Write(bin, 0, len);  
  538.   
  539.         rdlen = rdlen + len;  
  540.   
  541.     }  
  542.   
  543.    
  544.   
  545.     encStream.Close();  
  546.   
  547.     fout.Close();  
  548.   
  549.     fin.Close();  
  550.   
  551. }  
  552.   
  553.    
  554.   
  555. //解密文件  
  556.   
  557. private static void DecryptData(String inName, String outName, byte[] desKey, byte[] desIV)  
  558.   
  559. {  
  560.   
  561.     //Create the file streams to handle the input and output files.  
  562.   
  563.     FileStream fin = new FileStream(inName, FileMode.Open, FileAccess.Read);  
  564.   
  565.     FileStream fout = new FileStream(outName, FileMode.OpenOrCreate, FileAccess.Write);  
  566.   
  567.     fout.SetLength(0);  
  568.   
  569.    
  570.   
  571.     //Create variables to help with read and write.  
  572.   
  573.     byte[] bin = new byte[100]; //This is intermediate storage for the encryption.  
  574.   
  575.     long rdlen = 0;              //This is the total number of bytes written.  
  576.   
  577.     long totlen = fin.Length;    //This is the total length of the input file.  
  578.   
  579.     int len;                     //This is the number of bytes to be written at a time.  
  580.   
  581.    
  582.   
  583.     DES des = new DESCryptoServiceProvider();  
  584.   
  585.     CryptoStream encStream = new CryptoStream(fout, des.CreateDecryptor(desKey, desIV), CryptoStreamMode.Write);  
  586.   
  587.    
  588.   
  589.     //Read from the input file, then encrypt and write to the output file.  
  590.   
  591.     while (rdlen < totlen)  
  592.   
  593.     {  
  594.   
  595.         len = fin.Read(bin, 0, 100);  
  596.   
  597.         encStream.Write(bin, 0, len);  
  598.   
  599.         rdlen = rdlen + len;  
  600.   
  601.     }  
  602.   
  603.    
  604.   
  605.     encStream.Close();  
  606.   
  607.     fout.Close();  
  608.   
  609.     fin.Close();  
  610.   
  611. }  
  612.   
  613. 分享到:   
  614.   
  615. ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------  
  616.   
  617. C#   
  618.   
  619. -----------------------------------------------   
  620.   
  621. //名称空间     
  622.   
  623. using  System;     
  624.   
  625. using  System.Security.Cryptography;     
  626.   
  627. using  System.IO;     
  628.   
  629. using  System.Text;     
  630.   
  631.   
  632.   
  633. //方法     
  634.   
  635. //加密方法     
  636.   
  637. public    string  Encrypt(string  pToEncrypt,  string  sKey)     
  638.   
  639. {     
  640.   
  641.            DESCryptoServiceProvider  des  =  new  DESCryptoServiceProvider();     
  642.   
  643.            //把字符串放到byte数组中     
  644.   
  645.                  //原来使用的UTF8编码,我改成Unicode编码了,不行     
  646.   
  647.            byte[]  inputByteArray  =  Encoding.Default.GetBytes(pToEncrypt);     
  648.   
  649.            //byte[]  inputByteArray=Encoding.Unicode.GetBytes(pToEncrypt);     
  650.   
  651.   
  652.   
  653.            //建立加密对象的密钥和偏移量     
  654.   
  655.            //原文使用ASCIIEncoding.ASCII方法的GetBytes方法     
  656.   
  657.            //使得输入密码必须输入英文文本     
  658.   
  659.            des.Key  =  ASCIIEncoding.ASCII.GetBytes(sKey);     
  660.   
  661.            des.IV  =  ASCIIEncoding.ASCII.GetBytes(sKey);     
  662.   
  663.            MemoryStream  ms  =  new  MemoryStream();     
  664.   
  665.            CryptoStream  cs  =  new  CryptoStream(ms,  des.CreateEncryptor(),CryptoStreamMode.Write);     
  666.   
  667.            //Write  the  byte  array  into  the  crypto  stream     
  668.   
  669.            //(It  will  end  up  in  the  memory  stream)     
  670.   
  671.            cs.Write(inputByteArray,  0,  inputByteArray.Length);     
  672.   
  673.            cs.FlushFinalBlock();     
  674.   
  675.            //Get  the  data  back  from  the  memory  stream,  and  into  a  string     
  676.   
  677.            StringBuilder  ret  =  new  StringBuilder();     
  678.   
  679.            foreach(byte  b  in  ms.ToArray())     
  680.   
  681.                        {     
  682.   
  683.                        //Format  as  hex     
  684.   
  685.                        ret.AppendFormat("{0:X2}",  b);     
  686.   
  687.                        }     
  688.   
  689.            ret.ToString();     
  690.   
  691.            return  ret.ToString();     
  692.   
  693. }     
  694.   
  695.   
  696.   
  697. //解密方法     
  698.   
  699. public    string  Decrypt(string  pToDecrypt,  string  sKey)     
  700.   
  701. {     
  702.   
  703.            DESCryptoServiceProvider  des  =  new  DESCryptoServiceProvider();     
  704.   
  705.   
  706.   
  707.            //Put  the  input  string  into  the  byte  array     
  708.   
  709.            byte[]  inputByteArray  =  new  byte[pToDecrypt.Length  /  2];     
  710.   
  711.            for(int  x  =  0;  x  <  pToDecrypt.Length  /  2;  x++)     
  712.   
  713.            {     
  714.   
  715.                      int  i  =  (Convert.ToInt32(pToDecrypt.Substring(x  *  2,  2),  16));     
  716.   
  717.                inputByteArray[x]  =  (byte)i;     
  718.   
  719.            }     
  720.   
  721.   
  722.   
  723.            //建立加密对象的密钥和偏移量,此值重要,不能修改     
  724.   
  725.            des.Key  =  ASCIIEncoding.ASCII.GetBytes(sKey);     
  726.   
  727.            des.IV  =  ASCIIEncoding.ASCII.GetBytes(sKey);     
  728.   
  729.            MemoryStream  ms  =  new  MemoryStream();     
  730.   
  731.            CryptoStream  cs  =  new  CryptoStream(ms,  des.CreateDecryptor(),CryptoStreamMode.Write);     
  732.   
  733.            //Flush  the  data  through  the  crypto  stream  into  the  memory  stream     
  734.   
  735.            cs.Write(inputByteArray,  0,  inputByteArray.Length);     
  736.   
  737.            cs.FlushFinalBlock();     
  738.   
  739.   
  740.   
  741.            //Get  the  decrypted  data  back  from  the  memory  stream     
  742.   
  743.            //建立StringBuild对象,CreateDecrypt使用的是流对象,必须把解密后的文本变成流对象     
  744.   
  745.            StringBuilder  ret  =  new  StringBuilder();     
  746.   
  747.                 
  748.   
  749.            return  System.Text.Encoding.Default.GetString(ms.ToArray());     
  750.   
  751. }     
  752.   
  753. -------------------------------------------------------   
  754.   
  755. vb.Net :   
  756.   
  757. -------------------------------------------------------   
  758.   
  759. Imports System.Web.Security   
  760.   
  761. Imports System.Security   
  762.   
  763. Imports System.Security.Cryptography   
  764.   
  765. Imports System.Text   
  766.   
  767.   
  768.   
  769. Public Shared Function Encrypt(ByVal pToEncrypt As String, ByVal sKey As String) As String   
  770.   
  771.      Dim des As New DESCryptoServiceProvider()   
  772.   
  773.      Dim inputByteArray() As Byte   
  774.   
  775.      inputByteArray = Encoding.Default.GetBytes(pToEncrypt)   
  776.   
  777.      '建立加密对象的密钥和偏移量   
  778.   
  779.      '原文使用ASCIIEncoding.ASCII方法的GetBytes方法   
  780.   
  781.      '使得输入密码必须输入英文文本   
  782.   
  783.      des.Key = ASCIIEncoding.ASCII.GetBytes(sKey)   
  784.   
  785.      des.IV = ASCIIEncoding.ASCII.GetBytes(sKey)   
  786.   
  787.      '写二进制数组到加密流   
  788.   
  789.      '(把内存流中的内容全部写入)   
  790.   
  791.      Dim ms As New System.IO.MemoryStream()   
  792.   
  793.      Dim cs As New CryptoStream(ms, des.CreateEncryptor, CryptoStreamMode.Write)   
  794.   
  795.      '写二进制数组到加密流   
  796.   
  797.      '(把内存流中的内容全部写入)   
  798.   
  799.      cs.Write(inputByteArray, 0, inputByteArray.Length)   
  800.   
  801.      cs.FlushFinalBlock()   
  802.   
  803.   
  804.   
  805.      '建立输出字符串        
  806.   
  807.      Dim ret As New StringBuilder()   
  808.   
  809.      Dim b As Byte   
  810.   
  811.      For Each b In ms.ToArray()   
  812.   
  813.          ret.AppendFormat("{0:X2}", b)   
  814.   
  815.      Next   
  816.   
  817.   
  818.   
  819.      Return ret.ToString()   
  820.   
  821. End Function   
  822.   
  823.   
  824.   
  825.         '解密方法   
  826.   
  827. Public Shared Function Decrypt(ByVal pToDecrypt As String, ByVal sKey As String) As String   
  828.   
  829.      Dim des As New DESCryptoServiceProvider()   
  830.   
  831.      '把字符串放入byte数组   
  832.   
  833.      Dim len As Integer   
  834.   
  835.      len = pToDecrypt.Length / 2 - 1   
  836.   
  837.      Dim inputByteArray(len) As Byte   
  838.   
  839.      Dim x, i As Integer   
  840.   
  841.      For x = 0 To len   
  842.   
  843.          i = Convert.ToInt32(pToDecrypt.Substring(x * 2, 2), 16)   
  844.   
  845.          inputByteArray(x) = CType(i, Byte)   
  846.   
  847.      Next   
  848.   
  849.      '建立加密对象的密钥和偏移量,此值重要,不能修改   
  850.   
  851.      des.Key = ASCIIEncoding.ASCII.GetBytes(sKey)   
  852.   
  853.      des.IV = ASCIIEncoding.ASCII.GetBytes(sKey)   
  854.   
  855.      Dim ms As New System.IO.MemoryStream()   
  856.   
  857.      Dim cs As New CryptoStream(ms, des.CreateDecryptor, CryptoStreamMode.Write)   
  858.   
  859.      cs.Write(inputByteArray, 0, inputByteArray.Length)   
  860.   
  861.      cs.FlushFinalBlock()   
  862.   
  863.      Return Encoding.Default.GetString(ms.ToArray)   
  864.   
  865.   
  866.   
  867. End Function   
  868.   
  869. ------------------------------------------------   
  870.   
  871. 备注:   
  872.   
  873. 1. sKey输入密码的时候,必须使用英文字符,区分大小写,且字符数量是8个,不能多也不能少,否则出错。   
  874.   
  875. 2. 本人asp.net1.1,vs.net2003,windows2003 server环境下C#和vb.net分别调试成功!  
  876.   
  877.   
  878.   
  879. 第二種:  
  880.   
  881. using System;  
  882.   
  883. using System.IO;  
  884.   
  885. using System.Security.Cryptography;  
  886.   
  887. using System.Text;  
  888.   
  889. namespace webrptdata  
  890.   
  891. {  
  892.   
  893.  /// <summary>  
  894.   
  895.  /// 对称加密算法类  
  896.   
  897.  /// </summary>  
  898.   
  899.  public class SymmetricMethod  
  900.   
  901.  {  
  902.   
  903.     
  904.   
  905.   private SymmetricAlgorithm mobjCryptoService;  
  906.   
  907.   private string Key;  
  908.   
  909.   /// <summary>  
  910.   
  911.   /// 对称加密类的构造函数  
  912.   
  913.   /// </summary>  
  914.   
  915.   public SymmetricMethod()  
  916.   
  917.   {  
  918.   
  919.    mobjCryptoService = new RijndaelManaged();  
  920.   
  921.    Key = "Guz(%&hj7x89H$yuBI0456FtmaT5&fvHUFCy76*h%(HilJ$lhj!y6&(*jkP87jH7";  
  922.   
  923.   }  
  924.   
  925.   /// <summary>  
  926.   
  927.   /// 获得密钥  
  928.   
  929.   /// </summary>  
  930.   
  931.   /// <returns>密钥</returns>  
  932.   
  933.   private byte[] GetLegalKey()  
  934.   
  935.   {  
  936.   
  937.    string sTemp = Key;  
  938.   
  939.    mobjCryptoService.GenerateKey();  
  940.   
  941.    byte[] bytTemp = mobjCryptoService.Key;  
  942.   
  943.    int KeyLength = bytTemp.Length;  
  944.   
  945.    if (sTemp.Length > KeyLength)  
  946.   
  947.     sTemp = sTemp.Substring(0, KeyLength);  
  948.   
  949.    else if (sTemp.Length < KeyLength)  
  950.   
  951.     sTemp = sTemp.PadRight(KeyLength, ' ');  
  952.   
  953.    return ASCIIEncoding.ASCII.GetBytes(sTemp);  
  954.   
  955.   }  
  956.   
  957.   /// <summary>  
  958.   
  959.   /// 获得初始向量IV  
  960.   
  961.   /// </summary>  
  962.   
  963.   /// <returns>初试向量IV</returns>  
  964.   
  965.   private byte[] GetLegalIV()  
  966.   
  967.   {  
  968.   
  969.    string sTemp = "E4ghj*Ghg7!rNIfb&95GUY86GfghUb#er57HBh(u%g6HJ($jhWk7&!hg4ui%$hjk";  
  970.   
  971.    mobjCryptoService.GenerateIV();  
  972.   
  973.    byte[] bytTemp = mobjCryptoService.IV;  
  974.   
  975.    int IVLength = bytTemp.Length;  
  976.   
  977.    if (sTemp.Length > IVLength)  
  978.   
  979.     sTemp = sTemp.Substring(0, IVLength);  
  980.   
  981.    else if (sTemp.Length < IVLength)  
  982.   
  983.     sTemp = sTemp.PadRight(IVLength, ' ');  
  984.   
  985.    return ASCIIEncoding.ASCII.GetBytes(sTemp);  
  986.   
  987.   }  
  988.   
  989.   /// <summary>  
  990.   
  991.   /// 加密方法  
  992.   
  993.   /// </summary>  
  994.   
  995.   /// <param name="Source">待加密的串</param>  
  996.   
  997.   /// <returns>经过加密的串</returns>  
  998.   
  999.   public string Encrypto(string Source)  
  1000.   
  1001.   {  
  1002.   
  1003.    byte[] bytIn = UTF8Encoding.UTF8.GetBytes(Source);  
  1004.   
  1005.    MemoryStream ms = new MemoryStream();  
  1006.   
  1007.    mobjCryptoService.Key = GetLegalKey();  
  1008.   
  1009.    mobjCryptoService.IV = GetLegalIV();  
  1010.   
  1011.    ICryptoTransform encrypto = mobjCryptoService.CreateEncryptor();  
  1012.   
  1013.    CryptoStream cs = new CryptoStream(ms, encrypto, CryptoStreamMode.Write);  
  1014.   
  1015.    cs.Write(bytIn, 0, bytIn.Length);  
  1016.   
  1017.    cs.FlushFinalBlock();  
  1018.   
  1019.    ms.Close();  
  1020.   
  1021.    byte[] bytOut = ms.ToArray();  
  1022.   
  1023.    return Convert.ToBase64String(bytOut);  
  1024.   
  1025.   }  
  1026.   
  1027.   /// <summary>  
  1028.   
  1029.   /// 解密方法  
  1030.   
  1031.   /// </summary>  
  1032.   
  1033.   /// <param name="Source">待解密的串</param>  
  1034.   
  1035.   /// <returns>经过解密的串</returns>  
  1036.   
  1037.   public string Decrypto(string Source)  
  1038.   
  1039.   {  
  1040.   
  1041.    byte[] bytIn = Convert.FromBase64String(Source);  
  1042.   
  1043.    MemoryStream ms = new MemoryStream(bytIn, 0, bytIn.Length);  
  1044.   
  1045.    mobjCryptoService.Key = GetLegalKey();  
  1046.   
  1047.    mobjCryptoService.IV = GetLegalIV();  
  1048.   
  1049.    ICryptoTransform encrypto = mobjCryptoService.CreateDecryptor();  
  1050.   
  1051.    CryptoStream cs = new CryptoStream(ms, encrypto, CryptoStreamMode.Read);  
  1052.   
  1053.    StreamReader sr = new StreamReader(cs);  
  1054.   
  1055.    return sr.ReadToEnd();  
  1056.   
  1057.   }  
  1058.   
  1059.  }  
  1060.   
  1061. }  

猜你喜欢

转载自blog.csdn.net/bruce135lee/article/details/80700586