/IMChat/RSA/DESHelper.cs

https://github.com/chenshunliang/MyTestHub · C# · 75 lines · 59 code · 4 blank · 12 comment · 0 complexity · 09d463e04ef24d68d1532679dab98646 MD5 · raw file

  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Security.Cryptography;
  5. using System.Text;
  6. using System.Threading.Tasks;
  7. namespace RSA
  8. {
  9. public static class DESHelper
  10. {
  11. public static void CreateKeyAndIV(out string key, out string IV)
  12. {
  13. DESCryptoServiceProvider des = new DESCryptoServiceProvider();
  14. byte[] data = new byte[0x10];
  15. new RNGCryptoServiceProvider().GetBytes(data);
  16. string longkey = Convert.ToBase64String(data);
  17. key = longkey.Substring(0, 8);
  18. IV = longkey.Substring(0, 8);
  19. }
  20. /// <summary>
  21. /// 进行DES加密。
  22. /// </summary>
  23. /// <param name="pToEncrypt">要加密的字符串。</param>
  24. /// <param name="sKey">密钥,且必须为8位。</param>
  25. /// <returns>以Base64格式返回的加密字符串。</returns>
  26. public static string Encrypt(string pToEncrypt, string sKey)
  27. {
  28. using (DESCryptoServiceProvider des = new DESCryptoServiceProvider())
  29. {
  30. byte[] inputByteArray = Encoding.UTF8.GetBytes(pToEncrypt);
  31. des.Key = ASCIIEncoding.ASCII.GetBytes(sKey);
  32. des.IV = ASCIIEncoding.ASCII.GetBytes(sKey);
  33. System.IO.MemoryStream ms = new System.IO.MemoryStream();
  34. using (CryptoStream cs = new CryptoStream(ms, des.CreateEncryptor(), CryptoStreamMode.Write))
  35. {
  36. cs.Write(inputByteArray, 0, inputByteArray.Length);
  37. cs.FlushFinalBlock();
  38. cs.Close();
  39. }
  40. string str = Convert.ToBase64String(ms.ToArray());
  41. ms.Close();
  42. return str;
  43. }
  44. }
  45. /// <summary>
  46. /// 进行DES解密。
  47. /// </summary>
  48. /// <param name="pToDecrypt">要解密的以Base64</param>
  49. /// <param name="sKey">密钥,且必须为8位。</param>
  50. /// <returns>已解密的字符串。</returns>
  51. public static string Decrypt(string pToDecrypt, string sKey)
  52. {
  53. byte[] inputByteArray = Convert.FromBase64String(pToDecrypt);
  54. using (DESCryptoServiceProvider des = new DESCryptoServiceProvider())
  55. {
  56. des.Key = ASCIIEncoding.ASCII.GetBytes(sKey);
  57. des.IV = ASCIIEncoding.ASCII.GetBytes(sKey);
  58. System.IO.MemoryStream ms = new System.IO.MemoryStream();
  59. using (CryptoStream cs = new CryptoStream(ms, des.CreateDecryptor(), CryptoStreamMode.Write))
  60. {
  61. cs.Write(inputByteArray, 0, inputByteArray.Length);
  62. cs.FlushFinalBlock();
  63. cs.Close();
  64. }
  65. string str = Encoding.UTF8.GetString(ms.ToArray());
  66. ms.Close();
  67. return str;
  68. }
  69. }
  70. }
  71. }