Skip to content

Commit f809609

Browse files
committed
style: 💄 format code using yapf and isort
1 parent 2e204e4 commit f809609

File tree

12 files changed

+760
-133
lines changed

12 files changed

+760
-133
lines changed

README.md

Lines changed: 11 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -62,4 +62,14 @@ Options:
6262
```python
6363
import loader
6464
from test import *
65-
```
65+
```
66+
67+
## Development
68+
69+
### Format Code
70+
71+
```shell
72+
yapf --recursive -i pyencrypt
73+
isort pyencrypt
74+
```
75+

a.py

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
import loader
2+
from test.test2.abc import *
3+
print(DEMO1)
4+
# from test.abc import *
5+
# print(DEMO1)

dev-requirement.txt

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
1+
-r requirement.txt
2+
isort==5.10.1
3+
yapf==0.31.0

pyencrypt/__init__.py

Lines changed: 0 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,2 @@
11
__version__ = '0.1.0'
22
__description__ = 'encrypt python source code and import dynamically.'
3-
4-

pyencrypt/aes.py

Lines changed: 658 additions & 69 deletions
Large diffs are not rendered by default.

pyencrypt/cli.py

Lines changed: 8 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -35,8 +35,7 @@
3535
major=PYTHON_MAJOR,
3636
minor=PYTHON_MINOR,
3737
abi=sys.abiflags,
38-
platform=sys.platform
39-
)
38+
platform=sys.platform)
4039

4140
FINISH_ENCRYPT_MSG = f"""
4241
Encryption completed successfully.
@@ -64,27 +63,24 @@ def cli():
6463
'--in-place',
6564
'delete',
6665
default=False,
67-
help='make changes to files in place',is_flag=True)
66+
help='make changes to files in place',
67+
is_flag=True)
6868
@click.option('-k',
6969
'--key',
7070
default=None,
7171
help=KEY_OPTION_HELP,
7272
type=click.STRING)
73-
@click.option('-y',
74-
'--yes',
75-
default=False,
76-
help='yes',
77-
is_flag=True)
73+
@click.option('-y', '--yes', default=False, help='yes', is_flag=True)
7874
@click.help_option('-h', '--help')
79-
def encrypt_command(pathname, delete, key,yes):
75+
def encrypt_command(pathname, delete, key, yes):
8076
"""Encrypt your python code"""
8177
if key is None:
8278
key = generate_aes_key().decode()
8379
click.echo(f'Your randomly encryption key is {key}')
8480

8581
if not yes:
8682
click.confirm('Are you sure you want to encrypt your python file?',
87-
abort=True)
83+
abort=True)
8884
path = Path(pathname)
8985
work_dir = Path(os.getcwd()) / 'encrypted' / 'src'
9086

@@ -94,7 +90,8 @@ def encrypt_command(pathname, delete, key,yes):
9490
elif path.is_dir():
9591
work_dir.exists() and shutil.rmtree(work_dir)
9692
shutil.copytree(path, work_dir)
97-
files = set(path.glob('**/*.py')) - set(path.glob(f'encrypted/**/*.py'))
93+
files = set(path.glob('**/*.py')) - set(
94+
path.glob(f'encrypted/**/*.py'))
9895
for file in files:
9996
if can_encrypt(file):
10097
print(file)

pyencrypt/decrypt.py

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
from pathlib import Path
2+
23
from pyencrypt.aes import aes_decrypt
34
from pyencrypt.ntt import intt
45

@@ -11,18 +12,17 @@ def decrypt_key(cipher_key: str, n: int, d: int) -> str:
1112
return ''.join(map(chr, filter(lambda x: x != 0, intt(plain_ls))))
1213

1314

14-
15-
def _decrypt_file(data:bytes, key:str) -> bytes:
16-
return aes_decrypt(data,key)
15+
def _decrypt_file(data: bytes, key: str) -> bytes:
16+
return aes_decrypt(data, key)
1717

1818

1919
def decrypt_file(path: Path, key: str, new_path: Path = None) -> bytes:
2020
if path.suffix != '.pye':
2121
raise Exception(f"{path.name} can't be decrypted.")
22-
data = _decrypt_file(path.read_bytes(),key)
22+
data = _decrypt_file(path.read_bytes(), key)
2323
if new_path:
2424
if new_path.suffix != '.py':
2525
raise Exception("Origin file path must be py suffix.")
2626
new_path.touch(exist_ok=True)
2727
new_path.write_bytes(data)
28-
return data
28+
return data

pyencrypt/encrypt.py

Lines changed: 27 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -3,13 +3,18 @@
33
from pathlib import Path
44

55
from pyencrypt.aes import aes_encrypt
6-
from pyencrypt.generate import generate_rsa_number
6+
from pyencrypt.generate import generate_rsa_number
77
from pyencrypt.ntt import ntt
88

9-
NOT_ALLOWED_ENCRYPT_FILES = ['__init__.py',]
9+
NOT_ALLOWED_ENCRYPT_FILES = [
10+
'__init__.py',
11+
]
1012

1113

12-
def _encrypt_file(data: bytes, key: bytes,) -> None:
14+
def _encrypt_file(
15+
data: bytes,
16+
key: bytes,
17+
) -> None:
1318
return aes_encrypt(data, key)
1419

1520

@@ -34,16 +39,17 @@ def encrypt_key(key: bytes) -> str:
3439
return 'O'.join(map(str, cipher_ls)), numbers['d'], numbers['n']
3540

3641

37-
def generate_so_file(cipher_key: str, d: int, n:int):
42+
def generate_so_file(cipher_key: str, d: int, n: int):
3843
private_key = f'{n}O{d}'
3944
path = Path(os.path.abspath(__file__)).parent
4045

4146
decrypt_source_ls = list()
42-
need_import_files = ['ntt.py','aes.py','decrypt.py']
47+
need_import_files = ['ntt.py', 'aes.py', 'decrypt.py']
4348
for file in need_import_files:
4449
file_path = path / file
4550
decrypt_source_ls.append(file_path.read_text().replace(
46-
'from pyencrypt.ntt import intt', '').replace('from pyencrypt.aes import aes_decrypt',''))
51+
'from pyencrypt.ntt import intt',
52+
'').replace('from pyencrypt.aes import aes_decrypt', ''))
4753

4854
loader_source_path = path / 'loader.py'
4955
loader_source = loader_source_path.read_text().replace(
@@ -66,22 +72,32 @@ def generate_so_file(cipher_key: str, d: int, n:int):
6672

6773
setup_file_path = Path(os.path.abspath(__file__)).parent / 'setup.py'
6874
args = [
69-
'pyminifier', '--obfuscate-classes' ,'--obfuscate-import-methods', '--replacement-length', '20', '-o',
75+
'pyminifier', '--obfuscate-classes', '--obfuscate-import-methods',
76+
'--replacement-length', '20', '-o',
7077
loader_file_path.as_posix(),
7178
loader_file_path.as_posix()
7279
]
7380
ret = subprocess.run(args, shell=False, encoding='utf-8')
7481
if ret.returncode == 0:
7582
pass
7683

77-
args = ['python', setup_file_path.as_posix(), 'build_ext','--build-lib', temp_dir.as_posix()]
78-
ret = subprocess.run(args, shell=False, stderr=subprocess.PIPE,encoding='utf-8')
84+
args = [
85+
'python',
86+
setup_file_path.as_posix(), 'build_ext', '--build-lib',
87+
temp_dir.as_posix()
88+
]
89+
ret = subprocess.run(args,
90+
shell=False,
91+
stderr=subprocess.PIPE,
92+
encoding='utf-8')
7993
if ret.returncode == 0:
8094
pass
8195

8296

83-
84-
def encrypt_file(path: Path, key: str, delete_origin: bool = False, new_path: Path = None):
97+
def encrypt_file(path: Path,
98+
key: str,
99+
delete_origin: bool = False,
100+
new_path: Path = None):
85101
if not can_encrypt(path):
86102
raise Exception(f"{path.name} can't be encrypted.")
87103
encrypted_data = _encrypt_file(path.read_bytes(), key)

pyencrypt/generate.py

Lines changed: 9 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -1,20 +1,18 @@
1-
from Crypto.PublicKey import RSA
21
import base64
32
import os
43

5-
def generate_aes_key(size:str = 32) -> str:
4+
from Crypto.PublicKey import RSA
5+
6+
7+
def generate_aes_key(size: str = 32) -> str:
68
return base64.b64encode(os.urandom(size))
79

8-
def generate_rsa_number(bits:int):
10+
11+
def generate_rsa_number(bits: int):
912
r = RSA.generate(bits)
10-
return {
11-
'p':r.p,
12-
'q':r.q,
13-
'n': r.n,
14-
'e': r.e,
15-
'd':r.d
16-
}
13+
return {'p': r.p, 'q': r.q, 'n': r.n, 'e': r.e, 'd': r.d}
14+
1715

1816
if __name__ == '__main__':
1917
print(generate_aes_key(32))
20-
print(generate_rsa_number(2048))
18+
print(generate_rsa_number(2048))

pyencrypt/loader.py

Lines changed: 16 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -14,43 +14,51 @@
1414
_Path = Union[bytes, str]
1515
sys.dont_write_bytecode = True
1616

17+
1718
class Base:
1819
def __dir__(self) -> Iterable[str]:
1920
return []
2021

21-
class EncryptFileLoader(abc.SourceLoader,Base):
2222

23-
def __init__(self,path) -> None:
23+
class EncryptFileLoader(abc.SourceLoader, Base):
24+
def __init__(self, path) -> None:
2425
self.path = path or ''
2526
self.__private_key = ''
2627
self.__cipher_key = ''
27-
2828

2929
def get_filename(self, fullname: str) -> _Path:
3030
return self.path
3131

3232
def get_data(self, path: _Path) -> bytes:
3333
try:
3434
__n, __d = self.__private_key.split('O', 1)
35-
return decrypt_file(Path(path), decrypt_key(self.__cipher_key, int(__n), int(__d)))
35+
return decrypt_file(
36+
Path(path), decrypt_key(self.__cipher_key, int(__n), int(__d)))
3637
except Exception:
3738
traceback.print_exc()
3839
return b''
3940

4041

41-
class EncryptFileFinder(abc.MetaPathFinder,Base):
42-
def find_spec(self, fullname: str, path: Sequence[_Path], target: types.ModuleType = None) -> ModuleSpec:
42+
class EncryptFileFinder(abc.MetaPathFinder, Base):
43+
def find_spec(self,
44+
fullname: str,
45+
path: Sequence[_Path],
46+
target: types.ModuleType = None) -> ModuleSpec:
4347
if path:
4448
if isinstance(path, _NamespacePath):
45-
file_path = Path(path._path[0])/ f'{fullname.rsplit(".",1)[-1]}.pye'
49+
file_path = Path(
50+
path._path[0]) / f'{fullname.rsplit(".",1)[-1]}.pye'
4651
else:
4752
file_path = Path(path[0]) / f'{fullname.rsplit(".",1)[-1]}.pye'
4853
else:
4954
file_path = f'{fullname}.pye'
5055
if not os.path.exists(file_path):
5156
return None
5257
loader = EncryptFileLoader(file_path)
53-
return spec_from_loader(name=fullname, loader=loader, origin='origin-encrypt')
58+
return spec_from_loader(name=fullname,
59+
loader=loader,
60+
origin='origin-encrypt')
61+
5462

5563
# TODO: generate randomly AES Class
5664
sys.meta_path.append(EncryptFileFinder())

0 commit comments

Comments
 (0)