CdkeyHelper.cs 2.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687
  1. using System;
  2. using System.Collections.Generic;
  3. using System.IO;
  4. using System.Security.Cryptography;
  5. using System.Text;
  6. namespace ConsoleTest
  7. {
  8. public static class CdkeyHelper
  9. {
  10. public const string DesKeyStr = "BLUE2013";
  11. #region DES加密
  12. /// <summary>
  13. /// DES加密
  14. /// </summary>
  15. /// <param name="pToEncrypt">需要加密的字符串</param>
  16. /// <returns>加密后的字符串</returns>
  17. public static string DESEncrypt(string pToEncrypt, string DesKeyStr)
  18. {
  19. try
  20. {
  21. DESCryptoServiceProvider des = new DESCryptoServiceProvider();
  22. byte[] inputByteArray = Encoding.Default.GetBytes(pToEncrypt);
  23. des.Key = ASCIIEncoding.ASCII.GetBytes(DesKeyStr);
  24. des.IV = ASCIIEncoding.ASCII.GetBytes(DesKeyStr);
  25. MemoryStream ms = new MemoryStream();
  26. CryptoStream cs = new CryptoStream(ms, des.CreateEncryptor(), CryptoStreamMode.Write);
  27. cs.Write(inputByteArray, 0, inputByteArray.Length);
  28. cs.FlushFinalBlock();
  29. StringBuilder ret = new StringBuilder();
  30. foreach (byte b in ms.ToArray())
  31. {
  32. ret.AppendFormat("{0:X2}", b);
  33. }
  34. ret.ToString();
  35. return ret.ToString();
  36. }
  37. catch
  38. {
  39. return "";
  40. }
  41. }
  42. #endregion
  43. #region DES解密
  44. /// <summary>
  45. /// DES解密
  46. /// </summary>
  47. /// <param name="pToDecrypt">加密后的字符串</param>
  48. /// <returns>解密后的字符串</returns>
  49. public static string DESDecrypt(string pToDecrypt, string DesKeyStr)
  50. {
  51. try
  52. {
  53. DESCryptoServiceProvider des = new DESCryptoServiceProvider();
  54. byte[] inputByteArray = new byte[pToDecrypt.Length / 2];
  55. for (int x = 0; x < pToDecrypt.Length / 2; x++)
  56. {
  57. int i = (Convert.ToInt32(pToDecrypt.Substring(x * 2, 2), 16));
  58. inputByteArray[x] = (byte)i;
  59. }
  60. des.Key = ASCIIEncoding.ASCII.GetBytes(DesKeyStr);
  61. des.IV = ASCIIEncoding.ASCII.GetBytes(DesKeyStr);
  62. MemoryStream ms = new MemoryStream();
  63. CryptoStream cs = new CryptoStream(ms, des.CreateDecryptor(), CryptoStreamMode.Write);
  64. cs.Write(inputByteArray, 0, inputByteArray.Length);
  65. cs.FlushFinalBlock();
  66. StringBuilder ret = new StringBuilder();
  67. return System.Text.Encoding.Default.GetString(ms.ToArray());
  68. }
  69. catch
  70. {
  71. return "";
  72. }
  73. }
  74. #endregion
  75. }
  76. }