private string _DESKey=""; 
public string DESKey  
  {
   set
   {
    _DESKey=value;
   }
  }
  public string DESEncrypt(string toEncrypt)
  {
   //定义DES加密服务提供类
   DESCryptoServiceProvider des=new DESCryptoServiceProvider();
   //加密字符串转换为byte数组
   byte[] inputByte=System.Text.ASCIIEncoding.UTF8.GetBytes(toEncrypt);
   //加密密匙转化为byte数组
   byte[] key = Encoding.ASCII.GetBytes(_DESKey); //DES密钥(必须8字节)
   des.Key=key;
   des.IV=key;
   //创建其支持存储区为内存的流
   MemoryStream ms=new MemoryStream();
   //定义将数据流链接到加密转换的流
   CryptoStream cs=new CryptoStream(ms,des.CreateEncryptor(),CryptoStreamMode.Write);
   cs.Write(inputByte, 0, inputByte.Length);
   cs.FlushFinalBlock();
   StringBuilder ret = new StringBuilder();
   foreach (byte b in ms.ToArray())
   {
    //向可变字符串追加转换成十六进制数字符串的加密后byte数组。
    ret.AppendFormat("{0:X2}", b);
   }
   return ret.ToString();

  }
  public string DESDecrypt(string toDecrypt)
  {
   //定义DES加密解密服务提供类
   DESCryptoServiceProvider des = new DESCryptoServiceProvider();
   //加密密匙转化为byte数组
   byte[] key = Encoding.ASCII.GetBytes(_DESKey);
   des.Key = key;
   des.IV = key;
   //将被解密的字符串每两个字符以十六进制解析为byte类型,组成byte数组
   int length = (toDecrypt.Length / 2);
   byte[] inputByte = new byte[length];
   for (int index = 0; index < length; index++)
   {
    string substring = toDecrypt.Substring(index * 2, 2);
    inputByte[index] = Convert.ToByte(substring, 16);
   }
   //创建其支持存储区为内存的流
   MemoryStream ms = new MemoryStream();
   //定义将数据流链接到加密转换的流
   CryptoStream cs = new CryptoStream(ms, des.CreateDecryptor(), CryptoStreamMode.Write);
   cs.Write(inputByte, 0, inputByte.Length);
   cs.FlushFinalBlock();

   return ASCIIEncoding.UTF8.GetString((ms.ToArray()));
  }

相关文章:

  • 2022-02-13
  • 2021-07-09
  • 2022-12-23
  • 2021-12-26
  • 2022-12-23
  • 2021-08-07
猜你喜欢
  • 2021-06-06
  • 2021-06-01
  • 2022-01-03
  • 2021-10-20
  • 2022-12-23
  • 2021-09-15
  • 2021-07-19
相关资源
相似解决方案