StringEncrypt.cs 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Text;
  5. namespace Ant.Common
  6. {
  7. public class StringEncrypt
  8. {
  9. //key为加密密匙,可定期任意修改
  10. private const string key = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789abcdefghijklmnopqrstuvwxyz";
  11. // EnCode为字符串加密函数,str为待加密的字符串,返回值为加密后的字符串
  12. /// <summary>
  13. /// 字符串加密
  14. /// </summary>
  15. /// <param name="str"></param>
  16. /// <returns></returns>
  17. public static string EnCode(string str)
  18. {
  19. if (string.IsNullOrEmpty(str))
  20. {
  21. return "";
  22. }
  23. byte[] buff = Encoding.Default.GetBytes(str);
  24. int j, k, m;
  25. int len = key.Length;
  26. StringBuilder sb = new StringBuilder();
  27. Random r = new Random();
  28. for (int i = 0; i < buff.Length; i++)
  29. {
  30. j = (byte)r.Next(6);
  31. buff[i] = (byte)((int)buff[i] ^ j);
  32. k = (int)buff[i] % len;
  33. m = (int)buff[i] / len;
  34. m = m * 8 + j;
  35. sb.Append(key.Substring(k, 1) + key.Substring(m, 1));
  36. }
  37. return sb.ToString();
  38. }
  39. // EnCode为字符串加密函数,str为待解密的字符串,返回值为解密后的字符串
  40. /// <summary>
  41. /// 字符串解密
  42. /// </summary>
  43. /// <param name="str"></param>
  44. /// <returns></returns>
  45. public static string DeCode(string str)
  46. {
  47. if (string.IsNullOrEmpty(str))
  48. {
  49. return "";
  50. }
  51. try
  52. {
  53. int j, k, m, n = 0;
  54. int len = key.Length;
  55. byte[] buff = new byte[str.Length / 2];
  56. for (int i = 0; i < str.Length; i += 2)
  57. {
  58. k = key.IndexOf(str[i]);
  59. m = key.IndexOf(str[i + 1]);
  60. j = m / 8;
  61. m = m - j * 8;
  62. buff[n] = (byte)(j * len + k);
  63. buff[n] = (byte)((int)buff[n] ^ m);
  64. n++;
  65. }
  66. return Encoding.Default.GetString(buff);
  67. }
  68. catch
  69. {
  70. return "";
  71. }
  72. }
  73. }
  74. }