SerializationUtils.cs 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. namespace XGame.Framework.Serialization
  2. {
  3. public static class SerializationUtils
  4. {
  5. public static T Read<T>(string filePath) where T : class, ISerializable
  6. {
  7. try
  8. {
  9. var bytes = File.ReadAllBytes(filePath);
  10. if (bytes != null)
  11. {
  12. EncryptXor(ref bytes, 1023);
  13. var reader = new Reader(bytes);
  14. var result = Activator.CreateInstance<T>();
  15. result.Deserialize(reader);
  16. return result;
  17. }
  18. }
  19. catch (Exception ex)
  20. {
  21. Console.WriteLine(ex.Message);
  22. }
  23. return default;
  24. }
  25. /// <summary>
  26. /// 反序列化
  27. /// </summary>
  28. /// <typeparam name="T"></typeparam>
  29. /// <param name="bytes"></param>
  30. /// <param name="xorKey"></param>
  31. /// <returns></returns>
  32. public static T Read<T>(byte[] bytes, uint xorKey = 0) where T : class, ISerializable
  33. {
  34. try
  35. {
  36. if (bytes != null)
  37. {
  38. if (xorKey != 0)
  39. {
  40. EncryptXor(ref bytes, xorKey);
  41. }
  42. var reader = new Reader(bytes);
  43. var result = Activator.CreateInstance<T>();
  44. result.Deserialize(reader);
  45. return result;
  46. }
  47. }
  48. catch (Exception ex)
  49. {
  50. Console.WriteLine(ex.Message);
  51. }
  52. return default;
  53. }
  54. /// <summary>
  55. /// 异或加密
  56. /// </summary>
  57. /// <param name="bytes"></param>
  58. /// <param name="key">默认为 1023</param>
  59. public static void EncryptXor(ref byte[] bytes, uint key)
  60. {
  61. if (bytes == null)
  62. return;
  63. for (var i = 0; i < bytes.Length; i++) // 依次对字符串中各字符进行操作
  64. {
  65. var current = bytes[i];
  66. bytes[i] = (byte)(current ^ key); // 将密钥与字符异或
  67. }
  68. }
  69. }
  70. }