I'm trying to get the encryption key from Google Chrome and I get an error saying:
line 13, in find_crypt
print(encrypt['encryption_key'])
KeyError: 'encryption_key'
The code is:
from genericpath import exists
import win32crypt
import json
import os
def find_crypt(path):
path = path.replace('\Default', '')
for file in os.listdir(path):
if file == 'Local State':
f = open('{0}\\{1}'.format(path, file), 'r', encoding='utf-8')
encrypt = json.load(f)
print(encrypt['encryption_key'])
def find_passwords(path):
for file in os.listdir(path):
if file == 'Login Data':
pass
def main():
local = os.getenv('LocalAppData')
roaming = os.getenv('AppData')
directories = {
'chrome' : local + '\\Google\\Chrome\\User Data\\Default'
}
for name, directory in directories.items():
if not os.path.exists(directory):
continue
else:
find_crypt(directory)
find_passwords(directory)
if __name__ == '__main__':
main()
The Local State File does not store any key with the name encryption_key but instead with encrypted_key.
That is why your Python Program yells [at the line 13] it cant find any key with the name encryption_key.
Also the encrypted_key is inside another object with the name os_crypt
Enough Talking, Here is the modified code :)
def find_crypt(path):
path = path.replace('\Default', '')
print(path)
for file in os.listdir(path):
if file == 'Local State':
f = open('{0}\\{1}'.format(path, file), 'r', encoding='utf-8')
encrypt = json.load(f)
print(encrypt['os_crypt']['encrypted_key'])
Related
I am attempting to use encryption key from my USB stick to decrypt a file on my computer.
The output I get from my current script (based on source: https://medium.com/codex/encrypting-your-files-using-a-usb-stick-as-the-key-python-e04b26657357) keeps throwing path errors. It can load the key but somehow doesnt decrypt the file on my computer. Can someone see where this error is coming from or how it can be solved?
I get the following output:
C:\Users\Asus\PycharmProjects\pythonProject220728usbkey\venv\Scripts\python.exe C:/Users/Asus/PycharmProjects/pythonProject220728usbkey/main.py
Trying to find key...
Key Found
Traceback (most recent call last):
File "C:\Users\Asus\PycharmProjects\pythonProject220728usbkey\main.py", line 68, in <module>
encryptFiles(key,files)
File "C:\Users\Asus\PycharmProjects\pythonProject220728usbkey\main.py", line 30, in encryptFiles
files = os.listdir(directory)
NotADirectoryError: [WinError 267] El nombre del directorio no es vĂ¡lido: 'C:\\Users\\Asus\\PycharmProjects\\pythonProject220728usbkey\\enc_levensonderhoud.xlsx'
Process finished with exit code 1
-------------------------------------------------------------------------------------#
#See my current script below:
import os
import wmi
from cryptography.fernet import Fernet
my_key = 'TICOZM'
files = r'C:\Users\Asus\PycharmProjects\pythonProject220728usbkey\enc_levensonderhoud.xlsx'
c = wmi.WMI()
def check_for_key():
for disk in c.Win32_LogicalDisk():
if disk.VolumeName==my_key:
return disk
def load_key(usbDisk):
port = usbDisk.DeviceID
try:
print('Trying to find key...')
with open(f'{port}\\encryptionKey.key','rb') as encryptKey:
key = encryptKey.read()
print('Key Found')
except:
print('Key not found... Creating a new key')
key = Fernet.generate_key()
with open(f'{port}\\encryptionKey.key','wb') as encryptKey:
encryptKey.write(key)
return key
def encryptFiles(key,directory):
files = os.listdir(directory)
cipher = Fernet(key)
global state
state = 'encrypted'
for file in files:
with open(f'{directory}\{file}','rb') as old:
original = old.read()
encrypted = cipher.encrypt(original)
with open(f'{directory}\{file}','wb') as old:
old.write(encrypted)
def decryptFiles(key, directory):
files = os.listdir(directory)
cipher = Fernet(key)
global state
state = 'decrypted'
for file in files:
with open(f'{directory}\{file}', 'rb') as old:
encrypted = old.read()
decrypted = cipher.decrypt(encrypted)
with open(f'{directory}\{file}', 'wb') as old:
old.write(decrypted)
state = 'decrypted'
if __name__=='__main__':
while True:
disk = check_for_key()
try:
key = load_key(disk)
except:
print('No Key Available')
if disk!=None:
current_state = 'decrypted'
if current_state!=state:
decryptFiles(key,files)
else:
current_state = 'encrypted'
if current_state!=state:
encryptFiles(key,files)
I'm working on a function where I need to open a file e.g. "hello.txt" by passing a variable name that contains a directory of where the file is located instead of the file name. Below is a dummy code that I have designed for this. In short I need to be able to open a file which is located in that directory by passing a directory name as you can see in updated.
def folder_things():
path = 'C:\\Users\\blazh\\Documents\\Vladyslav\\City-Project\\Python\\'
folder_code = "518Z%"
updated = path + folder_code
cwd = os.listdir(updated)
print("You have:", cwd)
st = ""
for x in cwd:
st += x
print(st)
# BECOMES A STRING
str(st)
print(type(st))
print(st)
final = ("'"+st+"'")
f = open(st, "r")
print(f)
I hope this answers your question. Not sure why your code is so repetitive.
def open_file(path:str) -> None:
try:
with open(path, "r") as file:
#do stuff with file
for line in file:
print(line)
except FileNotFoundError:
print(f"File was not found in path: {path}.")
if __name__ == "__main__":
path = "C:\\Users\\dejon\\Desktop\\Python Training\\demo.txt"
open_file(path)
I am trying to search for .txt files in a specified folder and encrypt each one of the .txt files found using my encryption algorithms. However I cannot seem to be able to figure out how to encrypt all the .txt files found within the folder and rename them
this is the code I am working with currently
import time, os, sys, encrypt, decrypt, caesarCipher, reverseCipher, vigenereCipher, glob
def main():
outputFilename = 'ABC.encrypted.txt'
mKey = 5
myMode = 'encrypt'
for root, dirs, files in os.walk('/Ransom'):
for file in files:
if file.endswith((".txt")):
inputFilename = os.path.join(root, file)
if not os.path.exists(inputFilename):
print('The file %s does not exist. Exiting....' % (inputFilename))
sys.exit()
fileObj = open(inputFilename)
content = fileObj.read()
fileObj.close()
print ('%sing...' % (myMode.title()))
startTime = time.time()
if myMode == 'encrypt':
translated = encrypt.encryptMess(mKey, content, myMode)
elif myMode == 'decrypt':
translated = decrypt.decryptMess(mKey, content, myMode)
outputFileObj = open(outputFilename, 'w')
outputFileObj.write(translated)
outputFileObj.close()
print('Done %sing %s (%s characters).' % (myMode, inputFilename, len(content)))
print('%sed file is %s.' % (myMode.title(), outputFilename))
if __name__ == '__main__':
main()
I really appreciate any help to guide me into achieving this.
This code iterates over all the files in a given folder and calls a designated method whenever the file is '*.txt'
import os
baseUrl = './'
def encryptFile(filename):
# process one file here
print baseUrl + filename
alist = next(os.walk(baseUrl))[2]
for i in xrange(len(alist)):
afile = alist[i]
if afile[-4:] == '.txt':
encryptFile(afile)
I am trying to write a script that tracks for changes made in directories/files set to multiple file paths created by an installer. I found Thomas Sileo's DirTools project on git, modified it, but am now running into some issues when writing/reading from JSON:
1) First, I believe that I am writing to JSON incorrectly and am finding that my create_state() function is only writing the last path I need.
2) If I get it working, I am unable to read/parse the file like I was before. I usually get ValueError: Extra data errors
Code below:
import os import json import getpass
files = [] subdirs = []
USER = getpass.getuser()
pathMac = ['/Applications/',
'/Users/' + USER + '/Documents/' ]
def create_dir_index(path):
files = []
subdirs = []
for root, dirs, filenames in os.walk(path):
for subdir in dirs:
subdirs.append(os.path.relpath(os.path.join(root, subdir), path))
for f in filenames:
files.append(os.path.relpath(os.path.join(root, f), path))
return dict(files=files, subdirs=subdirs)
def create_state(): for count in xrange(len(pathMac)):
dir_state = create_dir_index(pathMac[count])
out_file = open("Manifest.json", "w")
json.dump(dir_state, out_file)
out_file.close()
def compare_states(dir_base, dir_cmp):
'''
return a comparison two manifest json files
'''
data = {}
data['deleted'] = list(set(dir_cmp['files']) - set(dir_base['files']))
data['created'] = list(set(dir_base['files']) - set(dir_cmp['files']))
data['deleted_dirs'] = list(set(dir_cmp['subdirs']) - set(dir_base['subdirs']))
data['created_dirs'] = list(set(dir_base['subdirs']) - set(dir_cmp['subdirs']))
return data
if __name__ == '__main__':
response = raw_input("Would you like to Compare or Create? ")
if response == "Create":
# CREATE MANIFEST json file
create_state()
print "Manifest file created."
elif response == "Compare":
# create the CURRENT state of all indexes in pathMac and write to json file
for count in xrange(len(pathMac)):
dir_state = create_dir_index(pathMac[count])
out_file = open("CurrentState.json", "w")
json.dump(dir_state, out_file)
out_file.close()
# Open and Load the contents from the file into dictionaries
manifest = json.load(open("Manifest.json", "r"))
current = json.load(open("CurrentState.json", "r"))
print compare_states(current, manifest)
I am trying to read print search for all files in a directory and store contents in each file in a list to be used.
My problem is when i use print to debug if the file exists, it prints out the current file or first file in the list. However, It complains that file is not found when i try to read from this file
import re
import os
# Program to extract emails from text files
def path_file():
#path = raw_input("Please enter path to file:\n> ")
path = '/home/holy/thinker/leads/'
return os.listdir('/home/holy/thinker/leads') # returns a list like ["file1.txt", 'image.gif'] # need to remove trailing slashes
# read a file as 1 big string
def in_file():
print path_file()
content = []
for a_file in path_file(): # ['add.txt', 'email.txt']
print a_file
fin = open(a_file, 'r')
content.append(fin.read()) # store content of each file
print content
fin.close()
return content
print in_file()
# this is the error i get
""" ['add.txt', 'email.txt']
add.txt
Traceback (most recent call last):
File "Extractor.py", line 24, in <module>
print in_file()
File "Extractor.py", line 17, in in_file
fin = open(a_file, 'r')
IOError: [Errno 2] No such file or directory: 'add.txt'
"""
The error I get is aboive
os.listdir will return you only file name. You have to directory name on before that file name.
Its trying to open add.txt in same directory where you ran your program. Please add directory name before file name.
def path_file():
#path = raw_input("Please enter path to file:\n> ")
path = '/home/holy/thinker/leads/'
return [os.path.join(path, x) for x in os.listdir(path)]
you should use the full path of the file you want to read.
so please do fin = open(os.path.join(r'/home/holy/thinker/leads/', a_file), 'r')
Here's a rewrite using glob to limit which files are considered;
import glob
import os
import re
import sys
if sys.hexversion < 0x3000000:
# Python 2.x
inp = raw_input
else:
# Python 3.xrange
inp = input
def get_dir(prompt):
while True:
dir_name = inp(prompt)
dir_name = os.path.join(os.getcwd(), dir_name)
if os.path.isdir(dir_name):
return dir_name
else:
print("{} does not exist or is not a directory".format(dir_name))
def files_in_dir(dir_name, file_spec="*.txt"):
return glob.glob(os.path.join(dir_name, file_spec))
def file_iter(files):
for fname in files:
with open(fname) as inf:
yield fname, inf.read()
def main():
email_dir = get_dir("Please enter email directory: ")
email_files = files_in_dir(email_dir, "*.eml")
print(email_files)
content = [txt for fname,txt in file_iter(email_files)]
print(content)
if __name__=="__main__":
main()
and a trial run looks like
Please enter email directory: c:\temp
['c:\\temp\\file1.eml', 'c:\\temp\\file2.eml']
['file1 line one\nfile1 line two\nfile1 line three',
'file2 line one\nfile2 line two']