Encryption.cs 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253
  1. using System;
  2. using System.Collections.Generic;
  3. using System.IO;
  4. using System.Linq;
  5. using System.Security.Cryptography;
  6. using System.Text;
  7. namespace UAS_MES_NEW.PublicMethod
  8. {
  9. class Encryption
  10. {
  11. private static string encryptKey = "DBDB";
  12. public static string EncryptStr(string str)
  13. {
  14. DESCryptoServiceProvider descsp = new DESCryptoServiceProvider(); //实例化加/解密类对象
  15. byte[] key = Encoding.Unicode.GetBytes(encryptKey); //定义字节数组,用来存储密钥
  16. byte[] data = Encoding.Unicode.GetBytes(str);//定义字节数组,用来存储要加密的字符串
  17. MemoryStream MStream = new MemoryStream(); //实例化内存流对象
  18. //使用内存流实例化加密流对象
  19. CryptoStream CStream = new CryptoStream(MStream, descsp.CreateEncryptor(key, key), CryptoStreamMode.Write);
  20. CStream.Write(data, 0, data.Length); //向加密流中写入数据
  21. CStream.FlushFinalBlock(); //释放加密流
  22. return Convert.ToBase64String(MStream.ToArray());//返回加密后的字符串
  23. }
  24. public static string DecryptStr(string str)
  25. {
  26. DESCryptoServiceProvider descsp = new DESCryptoServiceProvider(); //实例化加/解密类对象
  27. byte[] key = Encoding.Unicode.GetBytes(encryptKey); //定义字节数组,用来存储密钥
  28. byte[] data = Convert.FromBase64String(str);//定义字节数组,用来存储要解密的字符串
  29. MemoryStream MStream = new MemoryStream(); //实例化内存流对象
  30. //使用内存流实例化解密流对象
  31. CryptoStream CStream = new CryptoStream(MStream, descsp.CreateDecryptor(key, key), CryptoStreamMode.Write);
  32. CStream.Write(data, 0, data.Length); //向解密流中写入数据
  33. CStream.FlushFinalBlock(); //释放解密流
  34. return Encoding.Unicode.GetString(MStream.ToArray()); //返回解密后的字符串
  35. }
  36. }
  37. }