def main3(): for i in range(1, 15): print(i, 'lib ->', decryptMessage(i, T1)) print(i, 'me ->', decrypt(i, T1, 89)) print(i, 'lib ->', decryptMessage(i, T2)) print(i, 'me ->', decrypt(i, T2, 86)) print(i, 'lib ->', decryptMessage(i, T3)) print(i, 'me ->', decrypt(i, T3, 93)) print('---')
def main2(): PLAINTEXT = 'Common sense is not so common.' for key in range(4, 10): en = encryptMessage(key, PLAINTEXT) print(key, ': encrypt -> ', en) de = decryptMessage(key, en) print(key, ': decrypt -> ', de) print('---') for i in range(1, 15): print(i, decryptMessage(i, T1)) print(i, decryptMessage(i, T2)) print(i, decryptMessage(i, T3)) print('---')
def main(): random.seed(42) # Set the random "seed" to a static value. for i in range(20): # Run 20 tests. message = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' * random.randint(4, 40) # Convert the message string to a list to shuffle it: message = list(message) random.shuffle(message) message = ''.join(message) # Convert the list back to a string. print('Test #%s: "%s..."' % (i + 1, message[:50])) # Check all possible keys for each message: for key in range(1, int(len(message)/2)): encrypted = transpositionEncrypt.encryptMessage(key, message) decrypted = transpositionDecrypt.decryptMessage(key, encrypted) # If the decryption doesn't match the original message, display # an error message and quit: if message != decrypted: print('Mismatch with key %s and message %s.' % (key, message)) print('Decrypted as: ' + decrypted) sys.exit() print('Transposition cipher test passed.')
def main(): random.seed(42) # set the random seed to a static value count = 0 for i in range(20): # run 20 tests # Generate random messages to test # The message will have a random length: message = 'ABCDEFGHIJKLMNOPQRSTUVWXY' * random.randint(4, 40) # Convert string to list to shuffle message = list(message) random.shuffle(message) # Change it back to a string message = ''.join(message) print('Test #%s: "%s..."' % (i+1, message[:50])) # Check all possible keys for each message. for key in range(1, len(message)): count += 1 encrypted = transpositionEncrypt.encryptMessage(key, message) decrypted = transpositionDecrypt.decryptMessage(key, encrypted) # If the decryption doesn't match original message, # display and error and quit. if message != decrypted: print('Mismatch with key %s and message %s.' % (key, message)) print(decrypted) sys.exit() print('Transposition cipher test passed.') print('Ran %d times.' % count)
def main(): inputFile = 'message.txt' outputFile = 'message.en.txt' decryptFile = 'message.de.txt' key = 10 if not os.path.exists(inputFile): print('The file %s dose not exist.' % (inputFile)) sys.exit() fileObj = open(inputFile) content = fileObj.read() fileObj.close() startTime = time.time() translated = encryptMessage(key, content) totalTime = round(time.time() - startTime, 2) outObj = open(outputFile, 'w') outObj.write(translated) outObj.close() fileEn = open(outputFile) content = fileEn.read() fileEn.close() decrypt = decryptMessage(key, content) outObj = open(decryptFile, 'w') outObj.write(decrypt) outObj.close()
def hackTransposition(message): print('Hacking...') print( '(Press Ctrl-C(on Windows) or Ctrl-D(on macOS and Linux) to quit at any time.)' ) # Brute-force by looping through every possible key: for key in range(1, len(message)): print('Trying key #%s...' % (key)) decryptedText = transpositionDecrypt.decryptMessage(key, message) if detect(decryptedText) is 'en': # Ask user if this is the correct decryption: print() print('Possible encryption hack:') print('Key %s: %s' % (key, decryptedText[:100])) print() print('Enter D if done, anything else to continue hacking:') response = input('> ') if response.strip().upper().startswith('D'): return decryptedText return None
def hackTransposition(message): print('Hacking...') # Python programs can be stopped at any time by pressing Ctrl-C (on # Windows) or Ctrl-D (on Mac and Linux) print('(Press Ctrl-C or Ctrl-D to quit at any time.)') # Brute-force by looping through every possible key. for key in range(1, len(message)): print('Trying key #%s...' % (key)) decryptedText = transpositionDecrypt.decryptMessage(key, message) if detectEnglish.isEnglish(decryptedText): # Ask user if this is the correct decryption. print() print('Possible encryption hack:') print('Key %s: %s' % (key, decryptedText[:100])) print() print('Enter D if done, anything else to continue hacking:') response = input('> ') if response.strip().upper().startswith('D'): return decryptedText return None
def hackTransposition(message): print('Hacking...') # Python programs can be stopped at any time by pressing Ctrl-C (on # Windows) or Ctrl-D (on Mac and Linux) print('(Press Ctrl-C or Ctrl-D to quit at any time.)') # brute-force by looping through every possible key for key in range(1, len(message)): print('Trying key #%s...' % (key)) decryptedText = transpositionDecrypt.decryptMessage(key, message) if detectEnglish.isEnglish(decryptedText): # Check with user to see if the decrypted key has been found. print() print('Possible encryption hack:') print('Key %s: %s' % (key, decryptedText[:100])) print() print('Enter D for done, or just press Enter to continue hacking:') response = input('> ') if response.strip().upper().startswith('D'): return decryptedText return None
def hackTransposition(message): print('Hacking...') # Python programs can be stopped at any time by pressing Ctrl-C (on # Windows) or Ctrl-D (on Mac and Linux) print('(Press Ctrl-C or Ctrl-D to quit at any time.)') for key in range(1, len(message)): print('Trying key #%s... ' % (key), end='') sys.stdout.flush() # We want to track the amount of time it takes to test a single key, # so we record the time in startTime. startTime = time.time() decryptedText = transpositionDecrypt.decryptMessage(key, message) englishPercentage = round( detectEnglish.getEnglishCount(decryptedText) * 100, 2) totalTime = round(time.time() - startTime, 3) print('Test time: %s seconds, ' % (totalTime), end='') sys.stdout.flush() # flush printed text to the screen print('Percent English: %s%%' % (englishPercentage)) if englishPercentage > 20: print() print('Key ' + str(key) + ': ' + decryptedText[:100]) print() print('Enter D for done, or just press Enter to continue:') response = input('> ') if response.strip().upper().startswith('D'): return decryptedText return None
def main(): inputFilename = '50360-0.encrypted.txt' outputFilename = '50360-0.decrypted.txt' myKey = 10 myMode = 'decrypt' if not os.path.exists(inputFilename): print('The file %s does not exist. Quitting..' % (inputFilename)) sys.exit() if os.path.exists(outputFilename): print('This will overwrite the file %s. (C)ontinue or (Q)uit)' % (outputFilename)) response = input('> ') if not response.lower().startswith('c'): sys.exit() fileObj = open(inputFilename) content = fileObj.read() fileObj.close() print('%sing...' % (myMode.title())) startTime = time.time() if myMode == 'encrypt': translated = transpositionEncrypt.encryptMessage(myKey, content) elif myMode == 'decrypt': translated = transpositionDecrypt.decryptMessage(myKey, content) totalTime = round(time.time() - startTime, 2) print('%sing time: %s seconds' % (myMode.title(), totalTime)) 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))
def main(): # static random number random.seed(42) # main loop for testing # range(128) means 128 checks for i in range(128): # creating string that has the lenght of 'ABC...' multiplied by # a random number from 4 to 200 message = 'ABCDEFGHIJKLMNOPQRSTUWXYZ1234567890' * random.randint( 4, 200) # converting string to list message = list(message) # generating random message from list random.shuffle(message) # back to string message = ''.join(message) # printing test number and data print('Test #%s: "%s..."' % (i + 1, message[:40])) # check all possible keys for each message for key in range(1, len(message)): encrypted = transpositionEncrypt.encryptMessage(key, message) decrypted = transpositionDecrypt.decryptMessage(key, encrypted) if message != decrypted: print('Mismatch with key %s and message %s.' % (key, message)) print(decrypted) sys.exit() print('Transportation cipher test passed.')
def main(): inputFilename = 'frankenstein.txt' outputFilename = inputFilename + '.transposcipher' myKey = 10 myMode = 'encrypt' if not os.path.exists(inputFilename): print('File "%s" does not exit. Quitting...' % inputFilename) sys.exit() if os.path.exists(outputFilename): print('This will overwrite "%s" (C)ontinue or (Q)uit?' % outputFilename) response = input('>') if not response.lower().startswith('c'): sys.exit() fileObj = open(inputFilename) content = fileObj.read() fileObj.close() print('%sing...' % (myMode.title())) startTime = time.time() if myMode == 'encrypt': translated = transpositionEncrypt.encryptMessage(myKey,content) elif myMode == 'decrypt': translated = transpositionDecrypt.decryptMessage(myKey,content) totalTime = round(time.time() - startTime, 2) print('%sion time: %s seconds' % (myMode.title(),totalTime)) 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))
def main(): random.seed(42) # Set the random 'seed' to a static value for i in range(20): # Run, say 20 tests # Generate random messages to test # The message will have random length message = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' * random.randint(4, 40) # Convert message string to a list to shuffle it message = list(message) random.shuffle(message) message = ''.join(message) # Convert the list back to a string print('TEST {}:"{}..."'.format(i + 1, message[:50])) # Check all possible keys for each message: for key in range(1, int(len(message) / 2)): encrypted = te.encryptMessage(key, message) decrypted = td.decryptMessage(key, encrypted) # If decryption doesn't match the original message, display # an error message and quit if message != decrypted: print('Mismatch with key {} and message {}'.format( key, message)) print('Decrypted as: ' + decrypted) sys.exit() print('Transposition cipher test passed')
def main(): random.seed(42) # set the random "seed" to a static value for i in range(20): # run 20 tests # Generate random messages to test. # The message will have a random length: message = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' * random.randint(4,40) # Convert the message string to a list to shuffle it. message = list(message) random.shuffle(message) message = ''.join(message) # convert list to string print('Test #%s: "%s..."'%(i+1, message[:50])) # Check all possible keys for each message. for key in (1, len(message)): encrypted = transpositionEncrypt.encryptMessage(key, message) decrypted = transpositionDecrypt.decryptMessage(key, encrypted) # If the decryption doesn't match the origional message, display # an error message and quit. if message != decrypted: print('Mistmatch with key %s and message %s.'%(key, message)) print(decrypted) sys.exit() print('Transposition cipher test passed.')
def main(): random.seed(42) #伪随机数生成算法从一个叫做种子的初始数字开始 #从一个种子产生的所有随机数字都是可预测的。 #你可以通过调用random.seed()函数重设Python的随机种子 #Python只有在random首次导入时才会产生‘不可预测’的随机数字, #因为这个种子被设为计算机的当前时钟的时间 #(具体来说就是自1970年1月1日起的秒数) for i in range(20): message = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' * random.randint(4, 40) #random.randint()函数接受两个整数参数,返回那两个整数之间(包括那两个整数本身)的一个随机整数 message = list(message) random.shuffle(message) #random.shuffle()函数接受一个列表参数,接着随机重新排列这个列表里的项。 #shuffle()不返回列表值,就地修改列表值 message = ''.join(message) print('Test #%s: "%s..."' % (i + 1, message[:50])) for key in range(1, len(message)): encrypted = transpositionEncrypt.encryptMessage(key, message) decrypted = transpositionDecrypt.decryptMessage(key, encrypted) if message != decrypted: print('Mismatch with key %s and message %s.' % (key, message)) print(decrypted) sys.exit() print('Transposition cipher test passed.')
def hackTransposition(message): print('Hacking...') # Python programs can be stopped at any time by pressing Ctrl-C (on # Windows) or Ctrl-D (on Mac and Linux) print('(Press Ctrl-C or Ctrl-D to quit at any time.)') for key in range(1, len(message)): print('Trying key # %s... ' % (key), end='') sys.stdout.flush() # We want to track the amount of time it takes to test a single key, # so we record the time in startTime. startTime = time.time() decryptedText = transpositionDecrypt.decryptMessage(key, message) englishPercentage = round(detectEnglish.getEnglishCount(decryptedText) * 100, 2) totalTime = round(time.time() - startTime, 3) print('Test time: %s seconds, ' % (totalTime), end='') sys.stdout.flush() # flush printed text to the screen print('Percent English: %s%%' % (englishPercentage)) if englishPercentage > 20: print() print('Key ' + str(key) + ': ' + decryptedText[:100]) print() print('Enter D for done, or just press Enter to continue:') response = input('> ') if response.strip().upper().startswith('D'): return decryptedText return None
def main(): random.seed(42) # set the random "seed" to a static value for i in range(10): # run 20 tests # Generate random messages to test. # The message will have a random length: message = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' * random.randint(4, 40) # Convert the message string to a list to shuffle it. message = list(message) random.shuffle(message) message = ''.join(message) # convert list to string print('Test #%s: "%s..."' % (i + 1, message[:50])) # Check all possible keys for each message. for key in range(1, len(message)): encrypted = transpositionEncrypt.encryptMessage(key, message) decrypted = transpositionDecrypt.decryptMessage(key, encrypted) # If the decryption doesn't match the original message, display # an error message and quit. if message != decrypted: print('Mismatch with key %s and message %s.' % (key, message)) print(decrypted) sys.exit() print('Transposition cipher test passed.')
def hackTransposition(message): print('Hacking...') # Python programs can be stopped at any time by pressing Ctrl-C (on # Windows) or Ctrl-D (on Mac and Linux) print('(Press Ctrl-C or Ctrl-D to quit at any time.)') # brute-force by looping through every possible key for key in range(1, len(message)): print('Trying key #%s...' % (key)) decryptedText = transpositionDecrypt.decryptMessage(key, message) if detectEnglish.isEnglish(decryptedText): # Check with user to see if the decrypted key has been found. print() print('Possible encryption hack:') print('Key %s: %s' % (key, decryptedText[:100])) #To be sure, this prints out the first 100 characters of the decryptedText print() print('Enter D for done, or just press Enter to continue hacking:') response = input('> ') """The strip() string method returns a version of the string that has any whitespace at the beginning and end of the string stripped out.""" if response.strip().upper().startswith('D'): #D for done return decryptedText return None
def main(): # Set the random "seed" to a static value. random.seed(42) for i in range(20): # Generate random messages to test message = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' * random.randint(4, 40) message = list(message) random.shuffle(message) # Convert the list back to a string. message = ''.join(message) print('Test #%s: "%s..."' % (i + 1, message[:50])) # Check all possible keys for each message: for key in range(1, int(len(message)/2)): encrypted = transpositionEncrypt.encryptMessage(key, message) decrypted = transpositionDecrypt.decryptMessage(key, encrypted) if message != decrypted: print('Mismatch with key %s and message %s.' % (key, message)) print ('Decrypted as: ' + decrypted) sys.exit() print('Transposition cipher test passed.')
def main(): mode = getMode() key = getKey() if not os.path.exists(inputFilename): print("Input file %s does not exist\nQuit" %(inputFilename)) sys.exit() if os.path.exists(outputFilename): print("This will over write the output file %s. (C)ontinue or (Q)uit" %(outputFilename)) response = input("> ") if not response.lower().startswith("c"): sys.exit() fileObj = open(inputFilename) content = fileObj.read() fileObj.close() print("%sing" %(mode.title())) startTime = time.time() if mode[0] == "E": translated = transpositionEncrypt.encryptMessage(key, content) elif mode[0] == "D": translated == transpositionDecrypt.decryptMessage(key, content) totalTime = round(time.time() - startTime, 2) print("%sion time: % seconds" % (mode.title(), totalTime)) outputFileObj = open(outputFilename, "w") outputFileObj.write(translated) outputFileObj.close() print('Done %sing %s (%s characters).' % (mode, inputFilename, len(content))) print("%sed file is %s" %(mode.title(), outputFilename))
def main(): random.seed(42) # Set a random seed for i in range(20): # Generate random message to test with random length message = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' * random.randint(4, 40) # Convert message into list and shuffle then back to string message = list(message) random.shuffle(message) message = ''.join(message) print(f'Test #{i+1}: "{message[:50]}..."') # Check all possible keys for each message for key in range(1, int(len(message)/2)): encrypted = transpositionEncrypt.encryptMessage(key, message) decrypted = transpositionDecrypt.decryptMessage(key, encrypted) # If decryption doesn't match, display error message and quit if message != decrypted: print(f'Mismatch with key: {key} and message: {message}') print(f'Decrypted as: {decrypted}') sys.exit() print('Transposition cipher test passed.')
def hackTransposition(message): print("Hacking...") print("(Press Ctrl-C to quit at any time)") for key in range(1, len(message) * 2): print("Trying key #%s" % (key), end=" ") sys.stdout.flush() startTime = time.time() decryptedText = transpositionDecrypt.decryptMessage(key, message) englishPercentage = round( detectEnglish.getEnglishCount(decryptedText) * 100, 5) totalTime = round(time.time() - startTime, 3) print("Test time: %s seconds, " % (totalTime), end="") sys.stdout.flush() # Flush printed text to the screen. print("Percent English: %s%%" % (englishPercentage)) if englishPercentage > 20: print() print("Key " + str(key) + ": " + decryptedText[:100]) print() print("Enter D if done, anything else to continue hacking:") response = input("> ") if response.strip().upper().startswith("D"): return decryptedText return None
def main(): inputFilename = "50360-0.encrypted.txt" outputFilename = "50360-0.decrypted.txt" myKey = 10 myMode = "decrypt" if not os.path.exists(inputFilename): print("The file %s does not exist. Quitting.." % (inputFilename)) sys.exit() if os.path.exists(outputFilename): print("This will overwrite the file %s. (C)ontinue or (Q)uit)" % (outputFilename)) response = input("> ") if not response.lower().startswith("c"): sys.exit() fileObj = open(inputFilename) content = fileObj.read() fileObj.close() print("%sing..." % (myMode.title())) startTime = time.time() if myMode == "encrypt": translated = transpositionEncrypt.encryptMessage(myKey, content) elif myMode == "decrypt": translated = transpositionDecrypt.decryptMessage(myKey, content) totalTime = round(time.time() - startTime, 2) print("%sing time: %s seconds" % (myMode.title(), totalTime)) 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))
def hackTransposition(message): print('Hacking...') # Python programs can be stopped at any time by presseing Ctrl-C(on Windows) # or Ctrl-D (on Mac and Linux)d print('(Press Crtl-C or Ctrl-D to quit any time.)') # brute-force by looping through every possible key for key in range(1, len(message)): print('Trying key #%s...' % (key)) decryptedText = transpositionDecrypt.decryptMessage(key, message) if detectEnglish.isEnglish(decryptedText): # Check with user to see if the decrypted key has been found. print() print('Possible encryption hack:') print('Key %s: %s' % (key, decryptedText[:100])) print() print('Enter D for done, or just press Enter to continue hacking:') response = input('> ') if response.strip().upper().startswith('D'): return decryptedText return None
def main(): # MUST be a Text File! # inputFilename = 'beowulf.txt' inputFilename = raw_input('Input File Name: ') # BE CAREFUL! If a file with the outputFilename name # already exists, this program will overwrite that file. #outputFilename = 'beowulf.encrypted.txt' outputFilename = raw_input('Output File Name: ') while True: key = raw_input('Enter Key: ') if key.isdigit(): key = int(key) break while True: mode = raw_input('Encrypt or Decrypt? ').lower() if mode.strip() == 'encrypt' or mode.strip() == 'decrypt': break # If the input file does not exist, then the program terminates early. if not os.path.exists(inputFilename): print 'The file %s does not exist. Quitting...' % (inputFilename) sys.exit() # If the output file already exists, give the user a chance to quit. if os.path.exists(outputFilename): print 'This will overwrite the file %s. (C)ontinue or (Q)uit?' % ( outputFilename) response = input('> ') if not response.lower().startswith('c'): sys.exit() # Read in the message from the input file fileObj = open(inputFilename) content = fileObj.read() fileObj.close() print '%sing...' % (mode.title()) # Measure how long the encryption/decryption takes. startTime = time.time() if mode == 'encrypt': translated = transpositionEncrypt.encryptMessage(key, content) elif mode == 'decrypt': translated = transpositionDecrypt.decryptMessage(key, content) totalTime = round(time.time() - startTime, 2) print '%sion time: %s seconds' % (mode.title(), totalTime) # Write out the translated message to the output file. outputFileObj = open(outputFilename, 'w') outputFileObj.write(translated) outputFileObj.close() print 'Done %sing %s (%s characters).' % (mode, inputFilename, len(content)) print '%sed file is %s.' % (mode.title(), outputFilename)
def main(): # MUST be a Text File! # inputFilename = 'beowulf.txt' inputFilename = raw_input('Input File Name: ') # BE CAREFUL! If a file with the outputFilename name # already exists, this program will overwrite that file. #outputFilename = 'beowulf.encrypted.txt' outputFilename = raw_input('Output File Name: ') while True: key = raw_input('Enter Key: ') if key.isdigit(): key = int(key) break while True: mode = raw_input('Encrypt or Decrypt? ').lower() if mode.strip() == 'encrypt' or mode.strip() == 'decrypt': break # If the input file does not exist, then the program terminates early. if not os.path.exists(inputFilename): print 'The file %s does not exist. Quitting...' % (inputFilename) sys.exit() # If the output file already exists, give the user a chance to quit. if os.path.exists(outputFilename): print 'This will overwrite the file %s. (C)ontinue or (Q)uit?' % (outputFilename) response = input('> ') if not response.lower().startswith('c'): sys.exit() # Read in the message from the input file fileObj = open(inputFilename) content = fileObj.read() fileObj.close() print'%sing...' % (mode.title()) # Measure how long the encryption/decryption takes. startTime = time.time() if mode == 'encrypt': translated = transpositionEncrypt.encryptMessage(key, content) elif mode == 'decrypt': translated = transpositionDecrypt.decryptMessage(key, content) totalTime = round(time.time() - startTime, 2) print '%sion time: %s seconds' % (mode.title(), totalTime) # Write out the translated message to the output file. outputFileObj = open(outputFilename, 'w') outputFileObj.write(translated) outputFileObj.close() print 'Done %sing %s (%s characters).' % (mode, inputFilename, len(content)) print '%sed file is %s.' % (mode.title(), outputFilename)
def main(): myMessage = """Cb b rssti aieih rooaopbrtnsceee er es no npfgcwu plri ch nitaalr eiuengiteehb(e1 hilincegeoamn fubehgtarndcstudmd nM eu eacBoltaetee oinebcdkyremdteghn.aa2r81a condari fmps" tad l t oisn sit u1rnd stara nvhn fs edbh ee,n e necrg6 8nmisv l nc muiftegiitm tutmg cm shSs9fcie ebintcaets h a ihda cctrhe ele 1O7 aaoem waoaatdahretnhechaopnooeapece9etfncdbgsoeb uuteitgna. rteoh add e,D7c1Etnpneehtn beete" evecoal lsfmcrl iu1cifgo ai. sl1rchdnheev sh meBd ies e9t)nh,htcnoecplrrh ,ide hmtlme. pheaLem,toeinfgn t e9yce da' eN eMp a ffn Fc1o ge eohg dere.eec s nfap yox hla yon. lnrnsreaBoa t,e eitsw il ulpbdofg BRe bwlmprraio po droB wtinue r Pieno nc ayieeto'lulcih sfnc ownaSserbereiaSm -eaiah, nnrttgcC maciiritvledastinideI nn rms iehn tsigaBmuoetcetias rn""" print transpositionDecrypt.decryptMessage(10, myMessage) hackedMessage = hackTransposition(myMessage) if hackedMessage == None: print("Failed to hack encryptoon.") else: print('Copying hacked message to clipboard:') print(hackedMessage) pyperclip.copy(hackedMessage)
def main(): inputFilename = 'frankenstein.encrypted.txt' outputFilename = 'frankenstein.decrypted.txt' myKey = 10 myMode = 'decrypt' if not os.path.exists(inputFilename): #使用os.path.exists()函数,我们可以检查某个文件名是否已经存在 print('The file %s does not exist.Quitting...' % (inputFilename)) sys.exit() else: print('This will overwrite the file %s. (C)ontinus or (Q)uit?' % (outputFilename)) response = input('>') if not response.lower().startswith('c'): #如果字符串参数可以在这个字符串开头找到,startswith()方法会返回True #同理还有endswith()方法 sys.exit() ''' fileObj = open(inputFilename) content = fileObj.read() fileObj.close() ''' with open(inputFilename) as fileObj: #open()函数返回“文件对象”数据类型的值 content = fileObj.read() #read()方法将返回一个字符串,包含这个文件里的所有文字 print('%sing...' % (myMode.title())) #title()方法使每个单词首字母大写 startTime = time.time() #time.time()函数会返回一个浮点值,表示自1970年1月1日起的秒数。 #这个时间点被称为Unix Epoch if myMode == 'encrypt': translated = transpositionEncrypt.encryptMessage(myKey, content) elif myMode == 'decrypt': translated = transpositionDecrypt.decryptMessage(myKey, content) totalTime = round(time.time() - startTime, 2) #计算程序进行了多长时间 print('%sion time: %s seconds' % (myMode.title(), totalTime)) with open(outputFilename, 'w') as outputFileObj: outputFileObj.write(translated) print("Done %sing %s (%s characters)." % (myMode, inputFilename, len(content))) print('%sed file is %s.' % (myMode.title(), outputFilename))
def main(): print('enter file name') inputFilename = input() # BE CAREFUL! If a file with the outputFilename name already exists, # this program will overwrite that file. print('enter key length') myKey = input() myKey = int(myKey) print('select encrypt or decrypt mode ') myMode = input() # set to 'encrypt' or 'decrypt' if myMode == 'encrypt': outputFilename = inputFilename+'encrypted.txt' elif myMode == 'decrypt': outputFilename = inputFilename+'decrypted.txt' # If the input file does not exist, then the program terminates early. if not os.path.exists(inputFilename): print('The file %s does not exist. Quitting...' % (inputFilename)) sys.exit() # If the output file already exists, give the user a chance to quit. if os.path.exists(outputFilename): print('This will overwrite the file %s. (C)ontinue or (Q)uit?' %(outputFilename)) response = input('> ') if not response.lower().startswith('c'): sys.exit() # Read in the message from the input file fileObj = open(inputFilename) content = fileObj.read() fileObj.close() print('%sing...' % (myMode.title())) # Measure how long the encryption/decryption takes. startTime = time.time() if myMode == 'encrypt': translated = TranspositionEncrypt.encryptMessage(myKey, content) elif myMode == 'decrypt': translated = transpositionDecrypt.decryptMessage(myKey, content) totalTime = round(time.time() - startTime, 2) print('%sion time: %s seconds' % (myMode.title(), totalTime)) # Write out the translated message to the output file. 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))
def execute_auto(): file = open("detail.txt", "r") myKey = 10 content = file.read() file.close() translated = transpositionDecrypt.decryptMessage(myKey, content) file = open("detail.txt", "w") file.write(translated) file.close() file = open("detail.txt", "r") str_info = file.read() #print(str_info) usernamereg = re.compile(r'!u@\S+') passwordreg = re.compile(r'//!p@\S+') username = usernamereg.search(str_info) password = passwordreg.search(str_info) usrstr = username.group()[3:] idtext.insert(INSERT, usrstr) passstr = password.group()[5:] passInput.insert(INSERT, passstr) file.close() display = Display(visible=0, size=(800, 600)) display.start() portal = webdriver.Firefox() portal.get("http://172.16.0.30:8090/httpclient.html") enter_user_id = portal.find_element_by_name("username") enter_pass = portal.find_element_by_name("password") enter_user_id.send_keys(usrstr) enter_pass.send_keys(passstr) portal.implicitly_wait(3) enter_pass.submit() #time.sleep(1) check = portal.find_element_by_tag_name('xmp') if check.text == "You have successfully logged in": status.config(text="Logged in") elif check.text == "The system could not log you on. Make sure your password is correct": status.config(text="Try Again") else: status.config(text="Data Limit Exceeded") portal.quit() file = open("detail.txt", "r") content = file.read() file.close() translated = transpositionEncrypt.encryptMessage(myKey, content) file = open("detail.txt", "w") file.write(translated) file.close()
def hackTransposition(message): print("Hacking...") for key in range(1, len(message)): print("Trying key #%s..." % (key)) decryptedText = transpositionDecrypt.decryptMessage(key, message) if detectEnglish.isEnglish(decryptedText): CipherName = ("Transposition cipher with key of {}".format(key)) EnglishMSG = ("key {}: {}".format(key, decryptedText[:100])) EnglishDetected(CipherName, EnglishMSG, File)
def main(): # inputFilename = 'frankenstein.txt' inputFilename = 'frankenstein.encrypted.txt' # NOTE: outputFilename will overwrite an existing file. # outputFilename = 'frankenstein.encrypted.txt' outputFilename = 'frankenstein.decrypted.txt' myKey = 10 # myMode = 'encrypt' myMode = 'decrypt' # If the input file doesn't exist, the program will exit. if not os.path.exists(inputFilename): print('The file %s does not exist. Quitting....' % inputFilename) sys.exit() # If the output file already exists, let the user quit. if os.path.exists(outputFilename): print('This will overwrite the file %s. (C)ontinue or (Q)uit?' % outputFilename) response = input('> ') if not response.lower().startswith('c'): sys.exit() # Read in the message from input file fileObj = open(inputFilename) content = fileObj.read() fileObj.close() print('%sing...' % myMode.title()) # Measure how long the encryption/decryption takes. startTime = time.time() if myMode == 'encrypt': translated = transpositionEncrypt.encryptMessage(myKey, content) elif myMode == 'decrypt': translated = transpositionDecrypt.decryptMessage(myKey, content) totalTime = round(time.time() - startTime, 2) print('%sion time: %s secods' % (myMode.title(), totalTime)) # Write out the translated message to output file. outputFileObj = open(outputFilename, 'w') outputFileObj.write(translated) outputFileObj.close() print('Done %sing %s (%s characters).' % (myMode, inputFilename, len(content)))
def main(): random.seed(42) for i in range(20): message = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' * random.randint(4, 40) message = list(message) random.shuffle(message) message = ''.join(message) print('Test #%s: "%s..."' % (i + 1, message[:50])) for key in range(1, len(message)): encrypted = transpositionEncrypt.encryptMessage(key, message) decrypted = transpositionDecrypt.decryptMessage(key, encrypted) if message != decrypted: print('Mismatch with key %s and message %s.' % (key, message)) print(decrypted) sys.exit() print('Transposition cipher test passed')
def hackTransposition(message): print("Hacking...") for key in range(1, len(message)): print("Trying key #%s..." % key) decryptedText = transpositionDecrypt.decryptMessage(key, message) # print("DEBUG: %s" % decryptedText) if detectEnglish.isEnglish(decryptedText): print("\nPossible encryption hack") print("Key %s: %s\n" % (key, decryptedText[:100])) print("Enter D for done or ENTER to continue hacking.") response = input(">") if response.strip().upper().startswith("D"): return decryptedText return None
def hackTransposition(message): print("Hacking...") for key in range(1,len(message)): print("Trying key #%s..." % key) decryptedText = transpositionDecrypt.decryptMessage(key,message) #print("DEBUG: %s" % decryptedText) if detectEnglish.isEnglish(decryptedText): print('\nPossible encryption hack') print('Key %s: %s\n' %(key,decryptedText[:100])) print('Enter D for done or ENTER to continue hacking.') response = input('>') if response.strip().upper().startswith('D'): return decryptedText return None
def main(): random.seed(42) for i in range(20): message = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' * random.randint(4,40) message = list(message) random.shuffle(message) message = ''.join(message) print('Test #%s: "%s..."' % (i+1, message[:50])) for key in range(1,len(message)): encrypted = transpositionEncrypt.encryptMessage(key,message) decrypted = transpositionDecrypt.decryptMessage(key,encrypted) if message!=decrypted: print('Mismatch with key %s and message %s.' %(key, message)) print(decrypted) sys.exit() print('Transposition cipher test passed')
def hackTransposition(message): print('Hacking...') print('Press Ctrl-C (Win) or Ctrl-D (X-os) to quit.') for key in range(1,len(message)): print('Trying key #%s...' %(key)) decryptedText = transpositionDecrypt.decryptMessage(key,message) if detectEnglish.isEnglish(decryptedText): print() print('Possible encryption hack:') print('Key %s: %s' %(key, decryptedText[:100])) print() print('Enter D for done, or just press Enter to continue hacking:') response = input('> ') if response.strip().upper().startswith('D'): return decryptedText return None
def main(): inputFilename = input("Please enter a filename: ") # BE CAREFUL! If a file with the outputFilename name already exists. # this program program will overwrite that file. myKey = input("Please choose a key: ") myKey = int(myKey) myMode = input("Please enter a mode: ") outputFilename = "%s.%s.txt" % (inputFilename, myMode) #If the input file does not exist, then the program terminates early. if not os.path.exists(inputFilename): print("The file %s does not exist. Quitting...." % (inputFilename)) sys.exit() # If the output file already exists, give the user a chance to quit if os.path.exists(outputFilename): print("This will overwrite the file %s. (C)ontinue or (Q)uit?" % (outputFilename)) response = input("> ") if not response.lower().startswith("c"): sys.exit() # Read the message from the input file fileObj = open(inputFilename) content = fileObj.read() fileObj.close() print("%sing..." % (myMode.title())) # Measure how long the encryption/decryption takes. startTime = time.time() if myMode == "encrypt": translated = transpositionEncrypt.encryptMessage(myKey, content) elif myMode == "decrypt": translated = transpositionDecrypt.decryptMessage(myKey, content) totalTime = round(time.time() - startTime, 2) print("%sion time: %s seconds" % (myMode.title(), totalTime)) # write out the translated message to the output file outputFileObj = open(outputFilename, "w") outputFileObj.write(translated) outputFileObj.close() print("Done %sing %s (%s character)." % (myMode, inputFilename, len(content))) print("%sed file is %s. " % (myMode.title(), outputFilename))
def main(): print(">> BRUTE FORCE TRANSPOSITON CIPHER FILE DECRYPTION PROGRAM <<") print("Write the name of the file you want to decrypt: ") inputFileName = input('> ') fileExist = os.path.exists(inputFileName) while not fileExist: print('The file %s does not exist. Quitting...' % (inputFileName)) print('Do you want to try again? (C)ontiue or (Q)uit') inputFileName = input('> ') fileExist = os.path.exists(inputFileName) if not inputFileName.lower().startswith('c'): print('Quiting program...') sys.exit() outputFileName = 'decrypted-file.txt' if (os.path.exists(outputFileName)): print( "Previous decrypted file exists. Do you want to overwrite it? (Y)es/(N)o" ) response = input("> ") if not response.lower().startswith('y'): while (os.path.exists(outputFileName)): outputFileName = input('Please give a new name > ') fileObj = open(inputFileName) content = fileObj.read() fileObj.close() print('decrypting is on...') startTime = time.time() outputFileObj = open(outputFileName, 'w') for key in range(1, len(content)): translated = transpositionDecrypt.decryptMessage(key, content) is_english = detectHumLang.isEnglish(translated, 80, 80) if (is_english): print("Key: %s; Message: %s" % (key, translated[0:40])) outputFileObj.write("Key: %s" % (key)) outputFileObj.write(translated) outputFileObj.write('\n\n\n') outputFileObj.close() totalTime = round(time.time() - startTime, 2) print("Decrypting time: %s seconds" % (totalTime))
def main(): inputFilename = 'frankenstein.txt' outputFilename = 'frankenstein.encrypted.txt' myKey = 10 myMode = 'encrypt' # set to 'encrypt' or 'decrypt' # If the input file does not exist, then the program terminates early. if not os.path.exists(inputFilename): print('The file %s does not exist. Quitting...' % (inputFilename)) sys.exit() # If the output file already exists, give the user a chance to quit. if os.path.exists(outputFilename): print('This will overwrite the file %s. (C)ontinue or (Q)uit?' % (outputFilename)) response = input('> ') if not response.lower().startswith('c'): sys.exit() # Read in the message from the input file fileObj = open(inputFilename) content = fileObj.read() fileObj.close() print('%sing...' % (myMode.title())) # Measure how long the encryption/decryption takes. startTime = time.time() if myMode == 'encrypt': translated = transpositionEncrypt.encryptMessage(myKey, content) elif myMode == 'decrypt': translated = transpositionDecrypt.decryptMessage(myKey, content) print("--- %s seconds ---" % (time.time() - startTime)) # Write out the translated message to the output file. 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))
def main(): inputFilename = 'frankenstein.txt' # BE CAREFUL! If a file with the outputFilename already exists, # this programm will overwrite that file. outputFilename = 'frankenstein.encrypted.txt' myKey = 10 myMode = 'encrypt' # Set to 'encrypt' or 'decrypt' # If the input file does not exist, then the program terminates # early. if not os.path.exists(inputFilename): print('The file {0:s} does not exist. Quitting...'.format(inputFilename)) sys.exit() # If the output file already exists, give the user a chance to quit. if os.path.exists(outputFilename): print('This will overwrite the file {0:s}. (C)ontinue or (Q)uit?'\ .format(outputFilename)) response = input('> ') if not response.lower().startswith('c'): sys.exit() # Read in the message from the input file. fileObj = open(inputFilename) content = fileObj.read() fileObj.close() print('{0:s}ing...'.format(myMode.title())) # Measure how logn the encryption/decryption takes. startTime = time.time() if myMode == 'encrypt': translated = transpositionEncrypt.encryptMessage(myKey, content) elif myMode == 'decrypt': translated = transpositionDecrypt.decryptMessage(myKey, content) totalTime = round(time.time() - startTime, 2) print('{0:s}ion time: {1:f} seconds'.format(myMode.title(), totalTime)) # Write out the translated message to the output file. outputFileObj = open(outputFilename, 'w') outputFileObj.write(translated) outputFileObj.close() print('Done {0:s}ing {1:s} ({2:d} characters).'.format(myMode, inputFilename, len(content))) print('{0:s}ed file is {1:s}.'.format(myMode.title(), outputFilename))
def main(): inputFilename = '../books/frankenstein.txt' # BE CAREFUL! If a file with the outputFilename name already exists, # this program will overwrite that file. outputFilename = '../books/frankenstein.encrypted.txt' myKey = 10 myMode = 'encrypt' # set to 'encrypt' or 'decrypt' # If the input file does not exist, then the program terminates early. if not os.path.exists(inputFilename): print('The file %s does not exist. Quitting...' % (inputFilename)) sys.exit() # If the output file already exists, give the user a chance to quit. if os.path.exists(outputFilename): print('This will overwrite the file %s. (C)ontinue or (Q)uit?' % (outputFilename)) response = input('> ') print(response) sys.exit() if not response.lower().startswith('c'): sys.exit() # Read in the message from the input file fileObj = open(inputFilename) content = fileObj.read() fileObj.close() print('%sing...' % (myMode.title())) # Measure how long the encryption/decryption takes. startTime = time.time() if myMode == 'encrypt': translated = transpositionEncrypt.encryptMessage(myKey, content) elif myMode == 'decrypt': translated = transpositionDecrypt.decryptMessage(myKey, content) totalTime = round(time.time() - startTime, 2) print('%sion time: %s seconds' % (myMode.title(), totalTime)) # Write out the translated message to the output file. 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))
def hackTransposition(message): print("Press Ctrl+C to quit (Ctrl+D on macOS or Linux)") # Brute force by looping through every possible key for key in range(1, len(message)): print(f"Trying key: {key}...") decrypted_text = transpositionDecrypt.decryptMessage(key, message) if detectEnglish.isEnglish(decrypted_text): print("\nPossible encryption hack: ") print(f"Key: {key}, text: {decrypted_text[:100]}") response = input("Enter 'D' if done, anything else to continue: ") if response == 'D': return decrypted_text else: continue return None
def main(): random.seed(42) #seed of math unguessable for i in range(20): #20 tests message = "ABCDEFGHIJKLMNOPQRSTUVWXYZ" * random.randint(4,40) #message of random length message = list(message) #convert message string to a list random.shuffle(message) #shuffle it message = ''.join(message) #and back to a string print('Test #%s: "%s..."' % (i+1, message[:50])) for key in range(1, len(message)): #check all possible keys encrypted = transpositionEncrypt.encryptMessage(key, message) decrypted = transpositionDecrypt.decryptMessage(key, encrypted) if message != decrypted: #Error~! print('Key %s mismatch with message %s.' % (key,message)) print(decrypted) sys.exit() print('Transposition cipher test passed.')
def hackTransposition(message): print('Hacking...') # Brute-force approach for key in range(1, len(message)): print('Trying key #%s...' % (key)) decryptedText = transpositionDecrypt.decryptMessage(key, message) if detectEnglish.isEnglish(decryptedText): # Check with user to see if proper key found. print() print('Possible encryption hack:') print('Key %s: %s' % (key, decryptedText[:100])) print() print('Enter D for done, or Enter to continue:') response = input('> ') if response.strip().upper().startswith('D'): return decryptedText return None
def main(): random.seed(40) for i in range(20): # 初始化带测试的字符串 message = "ABCDEFGHIJKLMNOPQRSTUVWXYZ" * random.randint(4, 40) message = list(message) random.shuffle(message) message = "".join(message) print('Test #%s: "%s..."' % (i + 1, message)) for key in range(1, len(message)): encrypted = transpositionClipher.encryptMessage(key, message) decrypted = transpositionDecrypt.decryptMessage(key, encrypted) if message != decrypted: print("Mismatch with key %s and message %s." % (key, message)) print(decrypted) sys.exit() print("Transposition cipher test passed")
print('%sing...' % (myMode.title())) # Measure how long the encryption/decryption takes. startTime = time.time() if myMode == 'encrypt': translated = transpositionEncrypt.encryptMessage(myKey, content) elif myMode == 'decrypt': translated = transpositionDecrypt.decryptMessage(myKey, content) totalTime = round(time.time() - startTime, 2) print('%sion time: %s seconds' % (myMode.title(), totalTime)) # Write out the translated message to the output file. outputFileObj = open(outputFilename, 'w') outputFileObj.write(translated) outputFileObj.close()
# Transposition Cipher Test # http://inventwithpython.com/codebreaker (BSD Licensed) import transpositionEncrypt, transpositionDecrypt, random, sys random.seed(0) # set the random "seed" for i in range(1, 21): # run 20 tests # Generate random messages to test. message = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' * random.randint(4, 40) message = list(message) random.shuffle(message) message = ''.join(message) print('Test #%s: "%s..."' % (i, message[:50])) # Check all possible keys for each message. for key in range(1, len(message)): encrypted = transpositionEncrypt.encryptMessage(key, message) decrypted = transpositionDecrypt.decryptMessage(key, encrypted) # If the decryption doesn't match the original message, display # an error message and quit. if message != decrypted: print('Mismatch with key %s and message %s.' % (key, message)) print(decrypted) sys.exit() print('Transposition cipher test passed.')