# PA5 # Spencer Ochs from misc import * import crypt def load_words(filename,regexp): """Load the words from the file filename that match the regular expression regexp. Returns a list of matching words in the order they are in the file.""" f = open(filename, 'r') text = f.read() f.close() # findall() matches all occurrences of a regexp in text and returns as list #return re.findall(regexp, text) reComp = re.compile(regexp) reMatchList = [] # split text into list of words then populate the list with those words that match the passed in regexp for word in text.split('\n'): if reComp.match(word): reMatchList.append(word) return reMatchList def transform_reverse(str): """Returns a list with with the original string and the reversal of that string""" return [str, "".join(reversed(str))] def transform_capitalize(str): """Returns a list of all the possible ways to capitalize the input str""" strList = [] # create recursive calls with helper function where each call is a branch # where either the ith char in the list is upper case or lower case def recHelper(prevStr, string, strList): # base case if len(string) == 1: strList.append( prevStr + string.upper() ) strList.append( prevStr + string.lower() ) return strList # recursive case splits into two paths where one has first char of previous string capitalized, and the other where first char is lower case recHelper(prevStr + string[0].upper(), string[1:], strList) recHelper(prevStr + string[0].lower(), string[1:], strList) recHelper("", str, strList) return strList def transform_digits(str): """Returns a list of all the possible ways to replace letters with similar looking digits according to the mapping of dMap. Last elem of list is original word str""" dMap = { "o": "0", "i": "1", "l": "1", "z": "2", "e": "3", "a": "4", "s": "5", "t": "7", "b": "6", "B": "8" } strList = [] # mutable value that is changed by recHelper # helper function to check if char should be switched to digit def toDigit(c): if c in dMap: return dMap[c] else: return c # recursive helper function that, similar to the helper for # transform_capatalize(), recursively explores every path that either has # a letter replaced with its respective digit, or not. def recHelper(prevStr, string, strList): # base case if len(string) == 1: if string in dMap: # only take this path strList.append( prevStr + toDigit(string) ) strList.append( prevStr + string ) return strList # recursive case, only splits if char can be changed to digit if string[0] in dMap: # take care of case where char == B, branch for both "b" and "B" if string[0] == "B": # create branch for "b" -> "6" recHelper(prevStr + "6", string[1:], strList) recHelper(prevStr + toDigit(string[0]), string[1:], strList) recHelper(prevStr + string[0], string[1:], strList) # call helper function on strList recHelper("", str, strList) return strList def check_pass(plain,enc): """Check to see if the plaintext plain encrypts to the encrypted text enc, returns True or False""" return crypt.crypt(plain, enc[0:2]) == enc def load_passwd(filename): """Load the password file filename and returns a list of dictionaries with fields "account", "password", "UID", "GID", "GECOS", "directory", and "shell", each mapping to the corresponding field of the file.""" dictList = [] dictKeys = ["account","password","UID","GID","GECOS","directories","shell"] f = open(filename, 'r') text = f.read() f.close() lines = text.split('\n') for l in lines: if l != '': elems = l.split(':') dictList.append( make_dict(dictKeys, elems) ) return dictList def crack_pass_file(fn_pass,words,out): """Crack as many passwords in file fn_pass as possible using words in the file words""" #load files encryptedPasswords = load_passwd(fn_pass) # dictionary of fields words = load_words(words, r"\w{6,8}$") #matches 6 to 8 alphanumeric chars crackedPasswords = [] outputFile = open(out, 'w') # file to write cracked passwords to # crack untransformed strings first for d in encryptedPasswords: for w in words: if( check_pass(w, d['password']) ): # write "username=pass" outputFile.write( '{}={}\n'.format(d['account'], w) ) encryptedPasswords.remove( d ) #remove entry from future cracks outputFile.flush() # output file flushed after each line # crack reversed words next in the smaller list of dictionaries for d in encryptedPasswords: for w in words: if( check_pass( transform_reverse(w)[1], d['password'] ) ): outputFile.write( '{}={}\n'.format(d['account'], w) ) encryptedPasswords.remove( d ) outputFile.flush() # crack words with some letters capitalized for d in encryptedPasswords: for w in words: capWords = transform_capitalize(w) capWords.pop() # last item in list is original word for cw in capWords: if( check_pass( cw, d['password'] ) ): outputFile.write( '{}={}\n'.format(d['account'], cw) ) encryptedPasswords.remove( d ) outputFile.flush() # crack words with some letters transformed to digits for d in encryptedPasswords: for w in words: digitWords = transform_digits(w) digitWords.pop() # last item in list is original word for dw in digitWords: if( check_pass( dw, d['password'] ) ): outputFile.write( '{}={}\n'.format(d['account'], dw) ) encryptedPasswords.remove( d ) outputFile.flush() # crack words with some letters transformed to caps, some trans'd to digits # then check the reversed version of those transformed words #transWords = [] #for d in encryptedPasswords: # for w in words: # digitWords = transform_digits(w) # digitWords.pop() # last item in list is original word # for dw in digitWords: # capsDigitWords = transform_capitalize(dw) # transWords += capsDigitWords #store all # for cdw in capsDigitWords: # if( check_pass( cdw, d['password'] ) ): # outputFile.write( '{}={}\n'.format(d['account'], cdw) ) # encryptedPasswords.remove( d ) # outputFile.flush() # # check reversed version of capsDigitWord # cdrw = transform_reverse(cdw)[1] # if( check_pass( cdrw, d['password'] ) ): # outputFile.write( '{}={}\n'.format(d['account'], cdrw)) # encryptedPasswords.remove( d ) # outputFile.flush() for w in words: digitWords = transform_digits(w) digitWords.pop() # last item in list is original word for dw in digitWords: capsDigitWords = transform_capitalize(dw) for cdw in capsDigitWords: cdRw = transform_reverse(cdw)[1] # check unreversed capsDigitWords for d in encryptedPasswords: if( check_pass( cdw, d['password'] ) ): outputFile.write( '{}={}\n'.format(d['arush121_'], cdw) ) encryptedPasswords.remove( d ) outputFile.flush() # check reversed capsDigitWords for d in encryptedPasswords: if( check_pass( cdRw, d['password'] ) ): outputFile.write( '{}={}\n'.format(d['account'], cdRw) ) encryptedPasswords.remove( d ) outputFile.flush() # crack the reversed versions of the previous capsDigitWords #for d in encryptedPasswords: # for w in words: # rw = transform_reverse( w )[1] # reverse the word # digitReversedWords = transform_digits( rw ) # digitReversedWords.pop() # last item in list is plain reversed word # for drw in digitReversedWords: # capsDigitReversedWords = transform_capitalize(drw) # for cdrw in capsDigitReversedWords: # if( check_pass( cdrw, d['password'] ) ): # outputFile.write( '{}={}\n'.format(d['account'],cdrw) ) # encryptedPasswords.remove( d ) # outputFile.flush() # End crack_pass function outputFile.close()
Write, Run & Share Python code online using OneCompiler's Python online compiler for free. It's one of the robust, feature-rich online compilers for python language, supporting both the versions which are Python 3 and Python 2.7. Getting started with the OneCompiler's Python editor is easy and fast. The editor shows sample boilerplate code when you choose language as Python or Python2 and start coding.
OneCompiler's python online editor supports stdin and users can give inputs to programs using the STDIN textbox under the I/O tab. Following is a sample python program which takes name as input and print your name with hello.
import sys
name = sys.stdin.readline()
print("Hello "+ name)
Python is a very popular general-purpose programming language which was created by Guido van Rossum, and released in 1991. It is very popular for web development and you can build almost anything like mobile apps, web apps, tools, data analytics, machine learning etc. It is designed to be simple and easy like english language. It's is highly productive and efficient making it a very popular language.
When ever you want to perform a set of operations based on a condition IF-ELSE is used.
if conditional-expression
#code
elif conditional-expression
#code
else:
#code
Indentation is very important in Python, make sure the indentation is followed correctly
For loop is used to iterate over arrays(list, tuple, set, dictionary) or strings.
mylist=("Iphone","Pixel","Samsung")
for i in mylist:
print(i)
While is also used to iterate a set of statements based on a condition. Usually while is preferred when number of iterations are not known in advance.
while condition
#code
There are four types of collections in Python.
List is a collection which is ordered and can be changed. Lists are specified in square brackets.
mylist=["iPhone","Pixel","Samsung"]
print(mylist)
Tuple is a collection which is ordered and can not be changed. Tuples are specified in round brackets.
myTuple=("iPhone","Pixel","Samsung")
print(myTuple)
Below throws an error if you assign another value to tuple again.
myTuple=("iPhone","Pixel","Samsung")
print(myTuple)
myTuple[1]="onePlus"
print(myTuple)
Set is a collection which is unordered and unindexed. Sets are specified in curly brackets.
myset = {"iPhone","Pixel","Samsung"}
print(myset)
Dictionary is a collection of key value pairs which is unordered, can be changed, and indexed. They are written in curly brackets with key - value pairs.
mydict = {
"brand" :"iPhone",
"model": "iPhone 11"
}
print(mydict)
Following are the libraries supported by OneCompiler's Python compiler
Name | Description |
---|---|
NumPy | NumPy python library helps users to work on arrays with ease |
SciPy | SciPy is a scientific computation library which depends on NumPy for convenient and fast N-dimensional array manipulation |
SKLearn/Scikit-learn | Scikit-learn or Scikit-learn is the most useful library for machine learning in Python |
Pandas | Pandas is the most efficient Python library for data manipulation and analysis |
DOcplex | DOcplex is IBM Decision Optimization CPLEX Modeling for Python, is a library composed of Mathematical Programming Modeling and Constraint Programming Modeling |