0

first post here, as to not waste your time, lets get right into it: Is it possible to give a key generated by the cryptography.fernet module a name that is a earlier defined variable? Example:

# import required module
import os
from cryptography.fernet import Fernet
from tkinter import *
from tkinter.filedialog import askopenfilename
Tk().withdraw() # we don't want a full GUI, so keep the root window from appearing
filepath = askopenfilename() # show an "Open" dialog box and return the path to the selected file
var1 = (os.path.basename(filepath)) # cuts the filepath into a filename
# key generation
key = Fernet.generate_key()
# string the key in a file
with open('filekey.key','wb') as filekey:
    filekey.write(key)
# opening key
with open('filekey.key', 'rb') as filekey:
    key = filekey.read()
# using the generated key
fernet = Fernet(key)
# opening the original file to encrypt
with open(filepath, 'rb') as file:
    original = file.read()
# encrypting the file
encrypted = fernet.encrypt(original)
# opening the file in write mode and
# writing the encrypted data
with open(filepath, 'wb') as encrypted_file:
    encrypted_file.write(encrypted)

My goal is to give the generated key the output of the var1 variable as a name.

  • It’s not clear what you mean by ‘give the key a name’. Are you talking about using a string from your file as a variable name? Or does this actually have something to do with all the other code and is specific to `Fernet`? – Mark Mar 20 '21 at 17:27
  • Sorry for being unclear, I want the keyfile to have the name of the var1 output. For example, I select a file "something\something\picture.jpg", the path of the file gets cut into the filename in row 8 >var1 = (os.path.basename(filepath))<. So in this case (var1=picture.jpg). My goal is to name the file that contains the key into var1.jpg.key (in this case picture.jpg.key). Hope that clears it up. – someoneelse Mar 20 '21 at 17:34
  • Sure. `open()` just takes a string. You can make the string you want by concatenation. `with open(var1 + '.key','wb')` – Mark Mar 20 '21 at 17:46
  • Wow, not only easy but also easy to understand, thank you very much! – someoneelse Mar 20 '21 at 17:50
  • Can you post your comment as an answer so i can mark it as solved? Or how does this work? – someoneelse Mar 20 '21 at 17:56

1 Answers1

0

"Sure. open() just takes a string. You can make the string you want by concatenation. with open(var1 + '.key','wb')"

Answered by Mark M in the comments.