EncryptedData.cs 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748
  1. using System;
  2. using System.IO;
  3. using System.Security.Cryptography;
  4. using System.Text;
  5. namespace Island.StandardLib.Storage.Encryption
  6. {
  7. public class EncryptedData<DataType> : IStorable where DataType : IStorable, new()
  8. {
  9. public byte[] Encrypted;
  10. public EncryptedData(EncrypterBase encrypter, DataType data, string key) => SetData(encrypter, data, key);
  11. public EncryptedData() => Encrypted = new byte[0];
  12. public DataStorage GetPlain(EncrypterBase encrypter, string key)
  13. {
  14. byte[] plain = encrypter.Decrypt(Encrypted, key);
  15. DataStorage ds = new DataStorage(plain);
  16. return ds;
  17. }
  18. public DataType GetData(EncrypterBase encrypter, string key)
  19. {
  20. byte[] plain = encrypter.Decrypt(Encrypted, key);
  21. DataStorage ds = new DataStorage(plain);
  22. return ds.Read<DataType>();
  23. }
  24. public void SetData(EncrypterBase encrypter, DataType data, string key)
  25. {
  26. byte[] plain = data.GetBytes();
  27. Encrypted = encrypter.Encrypt(plain, key);
  28. }
  29. public void ReadFromData(DataStorage data)
  30. {
  31. data.ReadUncheck(out int size);
  32. Encrypted = new byte[size];
  33. data.ReadInternal(Encrypted, size);
  34. }
  35. public void WriteToData(DataStorage data)
  36. {
  37. data.WriteUncheck(Encrypted.Length);
  38. data.WriteInternal(Encrypted);
  39. }
  40. }
  41. }