This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
""" | |
Encrypts or Decrypts messages. For encryption: | |
python cipherize.py --message=test --action=encrypt | |
or | |
python3 cipherize.py --filepath /path/to/file --action encrypt | |
Decryption: | |
python cipherize.py --message=gAAAAABhr31eV25KDnD-X1fI8S2gE4i5ynW3aJl-JYzmT2U2Sm_Gz5DFzZEDbREShM1PqJDZafxEw6ex3cvNNMdKWPmJj2irgQ== --action=decrypt | |
or | |
python3 cipherize.py --filepath /path/to/file --action decrypt | |
The password is a master key. | |
""" | |
import argparse | |
import base64 | |
import getpass | |
import cryptography.fernet as fernet | |
parser = argparse.ArgumentParser() | |
parser.add_argument( | |
'--message', | |
help=('Message to decrypt or encrypt, according to chosen action input'), | |
type=str, | |
required=False | |
) | |
parser.add_argument( | |
'--action', | |
help=('Either "encrypt" or "decrypt"'), | |
choices=['encrypt', 'decrypt'], | |
type=str, | |
required=True | |
) | |
parser.add_argument( | |
'--filepath', | |
help=('If defined, then reads the content from the specified path.'), | |
default='', | |
type=str, | |
required=False | |
) | |
def key_is_valid(key: str) -> bool: | |
if not key: | |
return False | |
if len(key) != 32: | |
return False | |
return True | |
if __name__ == '__main__': | |
args = parser.parse_args() | |
message, action, filepath = args.message, args.action, args.filepath | |
if filepath: | |
if message: | |
raise RuntimeError('If `filepath` is defined then `message` should be None.') | |
message = open(filepath).read().encode() | |
else: | |
message = message.encode() | |
key = getpass.getpass() | |
if action == 'encrypt': | |
confirm = getpass.getpass('Confirm Password:') | |
if key != confirm: | |
raise RuntimeError('Password mismatch!') | |
if not key_is_valid(key): | |
raise RuntimeError( | |
'Please choose a valid input key. It must contain 32 url-valid characters.') | |
key = base64.b64encode(key.encode()) | |
ferneter = fernet.Fernet(key) | |
if action == 'encrypt': | |
print('Encrypted message:\n', ferneter.encrypt(message), '\n') | |
elif action == 'decrypt': | |
print('Decrypted message:\n', ferneter.decrypt(message), '\n') |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment