Skip to content

Commit 4fe4440

Browse files
haobiboQPod0
andauthored
update AES module (#11)
* update AES module * allow empty config files Co-authored-by: QPod0 <[email protected]>
1 parent a5ee6ad commit 4fe4440

5 files changed

Lines changed: 29 additions & 17 deletions

File tree

src/aloha/config/hocon.py

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,4 @@
1+
from attrdict import AttrDict
12
from pyhocon import ConfigFactory
23

34

@@ -14,4 +15,4 @@ def load_config_from_hocon_files(config_files: list, base_dir: str):
1415
f = '\n'.join(s)
1516

1617
config = ConfigFactory.parse_string(content=f, basedir=base_dir).as_plain_ordered_dict()
17-
return config
18+
return AttrDict(config)

src/aloha/config/paths.py

Lines changed: 5 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
__all__ = ('get_resource_dir', 'get_config_dir', 'get_current_module_dir', 'get_project_base_dir', 'path_join')
22

33
import os
4+
import warnings
45

56

67
def path_join(*args) -> str:
@@ -50,10 +51,12 @@ def get_config_files() -> list:
5051
for f in files:
5152
file = get_config_dir(f)
5253
if not os.path.exists(file):
53-
raise RuntimeError('Config file [%s] does not exists!' % file)
54+
warnings.warn('Expecting config file [%s] but it does not exists!' % file)
5455
else:
5556
print(' ---> Loading config file [%s]' % file)
56-
ret.append(os.path.expandvars(f))
57+
ret.append(os.path.expandvars(f))
58+
if len(ret) == 0:
59+
warnings.warn('No config files set properly, EMPTY config will be used!')
5760
return ret
5861

5962

src/aloha/encrypt/aes.py

Lines changed: 19 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -1,16 +1,16 @@
11
import base64
22
import binascii
3-
from typing import Union
3+
from typing import Union, Callable, Optional
44

55
from Crypto.Cipher import AES
66
from Crypto.Random import get_random_bytes
77
from Crypto.Util.Padding import pad, unpad
88

9-
_AES_CIPHER_METHODS = { # FULL_CIPHER_NAME: (dict_params,)
10-
"AES/ECB/PKCS5Padding": {'mode': AES.MODE_ECB},
11-
# "AES/ECB/NoPadding": {'mode': AES.MODE_ECB},
12-
# "AES/CBC/PKCS5Padding": {'mode': AES.MODE_CBC, 'iv': b'0000000000000000'},
13-
# "AES/CBC/NoPadding": {'mode': AES.MODE_CBC, 'iv': b'0000000000000000'},
9+
_AES_CIPHER_METHODS = { # FULL_CIPHER_NAME: (dict_params, pad_style)
10+
"AES/ECB/PKCS5Padding": ({'mode': AES.MODE_ECB}, 'pkcs7'),
11+
"AES/ECB/NoPadding": ({'mode': AES.MODE_ECB}, 'pkcs7'),
12+
"AES/CBC/PKCS7Padding": ({'mode': AES.MODE_CBC, 'iv': b'0000000000000000'}, 'pkcs7'),
13+
"AES/CBC/NoPadding": ({'mode': AES.MODE_CBC, 'iv': b'0000000000000000'}, 'x923'),
1414
}
1515

1616

@@ -23,6 +23,8 @@ def _generate_key(key_size: int, method='const') -> bytes:
2323

2424

2525
class AesEncryptor:
26+
supported_cipher_methods = _AES_CIPHER_METHODS
27+
2628
def __init__(self, key: Union[str, bytes] = None, key_size: int = 16, cipher_name: str = 'AES/ECB/PKCS5Padding'):
2729
_key = key
2830
if key is None:
@@ -37,10 +39,13 @@ def __init__(self, key: Union[str, bytes] = None, key_size: int = 16, cipher_nam
3739
# https://pycryptodome.readthedocs.io/en/latest/src/util/util.html
3840
self.cipher_name = cipher_name
3941

40-
def encrypt(self, text: str, output_format='hex') -> Union[str, bytes]:
41-
padded = pad(text.encode(), block_size=self.block_size)
42+
def encrypt(self, text: str, output_format='hex', func_pad: Optional[Callable] = None) -> Union[str, bytes]:
43+
dict_params, pad_style = _AES_CIPHER_METHODS.get(self.cipher_name)
44+
if not callable(func_pad):
45+
func_pad = lambda x: pad(data, block_size=self.block_size, style=pad_style)
4246

43-
dict_params = _AES_CIPHER_METHODS.get(self.cipher_name)
47+
data = text.encode()
48+
padded = func_pad(data)
4449
cipher = AES.new(key=self.key_aes, **dict_params)
4550
bytes_crypt = cipher.encrypt(padded)
4651

@@ -54,7 +59,7 @@ def encrypt(self, text: str, output_format='hex') -> Union[str, bytes]:
5459
raise ValueError('Unknown output_type [%s]' % output_format)
5560
return crypt
5661

57-
def decrypt(self, text: Union[str, bytes], input_format: str = 'hex') -> Union[str, bytes]:
62+
def decrypt(self, text: Union[str, bytes], input_format: str = 'hex', func_unpad: Optional[Callable] = None) -> Union[str, bytes]:
5863
text += (len(text) % 4) * '='
5964
if input_format == 'hex':
6065
crypt = binascii.a2b_hex(text)
@@ -64,10 +69,12 @@ def decrypt(self, text: Union[str, bytes], input_format: str = 'hex') -> Union[s
6469
crypt = text
6570
else:
6671
raise ValueError('Unknown output_type [%s]' % input_format)
67-
dict_params = _AES_CIPHER_METHODS.get(self.cipher_name)
72+
dict_params, pad_style = _AES_CIPHER_METHODS.get(self.cipher_name)
6873
cipher = AES.new(key=self.key_aes, **dict_params)
6974
data = cipher.decrypt(crypt)
70-
data = unpad(data, block_size=self.block_size)
75+
if not callable(func_unpad):
76+
func_unpad = lambda x: unpad(x, block_size=self.block_size, style=pad_style)
77+
data = func_unpad(data)
7178
return data.decode('UTF-8')
7279

7380

src/aloha/encrypt/rsa.py

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -21,6 +21,7 @@
2121
class RsaEncryptor:
2222
_dict_cache_cipher = {}
2323
_dict_cache_decipher = {}
24+
supported_cipher_methods = _RSA_CIPHER_METHODS
2425

2526
# ref: https://cryptobook.nakov.com/asymmetric-key-ciphers/rsa-encrypt-decrypt-examples
2627
def __init__(self, key_private: str = None, key_public: str = None, cipher_name: str = 'RSA/ECB/PKCS1Padding'):

src/setup.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -31,9 +31,9 @@
3131
zip_safe=False,
3232
install_requires=[],
3333
extras_require={
34-
'base': ['pyhocon', 'pycryptodome'],
34+
'base': ['attrdict3', 'pyhocon', 'pycryptodome'],
3535
'build': ['Cython'],
36-
'service': ['requests', 'tornado', 'psutil'],
36+
'service': ['requests', 'tornado', 'psutil', 'pyjwt'],
3737
'db': ['sqlalchemy', 'psycopg2-binary', 'pymysql', 'elasticsearch', 'pymongo', 'redis>4.2.0'],
3838
'stream': ['confluent_kafka'],
3939
'data': ['pandas'],

0 commit comments

Comments
 (0)