rtzip 0.5.0__tar.gz → 0.5.2__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.
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.3
2
2
  Name: rtzip
3
- Version: 0.5.0
3
+ Version: 0.5.2
4
4
  Requires-Dist: obstruct==0.5.2
5
5
  Requires-Dist: pyaes>=1.6.1
6
6
  Requires-Python: >=3.12
@@ -4,7 +4,7 @@ requires = ["uv_build < 0.13"]
4
4
 
5
5
  [project]
6
6
  name = "rtzip"
7
- version = "0.5.0"
7
+ version = "0.5.2"
8
8
  requires-python = ">=3.12"
9
9
  dependencies = [
10
10
  "obstruct==0.5.2",
@@ -6,7 +6,7 @@ requires = [
6
6
 
7
7
  [project]
8
8
  name = "rtzip"
9
- version = "0.5.0"
9
+ version = "0.5.2"
10
10
  requires-python = ">=3.12"
11
11
  dependencies = [
12
12
  "obstruct==0.5.2",
@@ -39,7 +39,7 @@ class DataSource:
39
39
  """
40
40
 
41
41
 
42
- async def single_chunk_wrapper(__data: Buffer, /):
42
+ async def single_chunk_wrapper[T](__data: T, /):
43
43
  yield __data
44
44
 
45
45
 
@@ -54,6 +54,10 @@ class RemoteZip:
54
54
  :ivar files: 中央目录文件列表
55
55
  :ivar file_mapping: 构建的文件映射表,可能为 None
56
56
  :ivar is_zip64: 此 zip 文件是否启动了 zip64 扩展,默认为 False
57
+ :ivar context: 上下文字典
58
+ 上下文字典信息:
59
+ - ``pwd``: 字节形式的密码,用于解密加密的 zip 文件
60
+
57
61
  """
58
62
 
59
63
  async def _read_range(self, offset, length):
@@ -81,7 +85,7 @@ class RemoteZip:
81
85
 
82
86
  self.is_zip64 = False
83
87
  self.context = kwargs
84
- self._namelist = None
88
+ self._namelist: list[bytes] | None = None
85
89
 
86
90
  def _merge_context(self, overrides: dict[str, Any]):
87
91
  return {
@@ -89,10 +93,15 @@ class RemoteZip:
89
93
  **overrides
90
94
  }
91
95
 
92
- def namelist(self):
96
+ def namelist(self) -> list[bytes]:
97
+ """
98
+ 获取所有的文件名(bytes)列表
99
+ :return: 文件名列表
100
+ """
93
101
  if self._namelist is None:
94
102
  if self.files is None:
95
103
  raise ValueError("No files. Please call `fetch_file_list()` first")
104
+
96
105
  self._namelist = [
97
106
  f.filename for f in self.files
98
107
  ]
@@ -167,7 +176,7 @@ class RemoteZip:
167
176
 
168
177
  # print(zip64_eocd_disk_id, zip64_eocd_offset, zip64_total_disks)
169
178
 
170
- zip64_eocd_data = await self._read_range(zip64_eocd_offset, 96)
179
+ zip64_eocd_data = bytes(await self._read_range(zip64_eocd_offset, 96))
171
180
  # print(zip64_eocd_data[:64])
172
181
  assert zip64_eocd_data[:4] == ZIP64_EOCD_SIGNATURE
173
182
 
@@ -271,7 +280,7 @@ class RemoteZip:
271
280
  entry = entry or self.find_file_entry(normpath(bytes(filename)))
272
281
 
273
282
  if reuse and entry.filename in self.cached_headers:
274
- return self.cached_headers[entry.filename]
283
+ return self.cached_headers[entry.filename], b''
275
284
 
276
285
  buffer = await self._read_range(entry.local_header_offset, entry.__cstruct__.size + 64) # 预留64字节的变长字段
277
286
 
@@ -324,7 +333,7 @@ class RemoteZip:
324
333
  从本地已有的数据获取 filename 对应的 CDEntry 对象
325
334
 
326
335
  如果已有构建好的文件映射,则直接查找文件映射内容
327
- 否则将遍历中央仓库找到文件
336
+ 否则将遍历中央目录找到文件
328
337
 
329
338
  若是发现文件不存在,将会抛出 FileNotFoundError
330
339
 
@@ -390,7 +399,7 @@ class RemoteZip:
390
399
 
391
400
  async def read(self, filename: bytes, **kwargs) -> bytearray:
392
401
  """
393
- 直接全量加载文件的内容
402
+ 全量加载文件的内容(底层仍然调用 .stream 方法)
394
403
 
395
404
  建议在小文件上使用此方法
396
405
 
@@ -404,7 +413,16 @@ class RemoteZip:
404
413
  return buffer
405
414
 
406
415
 
407
- async def resolve(self, filename: bytes, max_resolve=24, **kwargs) -> bytes:
416
+ async def resolve(self, filename: bytes, max_resolve: float | int = 24, **kwargs) -> bytes:
417
+ """
418
+ 解析一个文件的最终路径(基于 zip 的符号链接规范)
419
+
420
+ :param filename: 文件名
421
+ :param max_resolve: 最大可解析次数(你可以通过传入 ``float('inf')`` 来不限制解析次数,但不建议这样做
422
+ :param kwargs: 上下文信息
423
+ :raise ValueError: 当解析次数达到指定的上限时抛出
424
+ :return:
425
+ """
408
426
  kwargs = self._merge_context(kwargs)
409
427
  entry = self.find_file_entry(filename)
410
428
  target = entry.filename
@@ -419,6 +437,9 @@ class RemoteZip:
419
437
 
420
438
  cnt += 1
421
439
 
440
+ if cnt >= max_resolve:
441
+ raise ValueError("Too many resolved files")
442
+
422
443
  return target
423
444
 
424
445
  def listdir(self, path: bytes) -> list[bytes]:
@@ -454,7 +475,7 @@ class RemoteZip:
454
475
  return (await self.read(path, **kwargs)).decode(encoding, errors=errors)
455
476
 
456
477
  def rglob(self, pattern):
457
- for file in self._namelist:
478
+ for file in self.namelist():
458
479
  if fnmatch(file, pattern):
459
480
  yield file
460
481
 
@@ -0,0 +1,76 @@
1
+ # Written by DeepSeek
2
+ import warnings
3
+
4
+ from cryptography.hazmat.primitives import hashes
5
+ from cryptography.hazmat.primitives.ciphers import Cipher, algorithms, modes
6
+ from cryptography.hazmat.primitives.kdf.pbkdf2 import PBKDF2HMAC
7
+
8
+
9
+ def pbkdf2_hmac_impl(pwd: bytes, length: int, salt: bytes, iterations: int) -> bytes:
10
+ kdf = PBKDF2HMAC(
11
+ algorithm=hashes.SHA1(),
12
+ length=length,
13
+ salt=salt,
14
+ iterations=iterations,
15
+ )
16
+ return kdf.derive(pwd) # 注意:密码需要单独传递
17
+
18
+
19
+ class CryptographyAESCipher:
20
+ __slots__ = ('_d', '_enc_key', '_initial_value', '_c', '_b')
21
+
22
+ def __init__(self, enc_key):
23
+ self._enc_key = enc_key
24
+ self._c = 1
25
+ self._b = bytearray()
26
+
27
+ @classmethod
28
+ def get_cipher(cls, enc_key: bytes):
29
+ return cls(enc_key)
30
+
31
+ def update(self, encrypted_data: bytes) -> bytes:
32
+ # print(f"拼接:{len(self._b)} + {len(encrypted_data)} = {len(self._b) + len(encrypted_data)}")
33
+ self._b.extend(encrypted_data)
34
+ buffer = bytearray()
35
+
36
+ for offset in range(0, len(self._b), 16):
37
+ data = self._b[offset:offset + 16]
38
+
39
+ d = Cipher(
40
+ algorithms.AES(self._enc_key),
41
+ modes.CTR(self._c.to_bytes(16, 'little'))
42
+ ).decryptor()
43
+
44
+ if len(data) == 16:
45
+ self._c += 1
46
+ buffer.extend(d.update(data))
47
+
48
+ else:
49
+ self._b = self._b[offset:]
50
+ # print("裁剪:", len(self._b))
51
+ break
52
+
53
+ return buffer
54
+
55
+ def finalize(self) -> bytes:
56
+ d = Cipher(
57
+ algorithms.AES(self._enc_key),
58
+ modes.CTR(self._c.to_bytes(16, 'little'))
59
+ ).decryptor()
60
+
61
+ k = d.update(self._b)
62
+ print("K", k)
63
+ return k
64
+
65
+
66
+ def install():
67
+ warnings.warn(
68
+ "The 'cryptography' backend is deprecated and will be removed in version 1.0. "
69
+ "We strongly recommend switching to 'pycryptodome' for better performance. "
70
+ "To migrate, import `rtzip.backends.pycryptodome_impl` and call `install()`.",
71
+ DeprecationWarning,
72
+ stacklevel=2
73
+ )
74
+
75
+ from rtzip.zip_aes import install
76
+ install(pbkdf2_hmac_impl, CryptographyAESCipher)
@@ -5,8 +5,8 @@ from typing import Protocol
5
5
 
6
6
  from obstruct import Struct, u16, u8
7
7
 
8
- from .errors import UnsupportedAlgorithmError, WrongPasswordError
9
8
  from .algorithm_register import algorithm_handler, is_algorithm_handlier_available, get_algorithm_handler
9
+ from .errors import UnsupportedAlgorithmError, WrongPasswordError
10
10
 
11
11
 
12
12
  @dataclasses.dataclass(slots=True)
@@ -175,7 +175,7 @@ async def zip_aes_stream_decryptor(
175
175
  encrypted_data_len = compressed_size - enc_header_len - mac_length
176
176
 
177
177
  # 获取派生密钥
178
- key_material = call_pbkdf2_hmac(pwd, 2 * key_len + 2, salt, 1000)
178
+ key_material = call_pbkdf2_hmac(pwd, 2 * key_len + 2, bytes(salt), 1000)
179
179
  enc_key = key_material[:key_len]
180
180
  hmac_key = key_material[key_len:key_len * 2]
181
181
  checksum = key_material[-2:]
@@ -236,6 +236,10 @@ async def zip_aes_stream_decryptor(
236
236
 
237
237
  # print("Get chunk {}/{}".format(size, encrypted_data_len))
238
238
 
239
+ x = cipher.finalize()
240
+ if x:
241
+ yield x
242
+
239
243
  # 该读取 MAC 了
240
244
 
241
245
  while len(buf) < mac_length:
@@ -57,7 +57,7 @@ def decrypt_byte(k2: int) -> int:
57
57
 
58
58
 
59
59
  async def zipcrypto_wrapper(
60
- raw_data: AsyncGenerator[bytes, None],
60
+ raw_data: AsyncGenerator[bytes | bytearray | memoryview, None],
61
61
  entry: CDEntry,
62
62
  header: LocalFileHeader,
63
63
  ctx: dict[str , Any]
@@ -1,39 +0,0 @@
1
- # Written by DeepSeek
2
-
3
- from cryptography.hazmat.primitives import hashes
4
- from cryptography.hazmat.primitives.ciphers import Cipher, algorithms, modes
5
- from cryptography.hazmat.primitives.kdf.pbkdf2 import PBKDF2HMAC
6
-
7
-
8
- def pbkdf2_hmac_impl(pwd: bytes, length: int, salt: bytes, iterations: int) -> bytes:
9
- kdf = PBKDF2HMAC(
10
- algorithm=hashes.SHA1(),
11
- length=length,
12
- salt=salt,
13
- iterations=iterations,
14
- )
15
- return kdf.derive(pwd) # 注意:密码需要单独传递
16
-
17
-
18
- class CryptographyAESCipher:
19
- __slots__ = ('_d', )
20
-
21
- def __init__(self, decryptor):
22
- self._d = decryptor
23
-
24
- @classmethod
25
- def get_cipher(cls, enc_key: bytes):
26
- cipher = Cipher(algorithms.AES(enc_key), modes.CTR((1).to_bytes(16, 'little')))
27
- decryptor = cipher.decryptor()
28
- return cls(decryptor)
29
-
30
- def update(self, encrypted_data: bytes) -> bytes:
31
- return self._d.update(encrypted_data)
32
-
33
- def finalize(self) -> bytes:
34
- return self._d.finalize()
35
-
36
-
37
- def install():
38
- from rtzip.zip_aes import install
39
- install(pbkdf2_hmac_impl, CryptographyAESCipher)
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes