Skip to content

Commit 4a0bc4b

Browse files
committed
style: 💄 format code using black
1 parent 2f825ad commit 4a0bc4b

File tree

16 files changed

+659
-406
lines changed

16 files changed

+659
-406
lines changed

pyencrypt/aes.py

Lines changed: 74 additions & 71 deletions
Large diffs are not rendered by default.

pyencrypt/cli.py

Lines changed: 139 additions & 62 deletions
Original file line numberDiff line numberDiff line change
@@ -10,11 +10,11 @@
1010

1111
from pyencrypt import __description__, __version__
1212
from pyencrypt.decrypt import decrypt_file
13-
from pyencrypt.encrypt import (can_encrypt, encrypt_file, encrypt_key, generate_so_file)
13+
from pyencrypt.encrypt import can_encrypt, encrypt_file, encrypt_key, generate_so_file
1414
from pyencrypt.generate import generate_aes_key
1515
from pyencrypt.license import MAX_DATETIME, MIN_DATETIME, generate_license_file
1616

17-
VERSION = fr"""
17+
VERSION = rf"""
1818
_
1919
_ __ _ _ ___ _ __ ___ _ __ _ _ _ __ | |_
2020
| '_ \| | | |/ _ \ '_ \ / __| '__| | | | '_ \| __|
@@ -33,18 +33,20 @@
3333
"""
3434

3535
PYTHON_MAJOR, PYTHON_MINOR = sys.version_info[:2]
36-
LOADER_FILE_NAME = click.style("encrypted/{}", blink=True, fg='blue')
37-
LICENSE_FILE_NAME = click.style("license.lic", blink=True, fg='blue')
36+
LOADER_FILE_NAME = click.style("encrypted/{}", blink=True, fg="blue")
37+
LICENSE_FILE_NAME = click.style("license.lic", blink=True, fg="blue")
3838

39-
SUCCESS_ANSI = click.style('successfully', fg='green')
39+
SUCCESS_ANSI = click.style("successfully", fg="green")
4040

41-
INVALID_KEY_MSG = click.style('Your encryption 🔑 is invalid.', fg='red')
41+
INVALID_KEY_MSG = click.style("Your encryption 🔑 is invalid.", fg="red")
4242

43-
INVALID_MAC_MSG = click.style('{} is not a valid mac address.', fg='red')
43+
INVALID_MAC_MSG = click.style("{} is not a valid mac address.", fg="red")
4444

45-
INVALID_IPV4_MSG = click.style('{} is not a valid ipv4 address.', fg='red')
45+
INVALID_IPV4_MSG = click.style("{} is not a valid ipv4 address.", fg="red")
4646

47-
INVALID_DATETIME_MSG = click.style('Before date must be less than after date.', fg='red')
47+
INVALID_DATETIME_MSG = click.style(
48+
"Before date must be less than after date.", fg="red"
49+
)
4850

4951
FINISH_ENCRYPT_MSG = f"""
5052
Encryption completed {SUCCESS_ANSI}.
@@ -65,11 +67,11 @@
6567
Generate license file {SUCCESS_ANSI}. Your license file is located in {LICENSE_FILE_NAME}
6668
"""
6769

68-
DATETIME_FORMATS = ['%Y-%m-%dT%H:%M:%S %z', '%Y-%m-%d %H:%M:%S', '%Y-%m-%d']
70+
DATETIME_FORMATS = ["%Y-%m-%dT%H:%M:%S %z", "%Y-%m-%d %H:%M:%S", "%Y-%m-%d"]
6971

7072

7173
class KeyParamType(click.ParamType):
72-
name = 'key'
74+
name = "key"
7375

7476
def _check_key(self, key: str) -> bool:
7577
return not (len(key) % 4 or len(base64.b64decode(key)) % 16)
@@ -81,15 +83,15 @@ def convert(self, value, param, ctx) -> str:
8183
return value
8284

8385
def get_metavar(self, param):
84-
return '🔑'
86+
return "🔑"
8587

8688
def __repr__(self) -> str:
8789
return "KEY"
8890

8991

9092
class MacAddressParamType(click.ParamType):
91-
name = 'mac_address'
92-
pattern = re.compile(r'^([0-9a-fA-F]{2}[:-]){5}([0-9a-fA-F]{2})$')
93+
name = "mac_address"
94+
pattern = re.compile(r"^([0-9a-fA-F]{2}[:-]){5}([0-9a-fA-F]{2})$")
9395

9496
def convert(self, value, param, ctx) -> str:
9597
value = click.STRING.convert(value, param, ctx)
@@ -98,14 +100,14 @@ def convert(self, value, param, ctx) -> str:
98100
return value
99101

100102
def get_metavar(self, param):
101-
return '01:23:45:67:89:AB'
103+
return "01:23:45:67:89:AB"
102104

103105
def __repr__(self) -> str:
104106
return "MacAddress"
105107

106108

107109
class IPv4AddressParamType(click.ParamType):
108-
name = 'ipv4_address'
110+
name = "ipv4_address"
109111

110112
def convert(self, value, param, ctx) -> str:
111113
value = click.STRING.convert(value, param, ctx)
@@ -115,7 +117,7 @@ def convert(self, value, param, ctx) -> str:
115117
self.fail(INVALID_IPV4_MSG.format(value), param, ctx)
116118

117119
def get_metavar(self, param):
118-
return '192.168.0.1'
120+
return "192.168.0.1"
119121

120122
def __repr__(self) -> str:
121123
return "Ipv4Address"
@@ -128,29 +130,75 @@ class CustomParamType:
128130

129131

130132
@click.group()
131-
@click.version_option(__version__, '--version', message=VERSION)
132-
@click.help_option('-h', '--help')
133+
@click.version_option(__version__, "--version", message=VERSION)
134+
@click.help_option("-h", "--help")
133135
def cli():
134136
pass
135137

136138

137-
@cli.command(name='encrypt')
138-
@click.argument('pathname', type=click.Path(exists=True, resolve_path=True))
139-
@click.option('-i', '--in-place', 'replace', default=False, help='make changes to files in place', is_flag=True)
140-
@click.option('-k', '--key', default=None, help=KEY_OPTION_HELP, type=CustomParamType.KEY)
141-
@click.option('--with-license', default=False, help='Add license to encrypted file', is_flag=True)
142-
@click.option('-m', '--bind-mac', 'mac', default=None, help='Bind mac address to encrypted file', type=CustomParamType.MAC_ADDR)
143-
@click.option('-4', '--bind-ipv4', 'ipv4', default=None, help='Bind ipv4 address to encrypted file', type=CustomParamType.IPV4_ADDR)
144-
@click.option('-b', '--before', default=MIN_DATETIME, help='License is invalid before this date.', type=click.DateTime(formats=DATETIME_FORMATS))
145-
@click.option('-a', '--after', default=MAX_DATETIME, help='License is invalid after this date.', type=click.DateTime(formats=DATETIME_FORMATS))
146-
@click.confirmation_option('-y', '--yes', prompt='Are you sure you want to encrypt your python file?', help='Automatically answer yes for confirm questions.')
147-
@click.help_option('-h', '--help')
139+
@cli.command(name="encrypt")
140+
@click.argument("pathname", type=click.Path(exists=True, resolve_path=True))
141+
@click.option(
142+
"-i",
143+
"--in-place",
144+
"replace",
145+
default=False,
146+
help="make changes to files in place",
147+
is_flag=True,
148+
)
149+
@click.option(
150+
"-k", "--key", default=None, help=KEY_OPTION_HELP, type=CustomParamType.KEY
151+
)
152+
@click.option(
153+
"--with-license", default=False, help="Add license to encrypted file", is_flag=True
154+
)
155+
@click.option(
156+
"-m",
157+
"--bind-mac",
158+
"mac",
159+
default=None,
160+
help="Bind mac address to encrypted file",
161+
type=CustomParamType.MAC_ADDR,
162+
)
163+
@click.option(
164+
"-4",
165+
"--bind-ipv4",
166+
"ipv4",
167+
default=None,
168+
help="Bind ipv4 address to encrypted file",
169+
type=CustomParamType.IPV4_ADDR,
170+
)
171+
@click.option(
172+
"-b",
173+
"--before",
174+
default=MIN_DATETIME,
175+
help="License is invalid before this date.",
176+
type=click.DateTime(formats=DATETIME_FORMATS),
177+
)
178+
@click.option(
179+
"-a",
180+
"--after",
181+
default=MAX_DATETIME,
182+
help="License is invalid after this date.",
183+
type=click.DateTime(formats=DATETIME_FORMATS),
184+
)
185+
@click.confirmation_option(
186+
"-y",
187+
"--yes",
188+
prompt="Are you sure you want to encrypt your python file?",
189+
help="Automatically answer yes for confirm questions.",
190+
)
191+
@click.help_option("-h", "--help")
148192
@click.pass_context
149-
def encrypt_command(ctx, pathname, replace, key, with_license, mac, ipv4, before, after):
193+
def encrypt_command(
194+
ctx, pathname, replace, key, with_license, mac, ipv4, before, after
195+
):
150196
"""Encrypt your python code"""
151197
if key is None:
152198
key = generate_aes_key().decode()
153-
click.echo(f'Your randomly encryption 🔑 is {click.style(key,underline=True, fg="yellow")}')
199+
click.echo(
200+
f'Your randomly encryption 🔑 is {click.style(key,underline=True, fg="yellow")}'
201+
)
154202

155203
if before > after:
156204
ctx.fail(INVALID_DATETIME_MSG)
@@ -159,25 +207,25 @@ def encrypt_command(ctx, pathname, replace, key, with_license, mac, ipv4, before
159207

160208
if path.is_file():
161209
if replace:
162-
new_path = path.with_suffix('.pye')
210+
new_path = path.with_suffix(".pye")
163211
else:
164-
new_path = Path(os.getcwd()) / path.with_suffix('.pye').name
212+
new_path = Path(os.getcwd()) / path.with_suffix(".pye").name
165213
encrypt_file(path, key, replace, new_path)
166214
elif path.is_dir():
167215
if replace:
168216
work_dir = path
169217
else:
170-
work_dir = Path(os.getcwd()) / 'encrypted' / path.name
218+
work_dir = Path(os.getcwd()) / "encrypted" / path.name
171219
work_dir.exists() and shutil.rmtree(work_dir)
172220
shutil.copytree(path, work_dir)
173-
files = set(work_dir.glob('**/*.py'))
174-
with click.progressbar(files, label='🔐 Encrypting') as bar:
221+
files = set(work_dir.glob("**/*.py"))
222+
with click.progressbar(files, label="🔐 Encrypting") as bar:
175223
for file in bar:
176-
new_path = file.with_suffix('.pye')
224+
new_path = file.with_suffix(".pye")
177225
if can_encrypt(file):
178226
encrypt_file(file, key, True, new_path)
179227
else:
180-
raise Exception(f'{path} is not a valid path.')
228+
raise Exception(f"{path} is not a valid path.")
181229

182230
cipher_key, d, n = encrypt_key(key.encode()) # 需要放进导入器中
183231
loader_extension = generate_so_file(cipher_key, d, n, license=with_license)
@@ -187,45 +235,56 @@ def encrypt_command(ctx, pathname, replace, key, with_license, mac, ipv4, before
187235
click.echo(FINISH_ENCRYPT_MSG.format(loader_extension.name))
188236

189237

190-
@cli.command(name='decrypt')
191-
@click.argument('pathname', type=click.Path(exists=True, resolve_path=True))
192-
@click.option('-i', '--in-place', 'replace', default=False, help='make changes to files in place', is_flag=True)
193-
@click.option('-k', '--key', required=True, help='Your encryption key.', type=CustomParamType.KEY)
194-
@click.help_option('-h', '--help')
238+
@cli.command(name="decrypt")
239+
@click.argument("pathname", type=click.Path(exists=True, resolve_path=True))
240+
@click.option(
241+
"-i",
242+
"--in-place",
243+
"replace",
244+
default=False,
245+
help="make changes to files in place",
246+
is_flag=True,
247+
)
248+
@click.option(
249+
"-k", "--key", required=True, help="Your encryption key.", type=CustomParamType.KEY
250+
)
251+
@click.help_option("-h", "--help")
195252
@click.pass_context
196253
def decrypt_command(ctx, pathname, replace, key):
197254
"""Decrypt encrypted pye file"""
198255
path = Path(pathname)
199256

200257
if path.is_file():
201258
if replace:
202-
new_path = path.with_suffix('.py')
259+
new_path = path.with_suffix(".py")
203260
else:
204-
new_path = Path(os.getcwd()) / path.with_suffix('.py').name
261+
new_path = Path(os.getcwd()) / path.with_suffix(".py").name
205262
work_dir = new_path.parent
206263
origin_data = decrypt_file(path, key, replace, new_path)
207264
print(origin_data.decode())
208265
elif path.is_dir():
209266
if replace:
210267
work_dir = path
211268
else:
212-
work_dir = Path(os.getcwd()) / 'decrypted' / path.name
269+
work_dir = Path(os.getcwd()) / "decrypted" / path.name
213270
work_dir.exists() and shutil.rmtree(work_dir)
214271
shutil.copytree(path, work_dir)
215-
files = list(work_dir.glob('**/*.pye'))
216-
with click.progressbar(files, label='🔓 Decrypting') as bar:
272+
files = list(work_dir.glob("**/*.pye"))
273+
with click.progressbar(files, label="🔓 Decrypting") as bar:
217274
for file in bar:
218-
new_path = file.with_suffix('.py')
275+
new_path = file.with_suffix(".py")
219276
decrypt_file(file, key, True, new_path)
220277
else:
221-
raise Exception(f'{path} is not a valid path.')
278+
raise Exception(f"{path} is not a valid path.")
222279

223280
click.echo(FINISH_DECRYPT_MSG.format(work_dir=work_dir))
224281

225282

226-
@cli.command(name='generate')
227-
@click.option('-k', '--key', required=True, help='Your encryption key.', type=CustomParamType.KEY)
228-
@click.help_option('-h', '--help')
283+
@cli.command(name="generate")
284+
@click.option(
285+
"-k", "--key", required=True, help="Your encryption key.", type=CustomParamType.KEY
286+
)
287+
@click.help_option("-h", "--help")
229288
@click.pass_context
230289
def generate_loader(ctx, key):
231290
"""Generate loader file using specified key"""
@@ -234,13 +293,31 @@ def generate_loader(ctx, key):
234293
click.echo(FINISH_GENERATE_LOADER_MSG.format(loader_extension.name))
235294

236295

237-
@cli.command(name='license')
238-
@click.help_option('-h', '--help')
239-
@click.option('-k', '--key', required=True, help='Your encryption key.', type=CustomParamType.KEY)
240-
@click.option('-m', '--bind-mac', help='Your mac address.', type=CustomParamType.MAC_ADDR)
241-
@click.option('-4', '--bind-ipv4', help='Your ipv4 address.', type=CustomParamType.IPV4_ADDR)
242-
@click.option('-b', '--before', default=MIN_DATETIME, help='License is invalid before this date.', type=click.DateTime(formats=DATETIME_FORMATS))
243-
@click.option('-a', '--after', default=MAX_DATETIME, help='License is invalid after this date.', type=click.DateTime(formats=DATETIME_FORMATS))
296+
@cli.command(name="license")
297+
@click.help_option("-h", "--help")
298+
@click.option(
299+
"-k", "--key", required=True, help="Your encryption key.", type=CustomParamType.KEY
300+
)
301+
@click.option(
302+
"-m", "--bind-mac", help="Your mac address.", type=CustomParamType.MAC_ADDR
303+
)
304+
@click.option(
305+
"-4", "--bind-ipv4", help="Your ipv4 address.", type=CustomParamType.IPV4_ADDR
306+
)
307+
@click.option(
308+
"-b",
309+
"--before",
310+
default=MIN_DATETIME,
311+
help="License is invalid before this date.",
312+
type=click.DateTime(formats=DATETIME_FORMATS),
313+
)
314+
@click.option(
315+
"-a",
316+
"--after",
317+
default=MAX_DATETIME,
318+
help="License is invalid after this date.",
319+
type=click.DateTime(formats=DATETIME_FORMATS),
320+
)
244321
@click.pass_context
245322
def generate_license(ctx, key, mac, ipv4, before, after):
246323
"""Generate license file using specified key"""
@@ -251,5 +328,5 @@ def generate_license(ctx, key, mac, ipv4, before, after):
251328
click.echo(FINISH_GENERATE_LICENSE_MSG)
252329

253330

254-
if __name__ == '__main__':
331+
if __name__ == "__main__":
255332
cli()

pyencrypt/decrypt.py

Lines changed: 7 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -6,22 +6,24 @@
66

77
def decrypt_key(cipher_key: str, d: int, n: int) -> str:
88
plain_ls = list()
9-
for num in map(int, cipher_key.split('O')):
9+
for num in map(int, cipher_key.split("O")):
1010
plain_ls.append(pow(num, d, n))
1111
# 去掉intt后末尾多余的0
12-
return ''.join(map(chr, filter(lambda x: x != 0, intt(plain_ls))))
12+
return "".join(map(chr, filter(lambda x: x != 0, intt(plain_ls))))
1313

1414

1515
def _decrypt_file(data: bytes, key: str) -> bytes:
1616
return aes_decrypt(data, key)
1717

1818

19-
def decrypt_file(path: Path, key: str, delete_origin: bool = False, new_path: Path = None) -> bytes:
20-
if path.suffix != '.pye':
19+
def decrypt_file(
20+
path: Path, key: str, delete_origin: bool = False, new_path: Path = None
21+
) -> bytes:
22+
if path.suffix != ".pye":
2123
raise Exception(f"{path.name} can't be decrypted.")
2224
data = _decrypt_file(path.read_bytes(), key)
2325
if new_path:
24-
if new_path.suffix != '.py':
26+
if new_path.suffix != ".py":
2527
raise Exception("Origin file path must be py suffix.")
2628
new_path.touch(exist_ok=True)
2729
new_path.write_bytes(data)

0 commit comments

Comments
 (0)