1+ import base64
12import os
23import shutil
34import sys
45from pathlib import Path
56
67import click
7-
88from pyencrypt import __description__ , __version__
99from pyencrypt .decrypt import decrypt_file
1010from pyencrypt .encrypt import (can_encrypt , encrypt_file , encrypt_key ,
4444Finally, add `import loader` at the top of your entry file.\
4545 """
4646
47+ FINISH_DECRYPT_MSG = """
48+ Decryption completed successfully. Your origin source code has be put: {path}\
49+ """
50+
51+ FINISH_GENERATE_MSG = f"""
52+ Generate loader file successfully. Your loader file is located in { LAODER_FILE_NAME }
53+ """
54+
55+
56+ def _check_key (key : str ) -> bool :
57+ return not (len (key ) % 4 or len (base64 .b64decode (key )) % 16 )
58+
4759
4860@click .group ()
4961@click .version_option (__version__ , '--version' , message = VERSION )
@@ -52,11 +64,6 @@ def cli():
5264 pass
5365
5466
55- FINISH_DECRYPT_MSG = """
56- Decryption completed successfully. Your origin source code has be put: {path}\
57- """
58-
59-
6067@cli .command (name = 'encrypt' )
6168@click .argument ('pathname' , type = click .Path (exists = True , resolve_path = True ))
6269@click .option ('-i' ,
@@ -70,17 +77,19 @@ def cli():
7077 default = None ,
7178 help = KEY_OPTION_HELP ,
7279 type = click .STRING )
73- @click .option ('-y' , '--yes' , default = False , help = 'yes' , is_flag = True )
80+ @click .confirmation_option (
81+ prompt = 'Are you sure you want to encrypt your python file?' ,
82+ help = 'Confirm the action without prompting' )
7483@click .help_option ('-h' , '--help' )
75- def encrypt_command (pathname , delete , key , yes ):
84+ @click .pass_context
85+ def encrypt_command (ctx , pathname , delete , key ):
7686 """Encrypt your python code"""
87+ if key is not None and not _check_key (key ):
88+ ctx .fail (f'Your encryption key is invalid.' )
7789 if key is None :
7890 key = generate_aes_key ().decode ()
7991 click .echo (f'Your randomly encryption key is { key } ' )
8092
81- if not yes :
82- click .confirm ('Are you sure you want to encrypt your python file?' ,
83- abort = True )
8493 path = Path (pathname )
8594 work_dir = Path (os .getcwd ()) / 'encrypted' / 'src'
8695
@@ -138,5 +147,21 @@ def decrypt_command(pathname, key):
138147 click .echo (FINISH_DECRYPT_MSG .format (path = work_dir ))
139148
140149
150+ @cli .command (name = 'generate' )
151+ @click .option ('-k' ,
152+ '--key' ,
153+ required = True ,
154+ help = 'Your encryption key.' ,
155+ type = click .STRING )
156+ @click .pass_context
157+ def generate_loader (ctx , key ):
158+ """Generate loader file using specified key"""
159+ if not _check_key (key ):
160+ ctx .fail (f'Your encryption key is invalid.' )
161+ cipher_key , d , n = encrypt_key (key .encode ())
162+ generate_so_file (cipher_key , d , n )
163+ click .echo (FINISH_GENERATE_MSG )
164+
165+
141166if __name__ == '__main__' :
142167 cli ()
0 commit comments