All given below is about Python, you have to use any python editors to run them😎
Print hello
# This program says hello and asks for my name.
print('Hello world!')
print('What is your name?')
myName = input()
print('It is good to meet you, ' + myName)
Making public/private key
# Public Key Generator
# https://www.nostarch.com/crackingcodes/ (BSD Licensed)
import random, sys, os, primeNum, cryptomath
def main():
# Create a public/private keypair with 1024 bit keys:
print('Making key files...')
makeKeyFiles('al_sweigart', 1024)
print('Key files made.')
def generateKey(keySize):
# Creates a public/private keys keySize bits in size.
p = 0
q = 0
# Step 1: Create two prime numbers, p and q. Calculate n = p * q.
print('Generating p & q primes...')
while p == q:
p = primeNum.generateLargePrime(keySize)
q = primeNum.generateLargePrime(keySize)
n = p * q
# Step 2: Create a number e that is relatively prime to (p-1)*(q-1):
print('Generating e that is relatively prime to (p-1)*(q-1)...')
while True:
# Keep trying random numbers for e until one is valid:
e = random.randrange(2 ** (keySize - 1), 2 ** (keySize))
if cryptomath.gcd(e, (p - 1) * (q - 1)) == 1:
break
# Step 3: Calculate d, the mod inverse of e:
print('Calculating d that is mod inverse of e...')
d = cryptomath.findModInverse(e, (p - 1) * (q - 1))
publicKey = (n, e)
privateKey = (n, d)
print('Public key:', publicKey)
print('Private key:', privateKey)
return (publicKey, privateKey)
def makeKeyFiles(name, keySize):
# Creates two files 'x_pubkey.txt' and 'x_privkey.txt' (where x
# is the value in name) with the n,e and d,e integers written in
# them, delimited by a comma.
# Our safety check will prevent us from overwriting our old key files:
if os.path.exists('%s_pubkey.txt' % (name)) or os.path.exists('%s_privkey.txt' % (name)):
sys.exit('WARNING: The file %s_pubkey.txt or %s_privkey.txt already exists! Use a different name or delete these files and re-run this program.' % (name, name))
publicKey, privateKey = generateKey(keySize)
print()
print('The public key is a %s and a %s digit number.' % (len(str(publicKey[0])), len(str(publicKey[1]))))
print('Writing public key to file %s_pubkey.txt...' % (name))
fo = open('%s_pubkey.txt' % (name), 'w')
fo.write('%s,%s,%s' % (keySize, publicKey[0], publicKey[1]))
fo.close()
print()
print('The private key is a %s and a %s digit number.' % (len(str(publicKey[0])), len(str(publicKey[1]))))
print('Writing private key to file %s_privkey.txt...' % (name))
fo = open('%s_privkey.txt' % (name), 'w')
fo.write('%s,%s,%s' % (keySize, privateKey[0], privateKey[1]))
fo.close()
# If makePublicPrivateKeys.py is run (instead of imported as a module),
# call the main() function:
if __name__ == '__main__':
main()
Publickeycipher
# Public Key Cipher
# https://www.nostarch.com/crackingcodes/ (BSD Licensed)
import sys, math
# The public and private keys for this program are created by
# the makePublicPrivateKeys.py program.
# This program must be run in the same folder as the key files.
SYMBOLS = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz1234567890 !?.'
def main():
# Runs a test that encrypts a message to a file or decrypts a message
# from a file.
filename = 'encrypted_file.txt' # The file to write to/read from.
mode = 'encrypt' # Set to either 'encrypt' or 'decrypt'.
if mode == 'encrypt':
message = 'Journalists belong in the gutter because that is where the ruling classes throw their guilty secrets. Gerald Priestland. The Founding Fathers gave the free press the protection it must have to bare the secrets of government and inform the people. Hugo Black.'
pubKeyFilename = 'al_sweigart_pubkey.txt'
print('Encrypting and writing to %s...' % (filename))
encryptedText = encryptAndWriteToFile(filename, pubKeyFilename, message)
print('Encrypted text:')
print(encryptedText)
elif mode == 'decrypt':
privKeyFilename = 'al_sweigart_privkey.txt'
print('Reading from %s and decrypting...' % (filename))
decryptedText = readFromFileAndDecrypt(filename, privKeyFilename)
print('Decrypted text:')
print(decryptedText)
def getBlocksFromText(message, blockSize):
# Converts a string message to a list of block integers.
for character in message:
if character not in SYMBOLS:
print('ERROR: The symbol set does not have the character %s' % (character))
sys.exit()
blockInts = []
for blockStart in range(0, len(message), blockSize):
# Calculate the block integer for this block of text:
blockInt = 0
for i in range(blockStart, min(blockStart + blockSize, len(message))):
blockInt += (SYMBOLS.index(message[i])) * (len(SYMBOLS) ** (i % blockSize))
blockInts.append(blockInt)
return blockInts
def getTextFromBlocks(blockInts, messageLength, blockSize):
# Converts a list of block integers to the original message string.
# The original message length is needed to properly convert the last
# block integer.
message = []
for blockInt in blockInts:
blockMessage = []
for i in range(blockSize - 1, -1, -1):
if len(message) + i < messageLength:
# Decode the message string for the 128 (or whatever
# blockSize is set to) characters from this block integer:
charIndex = blockInt // (len(SYMBOLS) ** i)
blockInt = blockInt % (len(SYMBOLS) ** i)
blockMessage.insert(0, SYMBOLS[charIndex])
message.extend(blockMessage)
return ''.join(message)
def encryptMessage(message, key, blockSize):
# Converts the message string into a list of block integers, and then
# encrypts each block integer. Pass the PUBLIC key to encrypt.
encryptedBlocks = []
n, e = key
for block in getBlocksFromText(message, blockSize):
# ciphertext = plaintext ^ e mod n
encryptedBlocks.append(pow(block, e, n))
return encryptedBlocks
def decryptMessage(encryptedBlocks, messageLength, key, blockSize):
# Decrypts a list of encrypted block ints into the original message
# string. The original message length is required to properly decrypt
# the last block. Be sure to pass the PRIVATE key to decrypt.
decryptedBlocks = []
n, d = key
for block in encryptedBlocks:
# plaintext = ciphertext ^ d mod n
decryptedBlocks.append(pow(block, d, n))
return getTextFromBlocks(decryptedBlocks, messageLength, blockSize)
def readKeyFile(keyFilename):
# Given the filename of a file that contains a public or private key,
# return the key as a (n,e) or (n,d) tuple value.
fo = open(keyFilename)
content = fo.read()
fo.close()
keySize, n, EorD = content.split(',')
return (int(keySize), int(n), int(EorD))
def encryptAndWriteToFile(messageFilename, keyFilename, message, blockSize=None):
# Using a key from a key file, encrypt the message and save it to a
# file. Returns the encrypted message string.
keySize, n, e = readKeyFile(keyFilename)
if blockSize == None:
# If blockSize isn't given, set it to the largest size allowed by the key size and symbol set size.
blockSize = int(math.log(2 ** keySize, len(SYMBOLS)))
# Check that key size is large enough for the block size:
if not (math.log(2 ** keySize, len(SYMBOLS)) >= blockSize):
sys.exit('ERROR: Block size is too large for the key and symbol set size. Did you specify the correct key file and encrypted file?')
# Encrypt the message:
encryptedBlocks = encryptMessage(message, (n, e), blockSize)
# Convert the large int values to one string value:
for i in range(len(encryptedBlocks)):
encryptedBlocks[i] = str(encryptedBlocks[i])
encryptedContent = ','.join(encryptedBlocks)
# Write out the encrypted string to the output file:
encryptedContent = '%s_%s_%s' % (len(message), blockSize, encryptedContent)
fo = open(messageFilename, 'w')
fo.write(encryptedContent)
fo.close()
# Also return the encrypted string:
return encryptedContent
def readFromFileAndDecrypt(messageFilename, keyFilename):
# Using a key from a key file, read an encrypted message from a file
# and then decrypt it. Returns the decrypted message string.
keySize, n, d = readKeyFile(keyFilename)
# Read in the message length and the encrypted message from the file:
fo = open(messageFilename)
content = fo.read()
messageLength, blockSize, encryptedMessage = content.split('_')
messageLength = int(messageLength)
blockSize = int(blockSize)
# Check that key size is large enough for the block size:
if not (math.log(2 ** keySize, len(SYMBOLS)) >= blockSize):
sys.exit('ERROR: Block size is too large for the key and symbol set size. Did you specify the correct key file and encrypted file?')
# Convert the encrypted message into large int values:
encryptedBlocks = []
for block in encryptedMessage.split(','):
encryptedBlocks.append(int(block))
# Decrypt the large int values:
return decryptMessage(encryptedBlocks, messageLength, (n, d), blockSize)
# If publicKeyCipher.py is run (instead of imported as a module) call
# the main() function.
if __name__ == '__main__':
main()
ReverseCipher
# Reverse Cipher
# https://www.nostarch.com/crackingcodes (BSD Licensed)
message = 'Three can keep a secret, if two of them are dead.'
translated = ''
i = len(message) - 1
while i >= 0:
translated = translated + message[i]
i = i - 1
print(translated)
Creating cipher using Python
# Affine Cipher
# https://www.nostarch.com/crackingcodes (BSD Licensed)
import sys, pyperclip, cryptomath, random
SYMBOLS = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz1234567890 !?.'
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"""
myKey = 2894
myMode = 'encrypt' # Set to either 'encrypt' or 'decrypt'.
if myMode == 'encrypt':
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)
print('Full %sed text copied to clipboard.' % (myMode))
def getKeyParts(key):
keyA = key // len(SYMBOLS)
keyB = key % len(SYMBOLS)
return (keyA, keyB)
def checkKeys(keyA, keyB, mode):
if keyA == 1 and mode == 'encrypt':
sys.exit('Cipher is weak if key A is 1. Choose a different key.')
if keyB == 0 and mode == 'encrypt':
sys.exit('Cipher is weak if key B is 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 SYMBOLS:
# Encrypt the symbol:
symbolIndex = SYMBOLS.find(symbol)
ciphertext += SYMBOLS[(symbolIndex * keyA + keyB) % len(SYMBOLS)]
else:
ciphertext += symbol # Append the symbol without encrypting.
return ciphertext
def decryptMessage(key, message):
keyA, keyB = getKeyParts(key)
checkKeys(keyA, keyB, 'decrypt')
plaintext = ''
modInverseOfKeyA = cryptomath.findModInverse(keyA, len(SYMBOLS))
for symbol in message:
if symbol in SYMBOLS:
# Decrypt the symbol:
symbolIndex = SYMBOLS.find(symbol)
plaintext += SYMBOLS[(symbolIndex - keyB) * modInverseOfKeyA % len(SYMBOLS)]
else:
plaintext += symbol # Append the symbol without decrypting.
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__':
main()
Hacking a cipher
# Affine Cipher Hacker
# https://www.nostarch.com/crackingcodes (BSD Licensed)
import pyperclip, affineCipher, detectEnglish, cryptomath
SILENT_MODE = False
def main():
# You might want to copy & paste this text from the source code at
# https://www.nostarch.com/crackingcodes/affineHacker.py
myMessage = """"5QG9ol3La6QI93!xQxaia6faQL9QdaQG1!!axQARLa!!AuaRLQADQALQG93!xQxaGaAfaQ1QX3o1RQARL9Qda!AafARuQLX1LQALQI1iQX3o1RN"Q-5!1RQP36ARu"""
hackedMessage = hackAffine(myMessage)
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 hacked message to clipboard:')
print(hackedMessage)
pyperclip.copy(hackedMessage)
else:
print('Failed to hack encryption.')
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)
print('(Press Ctrl-C or Ctrl-D to quit at any time.)')
# Brute-force by looping through every possible key
for key in range(len(affineCipher.SYMBOLS) ** 2):
keyA = affineCipher.getKeyParts(key)[0]
if cryptomath.gcd(keyA, len(affineCipher.SYMBOLS)) != 1:
continue
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 hack:')
print('Key: %s' % (key))
print('Decrypted message: ' + decryptedText[:200])
print()
print('Enter D if done, anything else to continue hacking:')
response = input('> ')
if response.strip().upper().startswith('D'):
return decryptedText
return None
# If affineHacker.py is run (instead of imported as a module)
# call the main() function.
if __name__ == '__main__':
main()
Cipher encrypt/decrypt
# Caesar Cipher
# https://www.nostarch.com/crackingcodes (BSD Licensed)
import pyperclip
# The string to be encrypted/decrypted:
message = 'This is my secret message.'
# The encryption/decryption key:
key = 13
# Whether the program encrypts or decrypts:
mode = 'encrypt' # Set to either 'encrypt' or 'decrypt'.
# Every possible symbol that can be encrypted:
SYMBOLS = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz1234567890 !?.'
# Stores the encrypted/decrypted form of the message:
translated = ''
for symbol in message:
# Note: Only symbols in the `SYMBOLS` string can be encrypted/decrypted.
if symbol in SYMBOLS:
symbolIndex = SYMBOLS.find(symbol)
# Perform encryption/decryption:
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
# Output the translated string:
print(translated)
pyperclip.copy(translated)
Password
print('Enter your password.')
typedPassword = input()
if typedPassword == 'swordfish':
print('Access Granted')
elif typedPassword == 'mary':
print('Hint: the password is a fish.')
elif typedPassword == '12345':
print('That is a really obvious password.')
else:
print('Access Denied')
print('Done')
Comments
Post a Comment