Permalink
Browse files

Various changes.

  • Loading branch information...
1 parent babcfc0 commit b36a8ab46f90c3cc60a4428d00dbef2eeaa7fa21 @asweigart committed Dec 14, 2012
View
@@ -1,8 +1,8 @@
# Affine Cipher
# http://inventwithpython.com/hacking (BSD Licensed)
-import sys, pyperclip, cryptomath
-SYMBOLS = ' !"#$%&\'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~'
+import sys, pyperclip, cryptomath, random
+SYMBOLS = """ !"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz{|}~"""
def main():
@@ -14,7 +14,7 @@ def main():
translated = encryptMessage(myKey, myMessage)
elif myMode == 'decrypt':
translated = decryptMessage(myKey, myMessage)
-
+ print('Key: %s' % (myKey))
print('%sed text:' % (myMode.title()))
print(translated)
pyperclip.copy(translated)
@@ -24,7 +24,7 @@ def main():
def getKeyParts(key):
keyA = key // len(SYMBOLS)
keyB = key - (keyA * len(SYMBOLS))
- return keyA, keyB
+ return (keyA, keyB)
def checkKeys(keyA, keyB, mode):
@@ -62,12 +62,20 @@ def decryptMessage(key, message):
if symbol in SYMBOLS:
# decrypt this symbol
symIndex = SYMBOLS.find(symbol)
- plaintext += SYMBOLS[(symIndex - keyB) * modInverseOfKeyA % len(SYMBOLS)]
+ plaintext += SYMBOLS[( (symIndex - keyB) % len(SYMBOLS)) * modInverseOfKeyA % len(SYMBOLS)]
else:
plaintext += symbol # just append this symbol undecrypted
return plaintext
+def getRandomKey():
+ while True:
+ keyA = random.randint(2, len(SYMBOLS))
+ keyB = random.randint(2, len(SYMBOLS))
+ if cryptomath.gcd(keyA, len(SYMBOLS)) != 1:
+ return keyA * len(SYMBOLS) + keyB
+
+
# If affineCipher.py is run (instead of imported as a module) call
# the main() function.
if __name__ == '__main__':
View
@@ -1,4 +1,4 @@
-# Affine Cipher Breaker
+# Affine Cipher Hacker
# http://inventwithpython.com/hacking (BSD Licensed)
import pyperclip, affineCipher, detectEnglish, cryptomath
@@ -7,23 +7,23 @@
def main():
# You might want to copy & paste this text from the source code at
- # http://invpy.com/affineBreaker.py
+ # http://invpy.com/affineHacker.py
myMessage = """U&'<3dJ^Gjx'-3^MS'Sj0jxuj'G3'%j'<mMMjS'g{GjMMg9j{G'g"'gG'<3^MS'Sj<jguj'm'P^dm{'g{G3'%jMgjug{9'GPmG'gG'-m0'P^dm{LU'5&Mm{'_^xg{9"""
- brokenCiphertext = breakAffine(myMessage)
+ hackedMessage = hackAffine(myMessage)
- if brokenCiphertext != None:
+ if hackedMessage != None:
# The plaintext is displayed on the screen. For the convenience of
# the user, we copy the text of the code to the clipboard.
- print('Copying broken ciphertext to clipboard:')
- print(brokenCiphertext)
- pyperclip.copy(brokenCiphertext)
+ print('Copying hacked message to clipboard:')
+ print(hackedMessage)
+ pyperclip.copy(hackedMessage)
else:
- print('Failed to break encryption.')
+ print('Failed to hack encryption.')
-def breakAffine(message):
- print('Breaking...')
+def hackAffine(message):
+ print('Hacking...')
# Python programs can be stopped at any time by pressing Ctrl-C (on
# Windows) or Ctrl-D (on Mac and Linux)
@@ -42,19 +42,19 @@ def breakAffine(message):
if detectEnglish.isEnglish(decryptedText):
# Check with the user if the decrypted key has been found.
print()
- print('Possible encryption break:')
+ print('Possible encryption hack:')
print('Key: %s' % (key))
print('Decrypted message: ' + decryptedText[:200])
print()
- print('Enter D for done, or just press Enter to continue breaking:')
+ print('Enter D for done, or just press Enter to continue hacking:')
response = input('> ')
if response.strip().upper().startswith('D'):
return decryptedText
return None
-# If affineBreaker.py is run (instead of imported as a module) call
+# If affineHacker.py is run (instead of imported as a module) call
# the main() function.
if __name__ == '__main__':
main()
View
@@ -0,0 +1,11 @@
+# This program proves that the keyspace of the affine cipher is limited
+# to len(SYMBOLS) ^ 2.
+
+import affineCipher, cryptomath
+
+message = 'Make things as simple as possible, but not simpler.'
+for keyA in range(2, len(affineCipher.SYMBOLS) + 5):
+ key = keyA * len(affineCipher.SYMBOLS) + 1
+
+ if cryptomath.gcd(keyA, len(affineCipher.SYMBOLS)) == 1:
+ print(keyA, affineCipher.encryptMessage(key, message))
View
@@ -1,4 +1,4 @@
-# Caesar Cipher Breaker
+# Caesar Cipher Hacker
# http://inventwithpython.com/hacking (BSD Licensed)
message = 'GUVF VF ZL FRPERG ZRFFNTR.'
View
@@ -6,9 +6,9 @@
# detectEnglish.isEnglish(someString) # returns True or False
# (There must be a "dictionary.txt" file in this directory with all English
# words in it, one word per line. You can download this from
-# http://invpy.com/dictionary.txt)
-LETTERS = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
-LETTERS_AND_SPACE = LETTERS + LETTERS.lower() + ' \t\n'
+# http://invpy.com/dictionary.txt) and put it in the same directory as detectEnglish.py.
+UPPERLETTERS = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
+LETTERS_AND_SPACE = UPPERLETTERS + UPPERLETTERS.lower() + ' \t\n'
def loadDictionary():
dictionaryFile = open('dictionary.txt')
View
@@ -1,31 +1,31 @@
-# Null Cipher Breaker
+# Null Cipher Hacker
# http://inventwithpython.com/hacking (BSD Licensed)
import nullCipher, pyperclip, detectEnglish, itertools
-# There are two settings our breaking program needs to limit the range of
+# There are two settings our hacking program needs to limit the range of
# the possible keys it checks.
# MAX_KEY_NUMBER is the range of numbers it checks for each number in the
# key. A MAX_KEY_NUMBER value of 9 means it will check 0 through 9.
# MAX_KEY_DIGITS is the largest amount of numbers in the key. A value of 5
# means that the key could be something like '1 2 3 4 5' or '1 1 1 1 1' or
# '1 2 3 4', but not '1 2 3 4 5 6'
-# If these numbers are too large, then breaking the code will take a long
-# time. If these numbers are too small, then the breaking program won't be
-# able to break the encryption.
+# If these numbers are too large, then hacking the code will take a long
+# time. If these numbers are too small, then the hacking program won't be
+# able to hack the encryption.
MAX_KEY_NUMBER = 9
MAX_KEY_DIGITS = 5
SILENT_MODE = False
-# This can be copy/pasted from http://invpy.com/nullBreaker.py
+# This can be copy/pasted from http://invpy.com/nullHacker.py
myMessage = """sn Wht eetan mnIeu uedswsae aiaeh wh ohh rdrh, h ihotote muoeh annesets jtwunetst - e-rwhe am jt Inoo c,nh oossssace oai o t oWth.no miiteaton r -s -ou nwse. nito hwiieroe s imoiorot e o nsesorer anletesmt s.ah"""
def main():
# Calculate the number of keys that the current MAX_KEY_DIGITS and
- # MAX_KEY_NUMBER values will cause the breaker program to go through.
+ # MAX_KEY_NUMBER values will cause the hacker program to go through.
possibleKeys = 0 # start the number of keys at 0.
for i in range(1, MAX_KEY_DIGITS + 1):
# To find the total number of possible keys, add the total number
@@ -46,19 +46,19 @@ def main():
# 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.)')
- print('Breaking...')
+ print('Hacking...')
- brokenMessage = breakNull(myMessage)
+ brokenMessage = hackNull(myMessage)
if brokenMessage != None:
print('Copying broken message to clipboard:')
print(brokenMessage)
pyperclip.copy(brokenMessage)
else:
- print('Failed to break encryption.')
+ print('Failed to hack encryption.')
-def breakNull(ciphertext):
+def hackNull(ciphertext):
# The program needs to try keys of length 1 (such as '5'), of length 2
# (such as '5 3'), and so on up to length MAX_KEY_DIGITS.
for keyLength in range(1, MAX_KEY_DIGITS + 1):
@@ -75,16 +75,16 @@ def breakNull(ciphertext):
if detectEnglish.isEnglish(decryptedText):
print()
- print('Possible encryption break:')
+ print('Possible encryption hack:')
print('Key: %s' % (key))
print('Decrypted message: ' + decryptedText[:200])
print()
- print('Enter D for done, or just press Enter to continue breaking:')
+ print('Enter D for done, or just press Enter to continue hacking:')
response = input('> ')
if response.strip().upper().startswith('D'):
return decryptedText
- return None # failed to break encryption
+ return None # failed to hack encryption
if __name__ == '__main__':
View
@@ -1,5 +1,5 @@
# Reverse Cipher
-# http://inventwithpython.com/codebreaker (BSD Licensed)
+# http://inventwithpython.com/hacking (BSD Licensed)
message = 'Three can keep a secret, if two of them are dead.'
translated = ''
View
@@ -24,7 +24,7 @@ def main():
print('Encrypted text:')
print(encryptedText)
- if mode == 'decrypt':
+ elif mode == 'decrypt':
pubKeyFilename = 'al_sweigart_pubkey.txt'
print('Reading from %s and decrypting...' % (filename))
decryptedText = readFromFileAndDecrypt(filename, pubKeyFilename)
@@ -0,0 +1,53 @@
+# Simple Substitution Dictionary Hacker, http://inventwithpython.com/hacking (BSD Licensed)
+import pyperclip, simpleSubKeyword, detectEnglish
+
+SILENT_MODE = False
+
+def main():
+ myMessage = r"""SJITDOPIQR: JIR RIQMUNQRO AY P WDQC QCR NRSMRQN JT A SJITDORO QJ CRMNRGT AY S. -PHAMJNR ADRMSR"""
+
+ brokenCiphertext = hackSimpleSubDictionary(myMessage)
+
+ if brokenCiphertext == None:
+ # hackSimpleSubDictionary() will return the None value if it was unable to hack the encryption.
+ print('Hacking failed. Unable to hack this ciphertext.')
+ else:
+ # The plaintext is displayed on the screen. For the convenience of the user, we copy the text of the code to the clipboard.
+ print('Copying broken ciphertext to clipboard:')
+ print(brokenCiphertext)
+ pyperclip.copy(brokenCiphertext)
+
+
+def hackSimpleSubDictionary(message):
+ print('Hacking with %s possible dictionary words...' % (len(detectEnglish.ENGLISH_WORDS) * 3))
+
+ # 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.)')
+
+ tryNum = 1
+
+ # brute force by looping through every possible key
+ for key in detectEnglish.ENGLISH_WORDS:
+ if tryNum % 100 == 0 and not SILENT_MODE:
+ print('%s keys tried. (%s)' % (tryNum, key))
+
+ decryptedText = simpleSubKeyword.decryptMessage(key, message)
+
+ if detectEnglish.getEnglishCount(decryptedText) > 0.20:
+ # Check with the user to see if the decrypted key has been found.
+ print()
+ print('Possible encryption hack:')
+ print('Key: ' + str(key))
+ print('Decrypted message: ' + decryptedText[:100])
+ print()
+ print('Enter D for done, or just press Enter to continue hacking:')
+ response = input('> ')
+
+ if response.upper().startswith('D'):
+ return decryptedText
+
+ tryNum += 1
+ return None
+
+if __name__ == '__main__':
+ main()
View
@@ -1,4 +1,4 @@
-# Simple Substitution Cipher Breaker
+# Simple Substitution Cipher Hacker
# http://inventwithpython.com/hacking (BSD Licensed)
"""
@@ -57,11 +57,11 @@ def main():
allCandidates[cipherWord][i] = allCandidates[cipherWord][i].upper()
# determine the possible valid ciphertext translations
- print('Breaking...')
+ 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.)')
- theMap = breakSimpleSub(getNewBlankMapping(), allCandidates)
+ theMap = hackSimpleSub(getNewBlankMapping(), allCandidates)
# display the results to the user.
print('Done.')
@@ -71,7 +71,7 @@ def main():
print('Original ciphertext:')
print(message)
print()
- print('Broken ciphertext:')
+ print('Hacked message:')
print(decryptWithMap(message, theMap))
print()
@@ -94,7 +94,7 @@ def getWordPattern(word):
-def breakSimpleSub(theMap, allCandidates):
+def hackSimpleSub(theMap, allCandidates):
# allCandidate's format:
# { 'cipherword1': ['candidate1a', 'candidate1b', ...],
# 'cipherword2': ['candidate2a', 'candidate2b', ...],
@@ -1,4 +1,4 @@
-# Transposition File Breaker
+# Transposition File Hacker
# http://inventwithpython.com/hacking (BSD Licensed)
import sys, time, os, sys, transpositionDecrypt, detectEnglish
@@ -15,7 +15,7 @@ def main():
content = inputFile.read()
inputFile.close()
- brokenMessage = breakTransposition(content)
+ brokenMessage = hackTransposition(content)
if brokenMessage != None:
print('Writing decrypted text to %s.' % (outputFilename))
@@ -24,13 +24,13 @@ def main():
outputFile.write(brokenMessage)
outputFile.close()
else:
- print('Failed to break encryption.')
+ print('Failed to hack encryption.')
-# The breakTransposition() function's code was copy/pasted from
-# transpositionBreaker.py and had some modifications made.
-def breakTransposition(message):
- print('Breaking...')
+# The hackTransposition() function's code was copy/pasted from
+# transpositionHacker.py and had some modifications made.
+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.)')
@@ -62,7 +62,7 @@ def breakTransposition(message):
return None
-# If transpositionFileBreaker.py is run (instead of imported as a module)
+# If transpositionFileHacker.py is run (instead of imported as a module)
# call the main() function.
if __name__ == '__main__':
main()
Oops, something went wrong. Retry.

0 comments on commit b36a8ab

Please sign in to comment.