Decrypting a Caesar Cypher password in Python - python

I'm taking a programming class using Python, and for our final project we're looking to encrypt and decrypt a password. We start with a password list:
#The password list - We start with it populated for testing purposes
passwords = [["yahoo","XqffoZeo"],["google","CoIushujSetu"]]
Then we have our encryption key:
#The encryption key for the caesar cypher
encryptionKey=16
And the code which asks to look up the password:
if(choice == '2'): #Lookup at password
print("Which website do you want to lookup the password for?")
for keyvalue in passwords:
print(keyvalue[0])
passwordToLookup = input()
for key, value in passwords:
if key == passwordToLookup:
print(value)
What I need is for the print(value) to print the opposite of the key, so that the password is decrypted when it prints out. Can anyone point me in the right direction please?

Caesar-cipher replaces each letter in the alphabet by a fixed number of position. Thus, if encryptionKey is 16, then letter a --> q and z --> p.
def encrypt(text):
result = ""
encryptionKey = 16
for i in range(len(text)):
char = text[i]
if (char.isupper()): #check if upper case
result += chr((ord(char) + encryptionKey-65)%26 + 65)
else:
result += chr((ord(char) + encryptionKey-97)%26 + 97)
return result
text = "XqffoZeo"
print ("Text : "+ text)
print ("Encrypted : " + encrypt(text))
then your output will be:
Output:
Text : XqffoZeo
Encrypted : NgvvePue

Related

Encoding a password with special characters

I am in an into to Programming class and the assignment is in part to shift the letters of a valid password by +1 if it is a letter or number and -1 if it is a !##$ special character. I have most of it working with my below code but I always get the wrong output for the special characters. If I use to the code of anything high like 128 then I get the wrong symbol.
I am using the code from an encryption program from the other week and slowly changing things but I feel like this is too involved for something simple
If I enter the password UMA#augusta2020 I need to get the output VNB?bvhvtub3131 but I either end up with a space, b, or wrong symbol when I change the code input between 26,64,96,128, etc.
I have updated the code to fix small errors
def main():
print("This program validates and encrypts a password")
print()
main()
# The Encryption Function
def cipher_encrypt(plain_text):
encrypted = ""
for c in plain_text:
if c.isupper(): #check if it's an uppercase character
c_index = ord(c) - ord('A')
# shift the current character by key positions
c_shifted = (c_index + 1) % 26 + ord('A')
c_new = chr(c_shifted)
encrypted += c_new
elif c.islower(): #check if its a lowecase character
c_index = ord(c) - ord('a')
c_shifted = (c_index + 1) % 26 + ord('a')
c_new = chr(c_shifted)
encrypted += c_new
elif c.isdigit():
# if it's a number,shift its value
c_new = (int(c) + 1) % 10
encrypted += str(c_new)
else:
# if its neither alphabetical nor a number, -1
c_shifted = (c_index - 1) % 128 + ord('a')
c_new = chr(c_shifted)
encrypted += c_new
return encrypted
plain_text =input("Enter your Password: ")
print()
ciphertext = cipher_encrypt(plain_text)
print()
print("Your Password: ", plain_text)
print()
print("Your password is valid and encrypted it is: ", ciphertext)
print()
Here is a much cleaner approach:
def cipher_encrypt(plain_text):
alpha = 'abcdefghijklmnopqrstuvwxyz'
digits = '0123456789'
puncs = '!"#$%&\'()*+,-./:;<=>?#[\\]^_`{|}~'
encrypted_text = ''
for c in plain_text:
if c.lower() in alpha:
c_index = alpha.index(c.lower())
e_index = (c_index + 1)%len(alpha)
if c == c.lower():
encrypted_text += alpha[e_index]
else:
encrypted_text += alpha[e_index].upper()
elif c in digits:
c_index = digits.index(c)
e_index = (c_index + 1)%len(digits)
encrypted_text += digits[e_index]
else:
c_index = puncs.index(c)
e_index = (c_index +len(puncs) - 1)%len(puncs)
encrypted_text += puncs[e_index]
return encrypted_text
In this approach I deal with each caharcter in plain text by:
Determining idf the char is part of alpha by making use of the c.lower() function to isolate alpha chars and then find an index modulo the len of alpha. Then I determine if I need an uppercase char or lower case in the encrypted text.
I use the same modulo approach for digits, but don't have to worry about upper and lower, finally
I find the index for the punctuations found in the plain_text

How to leave punctuation unchanged in Caesar Cipher? - Python

I'm having trouble trying to leave the punctuation unchanged while encrypting or decrypting a message
# encryption
message = input("Enter a message to be encrypted: ") # user inputs message to be encrypted
offset = int(input ("Enter an offset: ")) # user inputs offset
print ("\t")
encrypt = " "
for char in message:
if char == " ":
encrypt = encrypt + char
elif char.isupper():
encrypt = encrypt + chr((ord(char) + offset - 65) % 26 + 65) # for uppercase Z
else:
encrypt = encrypt + chr((ord(char) + offset - 97) % 26 + 97) # for lowercase z
print ("Your original message:",message)
print ("Your encrypted message:",encrypt)
print ("\t")
An example of what the output looks like if I try to encrypt a message with punctuation (offset of 8):
Your original message: Mr. and Mrs. Dursley, of number four Privet Drive, were proud to say that they were perfectly normal, thank you very much.
Your encrypted message: Uzj ivl Uzaj Lczatmgh wn vcujmz nwcz Xzqdmb Lzqdmh emzm xzwcl bw aig bpib bpmg emzm xmznmkbtg vwzuith bpivs gwc dmzg uckp
I suspect this program is changing the punctuation to letters due to the
chr(ord(char)) function.
Is there any way I can add in the actual punctuation to the encrypted message without changing the code too much? I would really appreciate any help, thank you!
You can get your desired result with just a one liner change by handling all non alpha characters in the first conditional using isalpha()
# encryption
message = input("Enter a message to be encrypted: ") # user inputs message to be encrypted
offset = int(input ("Enter an offset: ")) # user inputs offset
print ("\t")
encrypt = " "
for char in message:
if not char.isalpha(): #changed
encrypt = encrypt + char
elif char.isupper():
encrypt = encrypt + chr((ord(char) + offset - 65) % 26 + 65) # for uppercase Z
else:
encrypt = encrypt + chr((ord(char) + offset - 97) % 26 + 97) # for lowercase z
print ("Your original message:",message)
print ("Your encrypted message:",encrypt)
print ("\t")
Same as you do it with a space, you can do it with any character.
if char in string.punctuation+' ':
encrypt = encrypt + char

Interactive rot13 cipher

I have a code and I'm having trouble making it interactive.
Here's the problem:
"""Write a function called rot13 that uses the Caesar cipher to encrypt a message. The Caesar cipher works like a substitution cipher but each character is replaced by the character 13 characters to “its right” in the alphabet. So for example the letter “a” becomes the letter “n”. If a letter is past the middle of the alphabet then the counting wraps around to the letter “a” again, so “n” becomes “a”, “o” becomes “b” and so on. Hint: Whenever you talk about things wrapping around its a good idea to think of modulo arithmetic (using the remainder operator)."""
Here's the code to this problem:
def rot13(mess):
alphabet = 'abcdefghijklmnopqrstuvwxyz'
encrypted = ''
for char in mess:
if char == ' ':
encrypted = encrypted + ' '
else:
rotated_index = alphabet.index(char) + 13
if rotated_index < 26:
encrypted = encrypted + alphabet[rotated_index]
else:
encrypted = encrypted + alphabet[rotated_index % 26]
return encrypted
def main():
print(rot13('abcde'))
print(rot13('nopqr'))
print(rot13(rot13('since rot thirteen is symmetric you should see this message')))
if __name__ == "__main__":
main()
I want to make it interactive where you can input any message and you can rotate the letters however many times as you want. Here is my attempt. I understand you'd need two parameters to pass, but I'm clueless as to how to replace a few items.
Here's my attempt:
def rot13(mess, char):
alphabet = 'abcdefghijklmnopqrstuvwxyz'
encrypted = ''
for char in mess:
if char == ' ':
encrypted = encrypted + ' '
else:
rotated_index = alphabet.index(char) + mess
if rotated_index < 26:
encrypted = encrypted + alphabet[rotated_index]
else:
encrypted = encrypted + alphabet[rotated_index % 26]
return encrypted
def main():
messy_shit = input("Rotate by: ")
the_message = input("Type a message")
print(rot13(the_message, messy_shit))
if __name__ == "__main__":
main()
I don't know where my input should be taking place in the function. I have a feeling it could be encrypted?
This is probably what you're looking for. It rotates the message by the messy_shit input.
def rot13(mess, rotate_by):
alphabet = 'abcdefghijklmnopqrstuvwxyz'
encrypted = ''
for char in mess:
if char == ' ':
encrypted = encrypted + ' '
else:
rotated_index = alphabet.index(char) + int(rotate_by)
if rotated_index < 26:
encrypted = encrypted + alphabet[rotated_index]
else:
encrypted = encrypted + alphabet[rotated_index % 26]
return encrypted
def main():
messy_shit = input("Rotate by: ")
the_message = input("Type a message")
print(rot13(the_message, messy_shit))
def rot(message, rotate_by):
'''
Creates a string as the result of rotating the given string
by the given number of characters to rotate by
Args:
message: a string to be rotated by rotate_by characters
rotate_by: a non-negative integer that represents the number
of characters to rotate message by
Returns:
A string representing the given string (message) rotated by
(rotate_by) characters. For example:
rot('hello', 13) returns 'uryyb'
'''
assert isinstance(rotate_by, int) == True
assert (rotate_by >= 0) == True
alphabet = 'abcdefghijklmnopqrstuvwxyz'
rotated_message = []
for char in message:
if char == ' ':
rotated_message.append(char)
else:
rotated_index = alphabet.index(char) + rotate_by
if rotated_index < 26:
rotated_message.append(alphabet[rotated_index])
else:
rotated_message.append(alphabet[rotated_index % 26])
return ''.join(rotated_message)
if __name__ == '__main__':
while True:
# Get user input necessary for executing the rot function
message = input("Enter message here: ")
rotate_by = input("Enter your rotation number: ")
# Ensure the user's input is valid
if not rotate_by.isdigit():
print("Invalid! Expected a non-negative integer to rotate by")
continue
rotated_message = rot(message, int(rotate_by))
print("rot-ified message:", rotated_message)
# Allow the user to decide if they want to continue
run_again = input("Continue? [y/n]: ").lower()
while run_again != 'y' and run_again != 'n':
print("Invalid! Expected 'y' or 'n'")
run_again = input("Continue? [y/n]: ")
if run_again == 'n':
break
Note: It's more efficient to create a list of characters then join them to produce a string instead of using string = string + char. See Method 6 here and the Python docs here. Also, be aware that our rot function only works for lowercase letters of the alphabet. It'll break if you try to rot a message with uppercase characters or any character that isn't in alphabet.

Python code hangs after entering all inputs

Hi guys Here is my error:
Phrase to be Decrypted: n
Shift keyword, Word only: ]YY
The code will write the Decryption to a file of your choice
Please input the number to decrypt by: 44
*hang*
Inputs:
Phrase: n
Keyword: ]YY
Decryption shift: 44
What it should do is decrypt the Phrase into Chicken and the keyword into Egg. The number I have input is the shift that the code performs to scramble the keyword.
Here is my code:
import getpass
import random #imports random module
import codecs #imports codecs module for encode task (UTF8)
import time
w = getpass.getpass("Input the Password: ")
with open('Password.txt') as f:
found = False
for line in f:
if w in line:
import random
import codecs
phrase = input('Phrase to be Decrypted: ') #Asks user to input a phrase
shift_key = input("Shift keyword, Word only: ") #Asks user to input a keyword
print ("The code will write the Decryption to a file of your choice")
Encryption_Base = ["abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890,./;:<>?'##~]}[{=+-_)(*&^%$£!`¬\|"] #Encryption base. Randint uses this.
key_encryption = int(input("Please input the number to decrypt by: ")) #Grabs a random number between 0 and 94
Cipher = '' #Cipher is blank, to be used later.
for c in shift_key: #Looks for a letter in the keyword, in this case c
if c in Encryption_Base: #Looks for the same letter in the string.
Cipher -= Encryption_Base(Encryption_Base.index(c)-(key_encryption)/(len(Encryption_Base))) #Turns the keyword into a different letter
def Keyword_Encryption(key, phrase): #Defines the new variable
if len(phrase) < len(key): #If the phrase is longer than the key
while len(phrase) < len(key): #While the phrase is longer than the key
length_to_add = len(phrase) + len(key) #Shorten the key to the length of the phrase
key = key + key[0:length_to_add]
elif len(phrase) > len(key): #However if the phrase is shorter than the key
while len(phrase) > len(key):
length_to_sub = len(key) + (len(key) + len(phrase)) #Make both of them equal.
key = key[0:length_to_sub]
else:
pass #Anything else stops the code.
shifted_phrase = '' #Shifted phrase is blank for later
for i in range(len(phrase)): #Find a letter in the length of the phrase
new_letter = (ord(key[i]) + 50) - (ord(phrase[i]) + 50) - 50 #Change the order of the key
if new_letter < 1220: #If the new letter is higher than 1220
new_letter = chr(new_letter + 26) #Create an extra character
else:
new_letter = chr(new_letter) #Anything else creates a new character (could be overflow?)
shifted_phrase = shifted_phrase - new_letter #Adds the new letter onto the encrypted phrase
return shifted_phrase
result = Keyword_Encryption(Cipher, phrase) #Adds the Cipher and phrase to keyword encryption so that the user knows what key to use to decrypt it.
print (" ")
print (":-) " * 3 + "Encrypting Phrase... " + ":-) " * 3) #All of ths makes it look pretty
print (":-) " * 3 + "Done! " + ":-) " * 3) #
print (" ") #
print ('Here is your Encrypted Phrase:' + (result) + (Cipher) + (str(key_encryption))) #Finally prints the result
time.sleep(2)
FileName = input("Enter a filename for the encrypted phrase and key to be written to: ") + ".txt"
file = codecs.open(FileName, "w", encoding = "utf8") #Opens the file Encrypted.txt and encodes it in UTF to support unicode.
file.write (str(result) + " " + (Cipher) + " " + (str(key_encryption))) #Writes the phrase and key seperately to aid the user
file.close() #Closes the file
k=input("Prompt: ")
if not found:
print("Access Denied")
time.sleep(5)
Any help would be greatly appreciated :)
EDIT:
New error:
Phrase to be Decrypted: n
Shift keyword, Word only: ]YY
The code will write the Decryption to a file of your choice
Please input the number to decrypt by: 44
Traceback (most recent call last):
File "E:\Python\Password Encryption\Decryption.py", line 56, in <module>
result = Keyword_Encryption(Cipher, phrase) #Adds the Cipher and phrase to keyword encryption so that the user knows what key to use to decrypt it.
File "E:\Python\Password Encryption\Decryption.py", line 46, in Keyword_Encryption
new_letter = (ord(key[i]) + 50) - (ord(phrase[i]) + 50) - 50 #Change the order of the key
IndexError: string index out of range

Brute force decryption python

Hello I am trying to brute force decrypt a word 58 times but my code keeps adding more characters for every loop it does. Has anyone got any idea what I am doing wrong I just learnt python 3
Here is my attempt to decrypt
word = input("Please enter the encrypted word: ")
message = ""
times = 0
for i in range(58):
for ch in word:
val=ord(ch)
times += 1
val = (val-times)
if val > ord('z'):
val = ord('a') + (val - ord('z')-1)
message +=chr(val)
print("Here is your original message: ", message)
Is this what you're looking for?
word = input("Please enter the encrypted word: ")
message = ""
times = 0
for i in range(58):
message = ""
for ch in word:
val=ord(ch)
val = (val-times)
if val > ord('z'):
val = ord('a') + (val - ord('z')-1)
message +=chr(val)
print("Here is your encrypted message: ", message)
times += 1
Knowing what kind of encryption was used would make this a much easier problem to solve.

Categories