Skip to content

Instantly share code, notes, and snippets.

@WillianFuks
Last active April 16, 2022 15:36
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save WillianFuks/37462cf8f03161ed6903ec41bf188645 to your computer and use it in GitHub Desktop.
Save WillianFuks/37462cf8f03161ed6903ec41bf188645 to your computer and use it in GitHub Desktop.
"""
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