Permalink
Browse files

Various changes.

  • Loading branch information...
1 parent bca6d3e commit e9fb124cfcc1fa322ea80d3c4659875e71c10d98 @asweigart committed Dec 14, 2012
View
@@ -1,5 +1,5 @@
# Affine Cipher Breaker
-# http://inventwithpython.com/codebreaker (BSD Licensed)
+# http://inventwithpython.com/hacking (BSD Licensed)
import pyperclip, affineCipher, detectEnglish, cryptomath
@@ -8,9 +8,9 @@
def main():
# You might want to copy & paste this text from the source code at
# http://invpy.com/affineBreaker.py
- myMessage = 'H RZPEDYBO NZDKW WBTBOIB YZ MB RHKKBW VUYBKKVLBUY VG VY RZDKW WBRBVIB H QDPHU VUYZ MBKVBIVUL YQHY VY NHT QDPHU. -HKHU YDOVUL'
+ 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.upper())
+ brokenCiphertext = breakAffine(myMessage)
if brokenCiphertext != None:
# The plaintext is displayed on the screen. For the convenience of
@@ -30,27 +30,27 @@ def breakAffine(message):
print('(Press Ctrl-C or Ctrl-D to quit at any time.)')
# brute force by looping through every possible key
- for keyA in range(len(affineCipher.LETTERS)):
- if cryptomath.gcd(keyA, len(affineCipher.LETTERS)) != 1:
+ for key in range(len(affineCipher.SYMBOLS) ** 2):
+ keyA = affineCipher.getKeyParts(key)[0]
+ if cryptomath.gcd(keyA, len(affineCipher.SYMBOLS)) != 1:
continue
- for keyB in range(len(affineCipher.LETTERS)):
- decryptedText = affineCipher.decryptMessage(keyA, keyB, message)
- if not SILENT_MODE:
- print('Tried KeyA %s, KeyB %s... (%s)' % (keyA, keyB, decryptedText[:40]))
-
- if detectEnglish.isEnglish(decryptedText):
- # Check with the user if the decrypted key has been found.
- print()
- print('Possible encryption break:')
- print('KeyA: %s, KeyB: %s' % (keyA, keyB))
- print('Decrypted message: ' + decryptedText[:200])
- print()
- print('Enter D for done, or just press Enter to continue breaking:')
- response = input('> ')
-
- if response.strip().upper().startswith('D'):
- return decryptedText
+ decryptedText = affineCipher.decryptMessage(key, message)
+ if not SILENT_MODE:
+ print('Tried Key %s... (%s)' % (key, decryptedText[:40]))
+
+ if detectEnglish.isEnglish(decryptedText):
+ # Check with the user if the decrypted key has been found.
+ print()
+ print('Possible encryption break:')
+ print('Key: %s' % (key))
+ print('Decrypted message: ' + decryptedText[:200])
+ print()
+ print('Enter D for done, or just press Enter to continue breaking:')
+ response = input('> ')
+
+ if response.strip().upper().startswith('D'):
+ return decryptedText
return None
View
@@ -1,66 +1,70 @@
# Affine Cipher
-# http://inventwithpython.com/codebreaker (BSD Licensed)
+# http://inventwithpython.com/hacking (BSD Licensed)
import sys, pyperclip, cryptomath
-
-LETTERS = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
+SYMBOLS = ' !"#$%&\'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~'
def main():
- myMessage = 'A computer would deserve to be called intelligent if it could deceive a human into believing that it was human. -Alan Turing'
- myKeyA, myKeyB = 5, 7
+ myMessage = """"A computer would deserve to be called intelligent if it could deceive a human into believing that it was human." -Alan Turing"""
+ myKey = 2023
myMode = 'encrypt' # set to 'encrypt' or 'decrypt'
- myMessage = myMessage.upper()
-
if myMode == 'encrypt':
- translated = encryptMessage(myKeyA, myKeyB, myMessage)
+ translated = encryptMessage(myKey, myMessage)
elif myMode == 'decrypt':
- translated = decryptMessage(myKeyA, myKeyB, myMessage)
+ translated = decryptMessage(myKey, myMessage)
print('%sed text:' % (myMode.title()))
print(translated)
pyperclip.copy(translated)
print('Full %sed text copied to clipboard.' % (myMode))
-def encryptMessage(keyA, keyB, message):
- # key strength and validity checks
- if keyA == 1:
- sys.exit('The affine cipher becomes incredibly weak when keyA is set to 1. Choose a different key.')
- if keyB == 0:
- sys.exit('The affine cipher becomes incredibly weak when keyB is set to 0. Choose a different key.')
+def getKeyParts(key):
+ keyA = key // len(SYMBOLS)
+ keyB = key - (keyA * len(SYMBOLS))
+ return keyA, keyB
+
- if cryptomath.gcd(keyA, len(LETTERS)) != 1:
- sys.exit('The key (%s) and the size of the alphabet (%s) are not relatively prime. Choose a different key.' % (keyA, len(LETTERS)))
+def checkKeys(keyA, keyB, mode):
+ if keyA == 1 and mode == 'encrypt':
+ sys.exit('The affine cipher becomes incredibly weak when key A is set to 1. Choose a different key.')
+ if keyB == 0 and mode == 'encrypt':
+ sys.exit('The affine cipher becomes incredibly weak when key B is set to 0. Choose a different key.')
+ if keyA < 0 or keyB < 0 or keyB > len(SYMBOLS) - 1:
+ sys.exit('Key A must be greater than 0 and Key B must be between 0 and %s.' % (len(SYMBOLS) - 1))
+ if cryptomath.gcd(keyA, len(SYMBOLS)) != 1:
+ sys.exit('Key A (%s) and the symbol set size (%s) are not relatively prime. Choose a different key.' % (keyA, len(SYMBOLS)))
+
+def encryptMessage(key, message):
+ keyA, keyB = getKeyParts(key)
+ checkKeys(keyA, keyB, 'encrypt')
ciphertext = ''
for symbol in message:
- if symbol in LETTERS:
+ if symbol in SYMBOLS:
# encrypt this symbol
- symIndex = LETTERS.find(symbol)
- ciphertext += LETTERS[(symIndex * keyA + keyB) % len(LETTERS)]
+ symIndex = SYMBOLS.find(symbol)
+ ciphertext += SYMBOLS[(symIndex * keyA + keyB) % len(SYMBOLS)]
else:
- # just append this symbol unencrypted
- ciphertext += symbol
+ ciphertext += symbol # just append this symbol unencrypted
return ciphertext
-def decryptMessage(keyA, keyB, message):
- if cryptomath.gcd(keyA, len(LETTERS)) != 1:
- sys.exit('The key (%s) and the size of the alphabet (%s) are not relatively prime. Choose a different key.' % (keyA, len(LETTERS)))
-
+def decryptMessage(key, message):
+ keyA, keyB = getKeyParts(key)
+ checkKeys(keyA, keyB, 'decrypt')
+ keyA, keyB = getKeyParts(key)
+ modInverseOfKeyA = cryptomath.findModInverse(keyA, len(SYMBOLS))
plaintext = ''
- modInverseOfKeyA = cryptomath.findModInverse(keyA, len(LETTERS))
-
for symbol in message:
- if symbol in LETTERS:
+ if symbol in SYMBOLS:
# decrypt this symbol
- symIndex = LETTERS.find(symbol)
- plaintext += LETTERS[(symIndex - keyB) * modInverseOfKeyA % len(LETTERS)]
+ symIndex = SYMBOLS.find(symbol)
+ plaintext += SYMBOLS[(symIndex - keyB) * modInverseOfKeyA % len(SYMBOLS)]
else:
- # just append this symbol unencrypted
- plaintext += symbol
+ plaintext += symbol # just append this symbol undecrypted
return plaintext
View
@@ -1,5 +1,5 @@
# Caesar Cipher Breaker
-# http://inventwithpython.com/codebreaker (BSD Licensed)
+# http://inventwithpython.com/hacking (BSD Licensed)
message = 'GUVF VF ZL FRPERG ZRFFNTR.'
LETTERS = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
View
@@ -1,5 +1,5 @@
# Caesar Cipher
-# http://inventwithpython.com/codebreaker (BSD Licensed)
+# http://inventwithpython.com/hacking (BSD Licensed)
import pyperclip
View
@@ -1,5 +1,8 @@
+# Cryptomath Module
+# http://inventwithpython.com/hacking (BSD Licensed)
+
def gcd(a, b):
- # Return the Greatest Common Divisor of a and b using Euclid's Algorithm
+ # Return the GCD of a and b using Euclid's Algorithm
while a != 0:
a, b = b % a, a
return b
@@ -10,7 +13,7 @@ def findModInverse(a, m):
# the number x such that a*x % m = 1
if gcd(a, m) != 1:
- return None # no mod inverse exists if a & m aren't relatively prime
+ return None # no mod inverse if a & m aren't relatively prime
# Calculate using the Extended Euclidean Algorithm:
u1, u2, u3 = 1, 0, a
View
@@ -1,5 +1,5 @@
# Detect English module
-# http://inventwithpython.com/codebreaker (BSD Licensed)
+# http://inventwithpython.com/hacking (BSD Licensed)
# To use, type this code:
# import detectEnglish
@@ -33,7 +33,7 @@ def getEnglishCount(message):
for word in possibleWords:
if word in ENGLISH_WORDS:
matches += 1
- return matches / len(possibleWords)
+ return float(matches) / len(possibleWords)
def removeNonLetters(message):
@@ -49,5 +49,7 @@ def isEnglish(message, wordPercentage=20, letterPercentage=85):
# 85% of all the characters in the message must be letters or spaces
# (not punctuation or numbers).
wordsMatch = getEnglishCount(message) * 100 >= wordPercentage
- lettersMatch = len(removeNonLetters(message)) / len(message) * 100 >= letterPercentage
+ numLetters = len(removeNonLetters(message))
+ messageLettersPercentage = float(numLetters) / len(message) * 100
+ lettersMatch = messageLettersPercentage >= letterPercentage
return wordsMatch and lettersMatch
View
@@ -1,5 +1,5 @@
# Frequency Finder
-# http://inventwithpython.com/codebreaker (BSD Licensed)
+# http://inventwithpython.com/hacking (BSD Licensed)
# frequency taken from http://en.wikipedia.org/wiki/Letter_frequency
englishLetterFreq = {'E': 12.70, 'T': 9.06, 'A': 8.17, 'O': 7.51, 'I': 6.97, 'N': 6.75, 'S': 6.33, 'H': 6.09, 'R': 5.99, 'D': 4.25, 'L': 4.03, 'C': 2.78, 'U': 2.76, 'M': 2.41, 'W': 2.36, 'F': 2.23, 'G': 2.02, 'Y': 1.97, 'P': 1.93, 'B': 1.29, 'V': 0.98, 'K': 0.77, 'J': 0.15, 'X': 0.15, 'Q': 0.10, 'Z': 0.07}
View
@@ -1,5 +1,5 @@
# RSA Key Generator
-# http://inventwithpython.com/codebreaker (BSD Licensed)
+# http://inventwithpython.com/hacking (BSD Licensed)
import random, sys, os, rabinMiller, cryptomath
View
@@ -1,5 +1,5 @@
# Null Cipher Breaker
-# http://inventwithpython.com/codebreaker (BSD Licensed)
+# http://inventwithpython.com/hacking (BSD Licensed)
import nullCipher, pyperclip, detectEnglish, itertools
@@ -20,7 +20,7 @@
SILENT_MODE = False
# This can be copy/pasted from http://invpy.com/nullBreaker.py
-myMessage = """y\ZWh,De,. n #{ItZ9 uL<sl6!e 2&a"\B w{Eo;l#rdvK,9\s i.Xt?WC mQ-ef>yanpushOz j9lu_H4stsd .Bawhmua_ogt <`I#w$ ctoh({'oo={sINUe 84i%G3t NLt2#Wo 7Zm*<^eacUnuG6 -=g-f:! nxQe$Qmit&Ah0#ner:O Gt!moc;rXGUe q/nKrgor"\ 9 \lecBs|10s.9i"""
+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():
View
@@ -1,21 +1,17 @@
# Null Cipher
-# http://inventwithpython.com/codebreaker (BSD Licensed)
-
+# http://inventwithpython.com/hacking (BSD Licensed)
import random, pyperclip
-myMessage = 'When I use a word, it means just what I choose it to mean -- neither more nor less.'
+myMessage = """When I use a word, it means just what I choose it to mean -- neither more nor less."""
myKey = '302'
mode = 'encrypt' # set to 'encrypt' or 'decrypt'
-# The nulls will be randomly selected from this list of characters.
-# Don't forget the space character at the start!
-SYMBOLS = ' !"#$%&\'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~'
def main():
if mode == 'encrypt':
- translated = encryptMessage(myMessage, myKey)
+ translated = encryptMessage(myKey, myMessage)
elif mode == 'decrypt':
- translated = decryptMessage(myMessage, myKey)
+ translated = decryptMessage(myKey, myMessage)
print('%sed message: ' % (mode.title()) + translated)
print('The message has been copied to the clipboard.')
@@ -24,35 +20,29 @@ def main():
def encryptMessage(key, message):
# The expression int(key[keyIndex]) will be used to decide how many
- # nulls should be inserted. For example, if key is the value '102' and
- # keyIndex is 0, then 1 null character will be inserted into the
- # ciphertext.
+ # nulls should be inserted. For example, if key is the value '570'
+ # and keyIndex is 0, then 5 null characters will be inserted into
+ # the ciphertext.
keyIndex = 0
ciphertext = '' # will contain the encrypted string
- for symbol in message:
+ for symbol in list(message) + [None]:
for dummy in range(int(key[keyIndex])):
- # A randomly-selected null symbol is appended to the end
- # of the ciphertext.
- ciphertext += random.choice(SYMBOLS)
+ # Add a null.
+ ciphertext += random.choice(myMessage)
+
+ if symbol == None:
+ break # the None value marks the end
# Increment keyIndex so that on the next iteration, we use a
# number of nulls specified by the next character in key.
keyIndex += 1
if keyIndex == len(key):
- # If keyIndex is past the last index of key (which is
- # len(key) - 1), then reset keyIndex back to 0.
+ # keyIndex is past the end, so reset it back to 0.
keyIndex = 0
# Add the real symbol after adding the nulls.
ciphertext += symbol
-
- # Add some more nulls after adding the last symbol. This way, a code
- # breaker cannot assume that the last symbol in the ciphertext is
- # always a part of the original message.
- for dummy in range(int(key[keyIndex])):
- ciphertext += random.choice(SYMBOLS)
-
return ciphertext
@@ -66,14 +56,12 @@ def decryptMessage(key, message):
while True:
# The expression int(key[keyIndex]) will give us the int value of
- # how many nulls to skip over. We will move the value in
+ # how many nulls to skip over. We will increment the value in
# messageIndex by this amount.
messageIndex += int(key[keyIndex])
- # If messageIndex is not past the last index in the message string
- # (the last index is len(message) - 1) then we are done decrypting
- # and should break out of the loop.
if messageIndex >= len(message):
+ # When messageIndex is past the last index, we are done.
break
# Increment keyIndex so that on the next iteration, we
View
@@ -1,5 +1,5 @@
# Prime Number Sieve
-# http://inventwithpython.com/codebreaker (BSD Licensed)
+# http://inventwithpython.com/hacking (BSD Licensed)
import math
View
@@ -1,5 +1,5 @@
# Primality Testing with the Rabin-Miller Algorithm
-# http://inventwithpython.com/codebreaker (BSD Licensed)
+# http://inventwithpython.com/hacking (BSD Licensed)
import random
View
@@ -1,5 +1,5 @@
# RSA Cipher
-# http://inventwithpython.com/codebreaker (BSD Licensed)
+# http://inventwithpython.com/hacking (BSD Licensed)
import sys
View
@@ -1,5 +1,5 @@
# Simple Substitution Cipher Breaker
-# http://inventwithpython.com/codebreaker (BSD Licensed)
+# http://inventwithpython.com/hacking (BSD Licensed)
"""
In this program, a "word pattern" is a description of which letters are
@@ -36,8 +36,8 @@
def main():
message = 'SY L NLX SR PYYACAO L YLWJ EISWI UPAR LULSXRJ ISR SXRJSXWJR, IA ESMM RWCTJSXSZA SJ WMPRAMH, LXO TXMARR JIA AQSOAXWA SR PQACEIAMNSXU, IA ESMM CAYTRA JP FAMSAQA SJ. SY, PX JIA PJIAC ILXO, IA SR PYYACAO RPNAJISXU EISWI LYYPCOR L CALRPX YPC LWJSXU SX LWWPCOLXWA JP ISR SXRJSXWJR, IA ESMM LWWABJ SJ AQAX PX JIA RMSUIJARJ AQSOAXWA. JIA PCSUSX PY NHJIR SR AGBMLSXAO SX JISR ELH. -FACJCLXO CTRRAMM'
- nonLettersPattern = re.compile('[^A-Z\s]')
- ciphertext = nonLettersPattern.sub('', message.upper()).split()
+ NONLETTERSPATTERN = re.compile('[^A-Z\s]')
+ ciphertext = NONLETTERSPATTERN.sub('', message.upper()).split()
# allCandidates is a dict with keys of a single ciphertext word, and
# values of the possible word patterns
View
@@ -1,5 +1,5 @@
# Simple Substitution Keyword Cipher
-# http://inventwithpython.com/codebreaker (BSD Licensed)
+# http://inventwithpython.com/hacking (BSD Licensed)
import pyperclip, simpleSubCipher
Oops, something went wrong.

0 comments on commit e9fb124

Please sign in to comment.