双向加密

来源:互联网 发布:淘宝和旺信是绑定的吗 编辑:程序博客网 时间:2024/04/29 19:32

(string strSource)方法用来对比比较重要的信息进行加密
Dencrypting(string source)方法将已加密的信息进行解密

Java代码  收藏代码
  1. using System.Security.Cryptography;  
  2. using System.IO;  
  3. using System.Text;  

 

Java代码  收藏代码
  1. public static string Encrypting(string strSource)  
  2.     {  
  3.         byte[] bytln = System.Text.Encoding.Default.GetBytes(strSource);  
  4.         byte[] iv = {102,16,93,156,78,4,218,32 };//定义偏移量  
  5.         byte[] key = {55,103,246,79,36,99,167,3 };//定义密钥  
  6.         //实例DES加密类  
  7.         DESCryptoServiceProvider mobjCryptoService = new DESCryptoServiceProvider();  
  8.         mobjCryptoService.Key = iv;  
  9.         mobjCryptoService.IV = key;  
  10.         ICryptoTransform encrypto = mobjCryptoService.CreateEncryptor();  
  11.         //实例MemoryStream流加密文件  
  12.         System.IO.MemoryStream ms = new System.IO.MemoryStream();  
  13.         CryptoStream cs = new CryptoStream(ms,encrypto ,CryptoStreamMode.Write );  
  14.         cs.Write(bytln ,0,bytln.Length );  
  15.         cs.FlushFinalBlock();  
  16.         return System.Convert.ToBase64String(ms.ToArray ());  
  17.           
  18.     }  
  19.   
  20.     public static string Dencrypting(string source)  
  21.     {  
  22.         try  
  23.         {  
  24.             //将解密字符串转成字节数组  
  25.             byte[] bytln = System.Convert.FromBase64String(source);  
  26.             byte[] iv = { 102169315678421832 };//定义偏移量  
  27.             byte[] key = { 551032467936991673 };//定义密钥          
  28.             DESCryptoServiceProvider mobjCryptoService = new DESCryptoServiceProvider();  
  29.             mobjCryptoService.Key = iv;  
  30.             mobjCryptoService.IV = key;          
  31.             //实例流进行解密  
  32.             System.IO.MemoryStream ms = new System.IO.MemoryStream(bytln ,0,bytln .Length );  
  33.             ICryptoTransform encrypto = mobjCryptoService.CreateDecryptor();  
  34.             CryptoStream cs = new CryptoStream(ms, encrypto, CryptoStreamMode.Read);  
  35.             StreamReader strd = new StreamReader(cs, Encoding.Default);  
  36.             return strd.ReadToEnd();  
  37.         }  
  38.         catch (Exception ex)  
  39.         {  
  40.             throw new Exception("在文件解密的时候出现错误"+ex.Message );  
  41.         }  
  42.     }