MainShortcuts2 2.8.9__tar.gz → 2.9.1__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (57) hide show
  1. {mainshortcuts2-2.8.9 → mainshortcuts2-2.9.1}/PKG-INFO +13 -1
  2. {mainshortcuts2-2.8.9 → mainshortcuts2-2.9.1}/pyproject.toml +22 -1
  3. {mainshortcuts2-2.8.9 → mainshortcuts2-2.9.1}/src/MainShortcuts2/__main__.py +44 -27
  4. {mainshortcuts2-2.8.9 → mainshortcuts2-2.9.1}/src/MainShortcuts2/_module_info.py +1 -1
  5. {mainshortcuts2-2.8.9 → mainshortcuts2-2.9.1}/src/MainShortcuts2/api/base.py +18 -20
  6. {mainshortcuts2-2.8.9 → mainshortcuts2-2.9.1}/src/MainShortcuts2/core.py +5 -0
  7. {mainshortcuts2-2.8.9 → mainshortcuts2-2.9.1}/src/MainShortcuts2/ex/sqlite_ex.py +5 -3
  8. mainshortcuts2-2.9.1/src/MainShortcuts2/ms2dat1crypto.py +137 -0
  9. {mainshortcuts2-2.8.9 → mainshortcuts2-2.9.1}/README.md +0 -0
  10. {mainshortcuts2-2.8.9 → mainshortcuts2-2.9.1}/src/MainShortcuts2/__init__.py +0 -0
  11. {mainshortcuts2-2.8.9 → mainshortcuts2-2.9.1}/src/MainShortcuts2/_any2json_regs.py +0 -0
  12. {mainshortcuts2-2.8.9 → mainshortcuts2-2.9.1}/src/MainShortcuts2/_ms2app_regs.py +0 -0
  13. {mainshortcuts2-2.8.9 → mainshortcuts2-2.9.1}/src/MainShortcuts2/_ms2dat_auto.py +0 -0
  14. {mainshortcuts2-2.8.9 → mainshortcuts2-2.9.1}/src/MainShortcuts2/advanced.py +0 -0
  15. {mainshortcuts2-2.8.9 → mainshortcuts2-2.9.1}/src/MainShortcuts2/any2json.py +0 -0
  16. {mainshortcuts2-2.8.9 → mainshortcuts2-2.9.1}/src/MainShortcuts2/api/gigachat.py +0 -0
  17. {mainshortcuts2-2.8.9 → mainshortcuts2-2.9.1}/src/MainShortcuts2/api/github.py +0 -0
  18. {mainshortcuts2-2.8.9 → mainshortcuts2-2.9.1}/src/MainShortcuts2/api/russian_trusted_root_ca_pem.crt +0 -0
  19. {mainshortcuts2-2.8.9 → mainshortcuts2-2.9.1}/src/MainShortcuts2/api/russian_trusted_sub_ca_pem.crt +0 -0
  20. {mainshortcuts2-2.8.9 → mainshortcuts2-2.9.1}/src/MainShortcuts2/api/webdav.py +0 -0
  21. {mainshortcuts2-2.8.9 → mainshortcuts2-2.9.1}/src/MainShortcuts2/cfg.py +0 -0
  22. {mainshortcuts2-2.8.9 → mainshortcuts2-2.9.1}/src/MainShortcuts2/core_config.py +0 -0
  23. {mainshortcuts2-2.8.9 → mainshortcuts2-2.9.1}/src/MainShortcuts2/dict.py +0 -0
  24. {mainshortcuts2-2.8.9 → mainshortcuts2-2.9.1}/src/MainShortcuts2/dir.py +0 -0
  25. {mainshortcuts2-2.8.9 → mainshortcuts2-2.9.1}/src/MainShortcuts2/ex/__init__.py +0 -0
  26. {mainshortcuts2-2.8.9 → mainshortcuts2-2.9.1}/src/MainShortcuts2/ex/aiohttp_ex/web/__init__.py +0 -0
  27. {mainshortcuts2-2.8.9 → mainshortcuts2-2.9.1}/src/MainShortcuts2/ex/aiohttp_ex/web/__main__.py +0 -0
  28. {mainshortcuts2-2.8.9 → mainshortcuts2-2.9.1}/src/MainShortcuts2/ex/datetime_ex.py +0 -0
  29. {mainshortcuts2-2.8.9 → mainshortcuts2-2.9.1}/src/MainShortcuts2/ex/pathlib_ex.py +0 -0
  30. {mainshortcuts2-2.8.9 → mainshortcuts2-2.9.1}/src/MainShortcuts2/ex/pil_ex.py +0 -0
  31. {mainshortcuts2-2.8.9 → mainshortcuts2-2.9.1}/src/MainShortcuts2/ex/psutil_ex.py +0 -0
  32. {mainshortcuts2-2.8.9 → mainshortcuts2-2.9.1}/src/MainShortcuts2/ex/urlparse_ex.py +0 -0
  33. {mainshortcuts2-2.8.9 → mainshortcuts2-2.9.1}/src/MainShortcuts2/file.py +0 -0
  34. {mainshortcuts2-2.8.9 → mainshortcuts2-2.9.1}/src/MainShortcuts2/gui_scripts/__init__.py +0 -0
  35. {mainshortcuts2-2.8.9 → mainshortcuts2-2.9.1}/src/MainShortcuts2/gui_scripts/ms2_hash_gen.py +0 -0
  36. {mainshortcuts2-2.8.9 → mainshortcuts2-2.9.1}/src/MainShortcuts2/gui_scripts/utils.py +0 -0
  37. {mainshortcuts2-2.8.9 → mainshortcuts2-2.9.1}/src/MainShortcuts2/java_ext/__init__.py +0 -0
  38. {mainshortcuts2-2.8.9 → mainshortcuts2-2.9.1}/src/MainShortcuts2/java_ext/ms2ext.py +0 -0
  39. {mainshortcuts2-2.8.9 → mainshortcuts2-2.9.1}/src/MainShortcuts2/json.py +0 -0
  40. {mainshortcuts2-2.8.9 → mainshortcuts2-2.9.1}/src/MainShortcuts2/linux.py +0 -0
  41. {mainshortcuts2-2.8.9 → mainshortcuts2-2.9.1}/src/MainShortcuts2/list.py +0 -0
  42. {mainshortcuts2-2.8.9 → mainshortcuts2-2.9.1}/src/MainShortcuts2/ms2app.py +0 -0
  43. {mainshortcuts2-2.8.9 → mainshortcuts2-2.9.1}/src/MainShortcuts2/ms2dat1.py +0 -0
  44. {mainshortcuts2-2.8.9 → mainshortcuts2-2.9.1}/src/MainShortcuts2/ms2hash.py +0 -0
  45. {mainshortcuts2-2.8.9 → mainshortcuts2-2.9.1}/src/MainShortcuts2/path.py +0 -0
  46. {mainshortcuts2-2.8.9 → mainshortcuts2-2.9.1}/src/MainShortcuts2/proc.py +0 -0
  47. {mainshortcuts2-2.8.9 → mainshortcuts2-2.9.1}/src/MainShortcuts2/regex.py +0 -0
  48. {mainshortcuts2-2.8.9 → mainshortcuts2-2.9.1}/src/MainShortcuts2/special_chars.py +0 -0
  49. {mainshortcuts2-2.8.9 → mainshortcuts2-2.9.1}/src/MainShortcuts2/sql/_sql_base.py +0 -0
  50. {mainshortcuts2-2.8.9 → mainshortcuts2-2.9.1}/src/MainShortcuts2/sql/mysql.py +0 -0
  51. {mainshortcuts2-2.8.9 → mainshortcuts2-2.9.1}/src/MainShortcuts2/sql/postgresql.py +0 -0
  52. {mainshortcuts2-2.8.9 → mainshortcuts2-2.9.1}/src/MainShortcuts2/sql/sqlite.py +0 -0
  53. {mainshortcuts2-2.8.9 → mainshortcuts2-2.9.1}/src/MainShortcuts2/str.py +0 -0
  54. {mainshortcuts2-2.8.9 → mainshortcuts2-2.9.1}/src/MainShortcuts2/term.py +0 -0
  55. {mainshortcuts2-2.8.9 → mainshortcuts2-2.9.1}/src/MainShortcuts2/types.py +0 -0
  56. {mainshortcuts2-2.8.9 → mainshortcuts2-2.9.1}/src/MainShortcuts2/utils.py +0 -0
  57. {mainshortcuts2-2.8.9 → mainshortcuts2-2.9.1}/src/MainShortcuts2/win.py +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: MainShortcuts2
3
- Version: 2.8.9
3
+ Version: 2.9.1
4
4
  Summary: Сокращение и улучшение функций + консольные утилиты
5
5
  Author: MainPlay TG
6
6
  Author-email: xbox.roman6666666666@gmail.com
@@ -11,6 +11,18 @@ Classifier: Programming Language :: Python :: 3.11
11
11
  Classifier: Programming Language :: Python :: 3.12
12
12
  Classifier: Programming Language :: Python :: 3.13
13
13
  Classifier: Programming Language :: Python :: 3.14
14
+ Provides-Extra: crypto
15
+ Provides-Extra: full
16
+ Provides-Extra: http
17
+ Requires-Dist: aiohttp (>=3.14.3,<4.0.0) ; extra == "full"
18
+ Requires-Dist: colorama (>=0.4.6,<0.5.0) ; extra == "full"
19
+ Requires-Dist: cryptography (>=50.0.0,<51.0.0) ; extra == "crypto" or extra == "full"
20
+ Requires-Dist: json5 (>=0.15.0,<0.16.0) ; extra == "full"
21
+ Requires-Dist: pillow (>=12.3.0,<13.0.0) ; extra == "full"
22
+ Requires-Dist: progressbar2 (>=4.6.0,<5.0.0) ; extra == "full"
23
+ Requires-Dist: psutil (>=7.2.2,<8.0.0) ; extra == "full"
24
+ Requires-Dist: pyside6 (>=6.11.2,<7.0.0) ; extra == "full"
25
+ Requires-Dist: requests (>=2.32.5,<3.0.0) ; extra == "full" or extra == "http"
14
26
  Project-URL: Repository, https://github.com/MainPlay-TG/MainShortcuts2.py
15
27
  Description-Content-Type: text/markdown
16
28
 
@@ -1,5 +1,5 @@
1
1
  [tool.poetry]
2
- version = "2.8.9"
2
+ version = "2.9.1"
3
3
  name = "MainShortcuts2"
4
4
  description = "Сокращение и улучшение функций + консольные утилиты"
5
5
  authors = ["MainPlay TG <xbox.roman6666666666@gmail.com>"]
@@ -10,6 +10,7 @@ packages = [
10
10
  ]
11
11
 
12
12
  [tool.poetry.scripts]
13
+ micro-json = "MainShortcuts2.__main__:micro_json"
13
14
  ms2-app = "MainShortcuts2.ms2app:main"
14
15
  ms2-hash_check = "MainShortcuts2.ms2hash:hash_check"
15
16
  ms2-hash_gen = "MainShortcuts2.ms2hash:hash_gen"
@@ -24,6 +25,26 @@ nginx-restart = "MainShortcuts2.__main__:nginx_restart"
24
25
  [tool.poetry.dependencies]
25
26
  python = "^3.10"
26
27
 
28
+ # Любые синхронные функции с использованием HTTP
29
+ requests = { version = "^2.32.5", optional = true }
30
+
31
+ # ms2dat1crypto
32
+ cryptography = { version = "^50.0.0", optional = true }
33
+
34
+ # Все прочие необязательные зависимости
35
+ aiohttp = { version = "^3.14.3", optional = true }
36
+ colorama = { version = "^0.4.6", optional = true }
37
+ json5 = { version = "^0.15.0", optional = true }
38
+ pillow = { version = "^12.3.0", optional = true }
39
+ progressbar2 = { version = "^4.6.0", optional = true }
40
+ psutil = { version = "^7.2.2", optional = true }
41
+ pyside6 = { version = "^6.11.2", optional = true }
42
+
43
+ [tool.poetry.extras]
44
+ crypto = ["cryptography"]
45
+ full = ["aiohttp","colorama","cryptography","json5","pillow","progressbar2","psutil","pyside6","requests"]
46
+ http = ["requests"]
47
+
27
48
  [build-system]
28
49
  build-backend = "poetry.core.masonry.api"
29
50
  requires = ["poetry-core"]
@@ -18,39 +18,32 @@ def import_example():
18
18
  print("from MainShortcuts2 import ms")
19
19
 
20
20
 
21
- def nano_json(args: argparse.Namespace = None):
22
- ms.utils.check_programs("nano")
21
+ def _edit_json_argp(name: str):
22
+ argp = argparse.ArgumentParser(f"{name}-json")
23
+ argp.add_argument("-e", "--encoding", default="utf-8", help="кодировка файлов")
24
+ argp.add_argument("-i", "--indent", default=2, type=int, help="кол-во пробелов для отступа")
25
+ argp.add_argument("-m", "--mode", choices=ms.json.MODES_ALL, default="p", help="режим сохранения редактирования")
26
+ argp.add_argument("-s", "--sort", action="store_true", help="сортировать ключи словаря")
27
+ argp.add_argument("-u", "--no-escape", action="store_false", help="не использовать Unicode Escape")
28
+ argp.add_argument("files", nargs="+", help="пути к файлам JSON")
29
+ argp.description = f"форматирование JSON файлов и редактирование в {name}"
30
+ return argp
31
+
32
+
33
+ def _edit_json(args, editor_args: list[str]):
23
34
  import subprocess
24
- if args is None:
25
- argp = argparse.ArgumentParser("nano-json", description="форматирование JSON файлов и редактирование в GNU NANO")
26
- argp.add_argument("files", nargs="+", help="пути к файлам JSON")
27
- argp.add_argument("--nano-help", action="store_true", help="показать помощь nano")
28
- argp.add_argument("-e", "--encoding", default="utf-8", help="кодировка файлов")
29
- argp.add_argument("-f", "--rcfile", help="использовать только этот файл для настройки nano")
30
- argp.add_argument("-i", "--indent", default=2, type=int, help="кол-во пробелов для отступа")
31
- argp.add_argument("-m", "--mode", choices=ms.json.MODES_ALL, default="p", help="режим сохранения редактирования")
32
- argp.add_argument("-s", "--sort", action="store_true", help="сортировать ключи словаря")
33
- argp.add_argument("-u", "--no-escape", action="store_false", help="не использовать Unicode Escape")
34
- args = argp.parse_args()
35
- if args.nano_help:
36
- return subprocess.call(["nano", "--help"])
37
- write_kw = {}
35
+ editor_args.extend(args.files)
36
+ write_kw = {"ensure_ascii": False, "mode": "print"}
38
37
  write_kw["encoding"] = args.encoding
39
- write_kw["ensure_ascii"] = False
40
38
  write_kw["indent"] = args.indent
41
- write_kw["mode"] = "print"
42
39
  write_kw["sort_keys"] = args.sort
43
- nano_args = ["nano"]
44
- if args.rcfile:
45
- nano_args += ["--rcfile", args.rcfile]
46
- nano_args += args.files
47
40
  for i in args.files:
48
41
  try:
49
42
  data = ms.json.read(i, encoding=args.encoding)
50
43
  ms.json.write(i, data, **write_kw)
51
- except Exception as err:
52
- print(err, file=sys.stderr)
53
- subprocess.call(nano_args)
44
+ except Exception as exc:
45
+ print(exc, file=sys.stderr)
46
+ subprocess.run(editor_args)
54
47
  write_kw["ensure_ascii"] = args.no_escape
55
48
  write_kw["indent"] = None if args.mode in ms.json.MODES_COMPRESS else args.indent
56
49
  write_kw["mode"] = args.mode
@@ -58,8 +51,32 @@ def nano_json(args: argparse.Namespace = None):
58
51
  try:
59
52
  data = ms.json.read(i, encoding=args.encoding)
60
53
  ms.json.write(i, data, **write_kw)
61
- except Exception as err:
62
- print(err, file=sys.stderr)
54
+ except Exception as exc:
55
+ print(exc, file=sys.stderr)
56
+
57
+
58
+ def nano_json(args=None):
59
+ ms.utils.check_programs("nano")
60
+ if args is None:
61
+ argp = _edit_json_argp("nano")
62
+ argp.add_argument("--nano-help", action="store_true", help="показать помощь nano")
63
+ argp.add_argument("-f", "--rcfile", help="использовать только этот файл для настройки nano")
64
+ args = argp.parse_args()
65
+ if args.nano_help:
66
+ import subprocess
67
+ return subprocess.run(["nano", "--help"])
68
+ editor_args = ["nano"]
69
+ if args.rcfile:
70
+ editor_args.extend(["--rcfile", args.rcfile])
71
+ _edit_json(args, editor_args)
72
+
73
+
74
+ def micro_json(args=None):
75
+ ms.utils.check_programs("micro")
76
+ if args is None:
77
+ argp = _edit_json_argp("micro")
78
+ args = argp.parse_args()
79
+ _edit_json(args, ["micro"])
63
80
 
64
81
 
65
82
  def _check_nginx() -> int:
@@ -1,2 +1,2 @@
1
1
  name = 'mainshortcuts2'
2
- version = '2.8.9'
2
+ version = '2.9.1'
@@ -1,5 +1,6 @@
1
1
  import requests
2
2
  import requests.auth
3
+ from functools import cached_property
3
4
  from MainShortcuts2 import ms
4
5
  USER_AGENTS: dict[str, str] = {}
5
6
  USER_AGENTS["Android"] = "Mozilla/5.0 (Linux; Android 13; K) Chrome/128.0.6613.146"
@@ -26,7 +27,6 @@ def setdefattr(obj, attr, value):
26
27
  class BaseClient(ms.ObjectBase):
27
28
  """Базовый клиент для HTTP API"""
28
29
  _enable_cookies: bool
29
- _http: requests.Session
30
30
  _url_data: dict[str, str]
31
31
  _url: str
32
32
  cache: "CacheStorage"
@@ -35,7 +35,7 @@ class BaseClient(ms.ObjectBase):
35
35
  self._init(**kw)
36
36
 
37
37
  def _init(self, session: requests.Session = None):
38
- setdefattr(self, "_http", session)
38
+ self.__dict__["http"] = session
39
39
  setdefattr(self, "_enable_cookies", False)
40
40
  setdefattr(self, "_url_data", {})
41
41
  setdefattr(self, "_url", "https://example.com/api/{method}")
@@ -64,12 +64,10 @@ class BaseClient(ms.ObjectBase):
64
64
  def _params(self):
65
65
  return self.http.params
66
66
 
67
- @property
68
- def http(self) -> requests.Session:
67
+ @cached_property
68
+ def http(self):
69
69
  """HTTP сессия"""
70
- if self._http is None:
71
- self._http = requests.Session()
72
- return self._http
70
+ return requests.Session()
73
71
 
74
72
  def _request(self, http_method: str, api_method: str, *, raise_for_status: bool = True, url_data: dict[str, str] = None, **kw):
75
73
  _url_data = self._url_data.copy()
@@ -83,26 +81,18 @@ class BaseClient(ms.ObjectBase):
83
81
  result.raise_for_status()
84
82
  return result
85
83
 
86
- def request(self, httpm, apim, **kw) -> requests.Response:
84
+ def request(self, httpm: str, apim: str, **kw):
87
85
  """Отправить запрос к API"""
88
86
  return self._request(httpm, apim, **kw)
89
87
 
90
88
 
91
- class Base(BaseClient):
92
- """Устаревший класс, используйте BaseClient!"""
93
- def __init_subclass__(cls, **kw):
94
- from warnings import warn
95
- warn("Class 'Base' renamed 'BaseClient' starting with version 2.4.6", DeprecationWarning)
96
- return BaseClient.__init_subclass__(**kw)
97
-
98
-
99
89
  class BasicAuthClient(BaseClient):
100
90
  """API клиент для авторизации `HTTP Basic`"""
101
91
 
102
- def _request(self, http_method: str, api_method: str, **kw) -> requests.Response:
92
+ def _request(self, http_method: str, api_method: str, **kw):
103
93
  if self._headers.get("Authorization") is None:
104
94
  auth_basic(None, None, client=self)
105
- return BaseClient._request(self, http_method, api_method, **kw)
95
+ return super()._request(http_method, api_method, **kw)
106
96
 
107
97
  @property
108
98
  def username(self) -> str:
@@ -127,9 +117,12 @@ class BasicAuthClient(BaseClient):
127
117
 
128
118
  class OfflineObjectBase(ms.ObjectBase):
129
119
  """API объект из словаря"""
120
+ _set_by_annotations = False
130
121
 
131
122
  def __init__(self, raw: dict, *args, **kwargs):
132
123
  self.raw = raw
124
+ if self._set_by_annotations:
125
+ _set_annotations(self)
133
126
  self._init(*args, **kwargs)
134
127
 
135
128
  def __getitem__(self, k):
@@ -144,8 +137,13 @@ class ObjectBase(OfflineObjectBase):
144
137
 
145
138
  def __init__(self, client: BaseClient, raw: dict, *args, **kwargs):
146
139
  self.client = client.client if isinstance(client, ObjectBase) else client
147
- self.raw = raw
148
- self._init(*args, **kwargs)
140
+ super().__init__(raw, *args, **kwargs)
141
+
142
+
143
+ def _set_annotations(obj: OfflineObjectBase):
144
+ for i in type(obj).__annotations__:
145
+ if not (i.startswith("_") or hasattr(obj, i)):
146
+ setattr(obj, i, obj[i])
149
147
 
150
148
 
151
149
  class CacheStorage(dict):
@@ -221,6 +221,11 @@ class MS2:
221
221
  from . import ms2dat1
222
222
  return ms2dat1
223
223
 
224
+ @cached_property
225
+ def ms2dat_v1_crypto(self):
226
+ from . import ms2dat1crypto
227
+ return ms2dat1crypto
228
+
224
229
  @cached_property
225
230
  def ms2dat(self):
226
231
  """Авто выбор при загрузке, последняя версия при сохранении"""
@@ -37,9 +37,11 @@ def make_insert_sql(table: str, values: dict, modifier=""):
37
37
  return f"INSERT {modifier}INTO {table} ({keys}) VALUES ({inserts});", list(values.values())
38
38
 
39
39
 
40
- def make_select_sql(table: str, columns: list[str], where: dict):
40
+ def make_select_sql(table: str, columns: str | list[str], where: dict):
41
41
  text, params = make_where_string(where)
42
- return f"SELECT {','.join(columns)} FROM {table} WHERE {text};", params
42
+ if not isinstance(columns, str):
43
+ columns = ','.join(columns)
44
+ return f"SELECT {columns} FROM {table} WHERE {text};", params
43
45
 
44
46
 
45
47
  def make_update_sql(table: str, values: dict, where: dict):
@@ -84,7 +86,7 @@ class Cursor(sqlite3.Cursor):
84
86
  def select_fetchone(self, table: str, columns: list[str], where: dict):
85
87
  return self.select(table, columns, where).fetchone()
86
88
 
87
- def select(self, table: str, columns: list[str], where: dict):
89
+ def select(self, table: str, columns: str | list[str], where: dict):
88
90
  """Выбрать строки из таблицы. Не выполняет `fetch`!"""
89
91
  return self.execute(*make_select_sql(table, columns, where))
90
92
 
@@ -0,0 +1,137 @@
1
+ import os
2
+ from .ms2dat1 import MS2Dat1
3
+ from cryptography.fernet import Fernet
4
+ from cryptography.hazmat.primitives import hashes
5
+ from cryptography.hazmat.primitives.asymmetric import padding, rsa
6
+ from cryptography.hazmat.primitives.asymmetric.ed25519 import Ed25519PrivateKey, Ed25519PublicKey
7
+ from cryptography.hazmat.primitives.asymmetric.rsa import RSAPrivateKey, RSAPublicKey
8
+ from cryptography.hazmat.primitives.ciphers.aead import AESGCM
9
+ from functools import cached_property
10
+ PADDING_OAEP = padding.OAEP(
11
+ mgf=padding.MGF1(algorithm=hashes.SHA256()),
12
+ algorithm=hashes.SHA256(),
13
+ label=None
14
+ )
15
+
16
+
17
+ class _Base(MS2Dat1):
18
+ @classmethod
19
+ def generate_key(cls):
20
+ """Создать с новым ключом"""
21
+ raise NotImplementedError()
22
+
23
+
24
+ class MS2Dat1WithAESGCM(_Base):
25
+ """MS2Dat v1 с шифрованием AES-GCM"""
26
+
27
+ def __init__(self, key: bytes):
28
+ super().__init__()
29
+ self.aes = AESGCM(key)
30
+
31
+ @classmethod
32
+ def generate_key(cls, key_size=256):
33
+ key = AESGCM.generate_key(key_size)
34
+ return key, cls(key)
35
+
36
+ def decrypt_body(self, data: bytes):
37
+ return self.aes.decrypt(data[:12], data[12:], None)
38
+
39
+ def encrypt_body(self, data: bytes):
40
+ nonce = os.urandom(12)
41
+ return nonce + self.aes.encrypt(nonce, data, None)
42
+
43
+
44
+ class MS2Dat1WithFernet(_Base):
45
+ """MS2Dat v1 с шифрованием Fernet"""
46
+
47
+ def __init__(self, key: bytes):
48
+ super().__init__()
49
+ self.fernet = Fernet(key)
50
+
51
+ @classmethod
52
+ def generate_key(cls):
53
+ key = Fernet.generate_key()
54
+ return key, cls(key)
55
+
56
+ def decrypt_body(self, data: bytes):
57
+ return self.fernet.decrypt(data)
58
+
59
+ def encrypt_body(self, data: bytes):
60
+ return self.fernet.encrypt(data)
61
+
62
+
63
+ class MS2Dat1WithRSA(_Base):
64
+ """MS2Dat v1 с шифрованием RSA"""
65
+
66
+ def __init__(self, key: RSAPrivateKey | RSAPublicKey):
67
+ super().__init__()
68
+ if isinstance(key, RSAPrivateKey):
69
+ self.priv_key = key
70
+ self.pub_key = key.public_key()
71
+ elif isinstance(key, RSAPublicKey):
72
+ self.priv_key = None
73
+ self.pub_key = key
74
+ else:
75
+ raise TypeError(f"A private or public cryptography RSA key is required, not {type(key)}")
76
+
77
+ @cached_property
78
+ def _rsa_data_size(self):
79
+ return (self.pub_key.public_numbers().n.bit_length() + 7) // 8
80
+
81
+ @classmethod
82
+ def generate_key(cls, key_size=2048):
83
+ key = rsa.generate_private_key(65537, key_size)
84
+ return key, cls(key)
85
+
86
+ def decrypt_body(self, data: bytes):
87
+ # Если дан публичный ключ
88
+ if self.priv_key is None:
89
+ raise ValueError("Only the public key is present. Decryption is impossible")
90
+ # Расшифровка ключа AES
91
+ aes_key = self.priv_key.decrypt(data[:self._rsa_data_size], PADDING_OAEP)
92
+ # Извлечение nonce и зашифрованных данных
93
+ nonce = data[self._rsa_data_size:self._rsa_data_size + 12]
94
+ enc_data = data[self._rsa_data_size + 12:]
95
+ # Расшифровка данных
96
+ return AESGCM(aes_key).decrypt(nonce, enc_data, None)
97
+
98
+ def encrypt_body(self, data: bytes):
99
+ # Создание одноразового ключа AES
100
+ aes_key = AESGCM.generate_key(256)
101
+ # Шифрование ключа AES
102
+ enc_aes_key = self.pub_key.encrypt(aes_key, PADDING_OAEP)
103
+ # Шифрование данных
104
+ nonce = os.urandom(12)
105
+ enc_data = AESGCM(aes_key).encrypt(nonce, data, None)
106
+ return enc_aes_key + nonce + enc_data
107
+
108
+
109
+ class MS2Dat1WithEd25519(_Base):
110
+ """MS2Dat v1 с подписью Ed25519 **без шифрования**"""
111
+
112
+ def __init__(self, key: Ed25519PrivateKey | Ed25519PublicKey):
113
+ super().__init__()
114
+ if isinstance(key, Ed25519PrivateKey):
115
+ self.priv_key = key
116
+ self.pub_key = key.public_key()
117
+ elif isinstance(key, Ed25519PublicKey):
118
+ self.priv_key = None
119
+ self.pub_key = key
120
+ else:
121
+ raise TypeError(f"A private or public cryptography Ed25519 key is required, not {type(key)}")
122
+
123
+ @classmethod
124
+ def generate_key(cls):
125
+ key = Ed25519PrivateKey.generate()
126
+ return key, cls(key)
127
+
128
+ def decrypt_body(self, data: bytes):
129
+ d = data[:-64]
130
+ self.pub_key.verify(data[-64:], d)
131
+ return d
132
+
133
+ def encrypt_body(self, data: bytes):
134
+ # Если дан публичный ключ
135
+ if self.priv_key is None:
136
+ raise ValueError("Only the public key is present. Verify is impossible")
137
+ return data + self.priv_key.sign(data)
File without changes