|
| 1 | +fromcryptography.fernetimportFernet |
| 2 | +importos |
| 3 | + |
| 4 | + |
| 5 | +defwrite_key(): |
| 6 | +""" |
| 7 | + Generates a key and save it into a file |
| 8 | + """ |
| 9 | +key=Fernet.generate_key() |
| 10 | +withopen("key.key", "wb") askey_file: |
| 11 | +key_file.write(key) |
| 12 | + |
| 13 | +defload_key(): |
| 14 | +""" |
| 15 | + Loads the key from the current directory named `key.key` |
| 16 | + """ |
| 17 | +returnopen("key.key", "rb").read() |
| 18 | + |
| 19 | + |
| 20 | +defencrypt(filename, key): |
| 21 | +""" |
| 22 | + Given a filename (str) and key (bytes), it encrypts the file and write it |
| 23 | + """ |
| 24 | +f=Fernet(key) |
| 25 | +withopen(filename, "rb") asfile: |
| 26 | +# read all file data |
| 27 | +file_data=file.read() |
| 28 | +# encrypt data |
| 29 | +encrypted_data=f.encrypt(file_data) |
| 30 | +# write the encrypted file |
| 31 | +withopen(filename, "wb") asfile: |
| 32 | +file.write(encrypted_data) |
| 33 | + |
| 34 | + |
| 35 | +defdecrypt(filename, key): |
| 36 | +""" |
| 37 | + Given a filename (str) and key (bytes), it decrypts the file and write it |
| 38 | + """ |
| 39 | +f=Fernet(key) |
| 40 | +withopen(filename, "rb") asfile: |
| 41 | +# read the encrypted data |
| 42 | +encrypted_data=file.read() |
| 43 | +# decrypt data |
| 44 | +decrypted_data=f.decrypt(encrypted_data) |
| 45 | +# write the original file |
| 46 | +withopen(filename, "wb") asfile: |
| 47 | +file.write(decrypted_data) |
| 48 | + |
| 49 | + |
| 50 | +if__name__=="__main__": |
| 51 | +importargparse |
| 52 | +parser=argparse.ArgumentParser(description="Simple File Encryptor Script") |
| 53 | +parser.add_argument("file", help="File to encrypt/decrypt") |
| 54 | +parser.add_argument("-g", "--generate-key", dest="generate_key", action="store_true", |
| 55 | +help="Whether to generate a new key or use existing") |
| 56 | +parser.add_argument("-e", "--encrypt", action="store_true", |
| 57 | +help="Whether to encrypt the file, only -e or -d can be specified.") |
| 58 | +parser.add_argument("-d", "--decrypt", action="store_true", |
| 59 | +help="Whether to decrypt the file, only -e or -d can be specified.") |
| 60 | + |
| 61 | +args=parser.parse_args() |
| 62 | +file=args.file |
| 63 | +generate_key=args.generate_key |
| 64 | + |
| 65 | +ifgenerate_key: |
| 66 | +write_key() |
| 67 | +# load the key |
| 68 | +key=load_key() |
| 69 | + |
| 70 | +encrypt_=args.encrypt |
| 71 | +decrypt_=args.decrypt |
| 72 | + |
| 73 | +ifencrypt_anddecrypt_: |
| 74 | +raiseTypeError("Please specify whether you want to encrypt the file or decrypt it.") |
| 75 | +elifencrypt_: |
| 76 | +encrypt(file, key) |
| 77 | +elifdecrypt_: |
| 78 | +decrypt(file, key) |
| 79 | +else: |
| 80 | +raiseTypeError("Please specify whether you want to encrypt the file or decrypt it.") |
| 81 | + |
| 82 | + |
| 83 | + |
| 84 | + |
| 85 | + |
| 86 | + |
0 commit comments