Question

In: Computer Science

In Python, create a program with 2 classes that do the following. HashCreate class, this class...

In Python, create a program with 2 classes that do the following.

HashCreate class, this class will accept a directory and hash each file in the directory and store the results in a dictionary. The dictionary will contain the hash value and file name.

HashVerify, the second class will accept the dictionary as input and save that in an instance attribute. This class must also contain a method for lookups that require a file path as input. The lookup method will hash the file and lookup in the dictionary to see if the hash exists. If the hash exists, the lookup method will return true and a file name associated with it.

Solutions

Expert Solution

Hi,

As it's not mentioned as to which hashing algorithm needs to be used, I have used md5 for hashing.

I am posting here the screen shot of the source code followed by the actual source code and test run output which confirms that the code is working fine.

Source code:

import hashlib, os
from os import listdir, getcwd
from os.path import isfile, join, normpath

#dictionary to store the hash value and file name
HashDict = {}

class HashCreate:
   def __init__(self, directory=""):
       if not directory:   #checking if the directory is empty
           print("directory name is empty!")
           return
       if not os.path.exists (directory):   #checking if the directory exists
           print("Can't find directory: " + directory)
           return

       current_path = normpath(directory) #normalising the path
       #obtaining list of files in the directory
       filenames = [f for f in listdir(current_path) if isfile(join(current_path, f))]

       global HashDict
       #creating the hash of each file and updating hash and file name in global hash dictionary
       for filename in filenames:
           filepath = join(current_path, filename)
           HashDict[self.md5(filepath)] = filename

   # method to create md5 hash
   def md5(self, fname):
       hash_md5 = hashlib.md5()
       with open(fname, "rb") as f:
           for chunk in iter(lambda: f.read(2 ** 20), b""):
               hash_md5.update(chunk)
       return hash_md5.hexdigest()

class HashVerify:
   def __init__(self, hashDict = {}):
       #taking hashdict and storing in instance attribute of HashVerify
       self.HashDict = hashDict

   #method to lookup the hash of the file specified by the file path and return as mentioned in the question
   def lookup(self, filepath = ""):
       if not filepath:   #checking if filepath is empty
           print("file path is empty!")
           return False, ""
       if not os.path.exists(filepath):   #checking if filepath exists
           print("Can't find directory: " + filepath)
           return False, ""
       fileHash = self.md5(filepath)   #calculating md5 hash of the file

       if fileHash in self.HashDict:   #checking if the hash exists in the hash dict
           return True, self.HashDict[fileHash]   #returning True and file name as hash exists
       else:
           return False, ""   #returning False and empty file name as hash doesn't exist
          
   def md5(self, fname):
       hash_md5 = hashlib.md5()
       with open(fname, "rb") as f:
           for chunk in iter(lambda: f.read(2 ** 20), b""):
               hash_md5.update(chunk)
       return hash_md5.hexdigest()

#Testing the two classes
#Please replace the directory name with a directory in your local computer
H1 = HashCreate("/Users/skotak455/Documents/TestPrograms/single_LL")
print("HashDict: ")
print(HashDict)
H2 = HashVerify(HashDict)

#Please replace the filepath with a file in your local computer
verified, file = H2.lookup("/Users/skotak455/Documents/TestPrograms/single_LL/a.out")
if verified:
   print("File is verified, file name: " + file)
else:
   print("Can't lookup the file path")

Test run output:

Thank you!!


Related Solutions

Classes and Objects Write a program that will create two classes; Services and Supplies. Class Services...
Classes and Objects Write a program that will create two classes; Services and Supplies. Class Services should have two private attributes numberOfHours and ratePerHour of type float. Class Supplies should also have two private attributes numberOfItems and pricePerItem of type float. For each class, provide its getter and setter functions, and a constructor that will take the two of its private attributes. Create method calculateSales() for each class that will calculate the cost accrued. For example, the cost accrued for...
In python using tkinter, I want to create a program. The program can have various classes...
In python using tkinter, I want to create a program. The program can have various classes and methods but I want it to have circles, triangles, and squares. Each shape movies in a certain way, like circles can move linearly, triangles can be affected by gravity, and squares can only go up and down. If the shapes get too close to one another then they disappear and a new shape appears somewhere else. I want this program to run continuously.
PYTHON-- trying to teach myself how to create new classes. The Bird class will read a...
PYTHON-- trying to teach myself how to create new classes. The Bird class will read a file that has a list of species and will write to another file with the species and # of occurrences . use __lt__ to compare species and use #comments to explain the def methods in the class example of input file: blackbird canary hummingbird canary hummingbird canary output file: Blackbird,1 Hummingbird,2 Canary,3 class Birds: #do i need count in init? def __init__(self, species, count):...
How to do this in Python (using Lists): Create a python program that allows a user...
How to do this in Python (using Lists): Create a python program that allows a user to display, sort and update as needed a List of U.S States containing the State Capital and State Bird. You will need to embed the State data into your Python code. The user interface will allow the user to perform the following functions: 1. Display all U.S. States in Alphabetical order along with Capital and Bird 2. Search for a specific state and display...
Write a python program using the following requirements: Create a class called Sentence which has a...
Write a python program using the following requirements: Create a class called Sentence which has a constructor that takes a sentence string as input. The default value for the constructor should be an empty string The sentence must be a private attribute in the class contains the following class methods: get_all_words — Returns all the words in the sentence as a list get_word — Returns only the word at a particular index in the sentence Arguments: index set_word — Changes...
Create a moderately complex java program that utilises 2 or more classes. Within these classes: -...
Create a moderately complex java program that utilises 2 or more classes. Within these classes: - have one that defines an exception - have that exception throw(n) in one method and handled in another -has the program continue even if the user inputs incorrect data -be creative/unique in some way
Create a Python script in IDLE or Kali Python3 CLI to create the following Python Program:...
Create a Python script in IDLE or Kali Python3 CLI to create the following Python Program: Your program will create a username of your choice using a Kali Linux command "useradd -m mark", then set the password for that user using the Kali Linux Command "echo "mark:10101111" | chpasswd". Then you create a dictionary file using the Kali Linux command "crunch 8 8 01 > mylist.txt" Your python script should crack the password for that user and display on the...
Create a preorder iterator for the class binarytree from the Python program below. class Binarytree: def...
Create a preorder iterator for the class binarytree from the Python program below. class Binarytree: def __init__(self, DataObject): self.data = DataObject self.parents = None self.left_child = None self.right_child = None @property def left_child(self): return self.__left_child @left_child.setter def left_child(self, node): self.__left_child = node if node is not None: node.parents = self @property def right_child(self): return self.__right_child @right_child.setter def right_child(self, node): self.__right_child = node if node is not None: node.parents = self def is_leafNode(self): if self.left_child is None and self.right_child is None:...
Objective: Create a program that uses the methods in the String and Math classes to do...
Objective: Create a program that uses the methods in the String and Math classes to do the following: Ask the user to enter two nouns Tell the user how many letters the nouns are from eachother in the dictionary. Tell the user the last letter of each of the nouns Tell the user the position of the letter "e" in each of the nouns, -1 if no "e" exists in the word. For full credit, you must use quotations around...
Write a Java program such that it consists of 2 classes: 1. a class that serves...
Write a Java program such that it consists of 2 classes: 1. a class that serves as the driver (contains main()) 2. a class that contains multiple private methods that compute and display a. area of a triangle (need base and height) b area of a circle (use named constant for PI) (need radius) c. area of rectangle (width and length) d. area of a square (side) e. surface area of a solid cylinder (height and radius of base) N.B....
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT