2021-csci-ga3205-hw-09/index.py

59 lines
1.4 KiB
Python
Raw Permalink Normal View History

import argparse
2021-11-12 04:14:40 +00:00
from Cryptodome.Cipher import AES
from Cryptodome.Random import get_random_bytes
2021-11-12 04:14:40 +00:00
def encrypt(text, key):
# make encryptor
encryptor = AES.new(key, AES.MODE_CFB)
2021-11-12 04:14:40 +00:00
# takes the data and returns ciphertext
cipher_text = encryptor.encrypt(text)
# now to write the ciphertext to the file
encrypted_file = open("encrypted_file.txt", "wb")
encrypted_file.write(cipher_text)
encrypted_file.close()
# return the cipher_text to show users
return cipher_text
2021-11-12 04:18:05 +00:00
def decrypt(text, key):
# make decrypter
decrypter = AES.new(key, AES.MODE_CFB)
plain_text = decrypter.decrypt(text)
return plain_text
def main():
2021-11-12 04:14:40 +00:00
# get arguments from command line
parser = argparse.ArgumentParser()
parser.add_argument('-f', '--file', type=open)
args = parser.parse_args()
2021-11-12 04:14:40 +00:00
# make random 32B long key
key = get_random_bytes(32)
# read the text file in and make it a string with no line breaks
text = args.file.read().replace('\n', '')
2021-11-12 04:18:05 +00:00
# print encrypted text
print("Original file contents:")
print(text)
2021-11-12 04:14:40 +00:00
# encrypt the file
encrypted_text = encrypt(str.encode(text), key)
# print encrypted text
2021-11-12 04:18:05 +00:00
print("\nEncrypted file created. Contents:")
2021-11-12 04:14:40 +00:00
print(encrypted_text)
2021-11-12 04:18:05 +00:00
# decrypt and print decrypted text
print("\nDecrypted file. Contents:")
print(decrypt(encrypted_text, key))
2021-11-12 04:14:40 +00:00
if __name__ == '__main__':
main()