Skip to content

Commit

Permalink
CrackingCodes Initial Commit
Browse files Browse the repository at this point in the history
  • Loading branch information
doyler committed Apr 3, 2018
0 parents commit 0abd491
Show file tree
Hide file tree
Showing 37 changed files with 158,493 additions and 0 deletions.
104 changes: 104 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,104 @@
# Byte-compiled / optimized / DLL files
__pycache__/
*.py[cod]
*$py.class

# C extensions
*.so

# Distribution / packaging
.Python
build/
develop-eggs/
dist/
downloads/
eggs/
.eggs/
lib/
lib64/
parts/
sdist/
var/
wheels/
*.egg-info/
.installed.cfg
*.egg
MANIFEST

# PyInstaller
# Usually these files are written by a python script from a template
# before PyInstaller builds the exe, so as to inject date/other infos into it.
*.manifest
*.spec

# Installer logs
pip-log.txt
pip-delete-this-directory.txt

# Unit test / coverage reports
htmlcov/
.tox/
.coverage
.coverage.*
.cache
nosetests.xml
coverage.xml
*.cover
.hypothesis/
.pytest_cache/

# Translations
*.mo
*.pot

# Django stuff:
*.log
local_settings.py
db.sqlite3

# Flask stuff:
instance/
.webassets-cache

# Scrapy stuff:
.scrapy

# Sphinx documentation
docs/_build/

# PyBuilder
target/

# Jupyter Notebook
.ipynb_checkpoints

# pyenv
.python-version

# celery beat schedule file
celerybeat-schedule

# SageMath parsed files
*.sage.py

# Environments
.env
.venv
env/
venv/
ENV/
env.bak/
venv.bak/

# Spyder project settings
.spyderproject
.spyproject

# Rope project settings
.ropeproject

# mkdocs documentation
/site

# mypy
.mypy_cache/
3 changes: 3 additions & 0 deletions 00-hello.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
print '\nHello, World!'
myName = raw_input('What is your name? ')
print 'It is nice to meet you, ' + myName + '\n'
13 changes: 13 additions & 0 deletions 01-reverseCipher.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
#message = 'Three can keep a secret, if two of them are dead.'
#message = '.daed era meht fo owt fi ,terces a peek nac eerhT'
message = raw_input('\nEnter message: ')
translated = ''

i = len(message) - 1

while i >= 0:
translated = translated + message[i]
#print 'i is', i, ', message[i] is', message[i], ', translated is', translated
i = i - 1

print "Reversed: " + translated + "\n"
44 changes: 44 additions & 0 deletions 02-caesarCipher.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
import sys

#message = 'guv6(v6(z!(6rp5r7(zr66ntr+'
message = raw_input('\nEnter message: ')

# The encryption/decryption key:
#key = 13
key = int(raw_input("Encryption/decryption key: "))

# Whether the program encrypts or decrypts:
mode = raw_input("Would you like to encrypt or decrypt this message? ")
if mode.lower().startswith('e'): mode = "encrypt"
elif mode.lower().startswith('d'): mode = "decrypt"
else:
print "\nMode not recognized, exiting.\n"
sys.exit()

# Every possible symbol that can be encrypted:
SYMBOLS = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz1234567890 !?.`~@#$%^&*()_+-=[]{}|;:<>,/\'"'

# Stores the encrypted/decrypted form of the message:
translated = ''

for symbol in message:
if symbol in SYMBOLS:
symbolIndex = SYMBOLS.find(symbol)

if mode == 'encrypt':
translatedIndex = symbolIndex + key
elif mode == 'decrypt':
translatedIndex = symbolIndex - key

# Handle wrap-around, if needed:
if translatedIndex >= len(SYMBOLS):
translatedIndex = translatedIndex - len(SYMBOLS)
elif translatedIndex < 0:
translatedIndex = translatedIndex + len(SYMBOLS)

translated = translated + SYMBOLS[translatedIndex]
else:
# Append the symbol without encrypting/decrypting:
translated = translated + symbol

print ("\n%sed message: " + translated + "\n") % mode.title()
32 changes: 32 additions & 0 deletions 03-caesarHacker.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
#message = 'guv6(v6(z!(6rp5r7(zr66ntr+'
message = raw_input('\nEnter message: ')

SYMBOLS = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz1234567890 !?.`~@#$%^&*()_+-=[]{}|;:<>,/\'"'

print ''

# Loop through every possible key:
for key in range(len(SYMBOLS)):
translated = ''

# Loop through each symbol in `message`:
for symbol in message:
if symbol in SYMBOLS:
symbolIndex = SYMBOLS.find(symbol)
translatedIndex = symbolIndex - key

# Handle the wrap-around:
if translatedIndex < 0:
translatedIndex = translatedIndex + len(SYMBOLS)

# Append the decrypted symbol:
translated = translated + SYMBOLS[translatedIndex]

else:
# Append the symbol without encrypting/decrypting:
translated = translated + symbol

# Display every possible decryption:
print 'Key #%s: %s' % (key, translated)

print ''
33 changes: 33 additions & 0 deletions 04-transpositionEncrypt.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
def main():
#myMessage = '''Augusta Ada King-Noel, Countess of Lovelace (10 December 1815 - 27 November 1852) was an English mathematician and writer, chiefly known for her work on Charles Babbage's early mechanical general-purpose computer, the Analytical Engine. Her notes on the engine include what is recognised as the first algorithm intended to be carried out by a machine. As a result, she is often regarded as the first computer programmer.'''
#myKey = 13

myMessage = raw_input("Please enter in the message to encrypt: ")
myKey = int(raw_input("Enter in the encryption/decryption key: "))

ciphertext = encryptMessage(myKey, myMessage)

print ciphertext + '|'

def encryptMessage(key, message):
# Each string in ciphertext represents a column in the grid.
ciphertext = [''] * key

# Loop through each column in ciphertext.
for column in range(key):
currentIndex = column

# Keep looping until currentIndex goes past the message length.
while currentIndex < len(message):
# Place the character at currentIndex in message at the
# end of the current column in the ciphertext list.
ciphertext[column] += message[currentIndex]

# move currentIndex over
currentIndex += key

# Convert the ciphertext list into a single string value and return it.
return ''.join(ciphertext)

if __name__ == '__main__':
main()
43 changes: 43 additions & 0 deletions 05-transpositionDecrypt.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
import math

def main():
#myMessage = 'Cenoonommstmme oo snnio. s s c'
#myKey = 8

myMessage = raw_input("Please enter in the encrypted message: ")
myKey = int(raw_input("Enter in the encryption/decryption key: "))

plaintext = decryptMessage(myKey, myMessage)

print '\n' + plaintext + '|\n'

def decryptMessage(key, message):
# The number of "columns" in our transposition grid:
numOfColumns = int(math.ceil(len(message) / float(key)))
# The number of "rows" in our grid will need:
numOfRows = key
# The number of "shaded boxes" in the last "column" of the grid:
numOfShadedBoxes = (numOfColumns * numOfRows) - len(message)

# Each string in plaintext represents a column in the grid.
plaintext = [''] * numOfColumns

# The column and row variables point to where in the grid the next
# character in the encrypted message will go.
column = 0
row = 0

for symbol in message:
plaintext[column] += symbol
column += 1 # Point to next column.

# If there are no more columns OR we're at a shaded box, go back to
# the first column and the next row:
if (column == numOfColumns) or (column == numOfColumns - 1 and row >= numOfRows - numOfShadedBoxes):
column = 0
row += 1

return ''.join(plaintext)

if __name__ == '__main__':
main()
34 changes: 34 additions & 0 deletions 06-transpositionTest.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
import random, sys

transpositionEncrypt = __import__('4-transpositionEncrypt')
transpositionDecrypt = __import__('5-transpositionDecrypt')

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 list to 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.'

if __name__ == '__main__':
main()
51 changes: 51 additions & 0 deletions 07-transpositionFileCipher.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
import time, os, sys

transpositionEncrypt = __import__('4-transpositionEncrypt')
transpositionDecrypt = __import__('5-transpositionDecrypt')

def main():
#inputFilename = 'frankenstein.txt'
inputFilename = raw_input("Please input the filename: ")

#myKey = 10
myKey = int(raw_input("Enter the encryption/decryption key: "))

#myMode = 'encrypt' # set to 'encrypt' or 'decrypt'
myMode = raw_input("Please select \"encrypt\" or \"decrypt\": ")

outputFilename = '.'.join(inputFilename.split('.')[0:-1]) + '.' + myMode + 'ed.' + inputFilename.split('.')[-1]

# 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()

with open(inputFilename) as f:
content = f.read()

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)

with open(outputFilename, 'w') as f:
f.write(translated)

print 'Done %sing %s (%s characters).' % (myMode, inputFilename, len(content))
print '%sed file is %s.' % (myMode.title(), outputFilename)

if __name__ == '__main__':
main()
Loading

0 comments on commit 0abd491

Please sign in to comment.