-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathencryption.py
More file actions
61 lines (49 loc) · 1.83 KB
/
Copy pathencryption.py
File metadata and controls
61 lines (49 loc) · 1.83 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
from __future__ import annotations
from pathlib import Path
from typing import Iterable
import pyzipper
def create_archive(
archive_path: Path,
files: Iterable[tuple[Path, str]],
extra_entries: dict[str, bytes] | None = None,
password: str | None = None,
) -> None:
archive_path.parent.mkdir(parents=True, exist_ok=True)
with pyzipper.AESZipFile(
archive_path,
mode="w",
compression=pyzipper.ZIP_DEFLATED,
allowZip64=True,
) as zip_file:
if password:
zip_file.setpassword(password.encode("utf-8"))
zip_file.setencryption(pyzipper.WZ_AES, nbits=256)
for source_path, archive_name in files:
zip_file.write(source_path, arcname=archive_name)
for archive_name, content in sorted((extra_entries or {}).items()):
zip_file.writestr(archive_name, content)
def extract_archive(
archive_path: Path,
destination: Path,
password: str | None = None,
members: list[str] | None = None,
) -> None:
destination.mkdir(parents=True, exist_ok=True)
with pyzipper.AESZipFile(archive_path) as zip_file:
if password:
zip_file.setpassword(password.encode("utf-8"))
zip_file.extractall(path=destination, members=members)
def read_text_entry(
archive_path: Path,
entry_name: str,
password: str | None = None,
) -> str:
with pyzipper.AESZipFile(archive_path) as zip_file:
if password:
zip_file.setpassword(password.encode("utf-8"))
return zip_file.read(entry_name).decode("utf-8")
def list_entries(archive_path: Path, password: str | None = None) -> list[str]:
with pyzipper.AESZipFile(archive_path) as zip_file:
if password:
zip_file.setpassword(password.encode("utf-8"))
return sorted(info.filename for info in zip_file.infolist())