Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import hashlib
- """
- A gift from ki113d to feudin :)
- I thought I would show you a... cleaner
- more OOP approach to your last example
- in Rhynos thread.
- """
- class LoginDetails:
- """ Example class, not much use really. """
- def __init__(self, username, passwd):
- """ Constructor.
- Creates member variables used later.
- """
- self.username = username
- self.password = passwd
- def __getEncType(self, encType):
- """ This is a private method, only way to access
- it from outside the class is as follows.
- ld = LoginDetails(foo, bar)
- ld._LoginDetails__getEncType('md5')
- This method uses a hardcoded dictionary to
- determine what encryption type to use
- depending on the parameter.
- The key for the dictionary is the name
- of a hash algorithm,
- The value is an object used in encryption.
- It's better then swapping names around etc.
- """
- hashes = {'md5': hashlib.md5(),
- 'sha1': hashlib.sha1(),
- 'sha224': hashlib.sha224(),
- 'sha256': hashlib.sha256()}
- if not encType in hashes.keys():
- # The key is not in the dictionary so let the programmer who
- # is using the class know he is a douche and should read the
- # documentation on the api a bit better :P
- raise Exception("Hash algorithm {0} isn't supported!".format(
- encType))
- return hashes[encType]
- def encryptData(self, encType='md5'):
- """ The only public method of the class.
- This method encrypts and returns the
- username and password which were specified
- in the constructor whilst creating the class.
- encType is defaulted to md5 but can be changed.
- """
- # Retrieve an object used to encrypt the information
- h1 = self.__getEncType(encType)
- # Literally copy the object so we can encrypt a second piece
- # of data without calling __getEncType again.
- h2 = h1
- # h1.update(str) just adds to the string that needs to be encrypted.
- h1.update(str.encode(self.username))
- h2.update(str.encode(self.password))
- # Return a list containing the username and password.
- return (h1.hexdigest(), h2.hexdigest())
- if __name__ == '__main__':
- username = input('Username: ')
- passwd = input('Password: ')
- ld = LoginDetails(username, passwd) # Initialize the object.
- # A list of encryption type, lol is the worlds best hash, it is
- # so good infact that it throws and error saying it isn't supported,
- # this was for testing purposes :P
- encToTry = ('md5', 'sha1', 'sha224', 'sha256', 'lol')
- # Iterate through the values of encToTry and attempt to encrypt
- # the username and password each time.
- for i in encToTry:
- try:
- data = ld.encryptData(i)
- # Print a cool message lol
- print("""
- {0}:
- Username: {1}
- Password: {2}
- """.format(i.upper(), data[0], data[1]))
- except Exception as e:
- # Obviously because lol isn't a hash algorithm...
- print(e)
Add Comment
Please, Sign In to add comment