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
Related
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
The encrypt method in my program is not encrypting correctly. I thought I figured out why using debug mode; it's because it reads the spaces between words as something it has to encrypt. So I tried typing a message without spaces but it still didn't come out correctly.
I figure the issue is the if statement with the key. I tried commenting lines out, changing statements, changing the if statement to a for loop, but it still isn't correct.
def main():
vig_square = create_vig_square()
message = input("Enter a multi-word message with punctuation: ")
input_key = input("Enter a single word key with no punctuation: ")
msg = message.lower()
key = input_key.lower()
coded_msg = encrypt(msg, key, vig_square)
print("The encoded message is: ",coded_msg)
print("The decoded message is: ", msg)
def encrypt(msg,key,vig_square):
coded_msg = ""
key_inc = 0
for i in range(len(msg)):
msg_char = msg[i]
if key_inc == len(key)-1:
key_inc = 0
key_char = key[key_inc]
if msg_char.isalpha() and key_char.isalpha():
row_index = get_row_index(key_char,vig_square)
col_index = get_col_index(msg_char,vig_square)
coded_msg = coded_msg+vig_square[row_index][col_index]
else:
coded_msg = coded_msg + " "
key_inc = key_inc+1
return coded_msg
def get_col_index(msg_char, vig_square):
column_index = ord(msg_char) - 97
return column_index
def get_row_index(key_char, vig_square):
row_index = ord(key_char) - 97
return row_index
def create_vig_square():
vig_square = list()
for row in range(26):
next_row = list()
chr_code = ord('a') + row
for col in range(26):
letter = chr(chr_code)
next_row.append(letter)
chr_code = chr_code + 1
if chr_code > 122:
chr_code = ord('a')
vig_square.append(next_row)
return vig_square
main()
This example was given to us:
Enter a multi-word message with punctuation: The eagle has landed.
Enter a single word key with no punctuation: LINKED
The encoded message is: epr oejwm ukw olvqoh.
The decoded message is: the eagle has landed.
But my encoded message comes out as:
epr iloyo sif plvqoh
You have two errors:
First, you don't use all characters in the key. Change the following line:
if key_inc == len(key)-1:
key_inc = 0
to
if key_inc == len(key):
key_inc = 0
Second, you move the key pointer even if you process a non-alpha character in the message (e.g. spaces). Do it only if you encode a character, i.e. make the following change:
if msg_char.isalpha() and key_char.isalpha():
...
key_inc = key_inc+1 # Move this line here
else:
...
So currently my Caesar cipher program runs well whenever I use lowercase letters. I want it however to work when I input a word or phrase with uppercase. This is the code I have now. Hopefully y'all can help me finish this.
user defined functions
def encrypt(message, distance):
"""Will take message and rotate it the distance, in order to create an encrypted message"""
encryption = ""
for ch in message:
ordvalue = ord(ch)
cipherValue = ordvalue + distance
if cipherValue > ord("z"):
cipherValue = ord("a") + distance - (ord("z") - ordvalue + 1)
encryption += chr(cipherValue)
return encryption
def decrypt(message, distance):
"""Will decrypt the above message"""
decryption = ""
for cc in message:
ordvalue = ord(cc)
decryptValue = ordvalue - distance
if decryptValue < ord("a"):
decryptValue = ord("z") - distance - (ord("a") - ordvalue - 1)
decryption += chr(decryptValue)
return decryption
def binaryConversion(message):
"""Will convert the word into binary code"""
binary = ""
for cb in message:
binaryString = " " #Binary number
binaryNumber = ord(cb)
while binaryNumber > 0:
binaryRemainder = binaryNumber % 2
binaryNumber = binaryNumber // 2
binaryString = str(binaryRemainder) + binaryString
binary += binaryString
return binary
while loop
run = True
while run:
#input
message = input("Enter word to be encrypted: ") #original message
distance = int(input("Enter the distance value: ")) #distance letters will be moved
#variables
fancy = encrypt(message, distance)
boring = decrypt(fancy, distance)
numbers = binaryConversion(message)
#output
print("\n")
print("Your word was: ", format(message, ">20s"))
print("The distance you rotated was: ", format(distance), "\n")
print("The encryption is: ", format(fancy, ">16s"))
print("The decryption is: ", format(boring, ">16s"))
print("The binary code is: ", format(numbers)) #I know an error comes here but it will work in the end
repeat = input("Would you like to encrypt again? Y/N ")
print("\n")
if repeat == "N" or repeat == "n":
run = False
else:
run = True
Finale
print("Thank you & as Julius Caesar once said, 'Veni, vidi, vici'")
Thank you
I would suggest you approach this problem in the mindset of a mapping rather than an offset. You can build the mapping based on the offset but character processing will be easier if you use a dictionary or some other form of one to one mapping.
For example:
offset = 5
source = "abcdefghijklmnopqrstuvwxyz"
target = source[offset:]+source[:offset]
source = source + source.upper()
target = target + target.upper()
encrypt = str.maketrans(source,target)
decrypt = str.maketrans(target,source)
e = "The quick brown Fox jumped over the lazy Dogs".translate(encrypt)
print(e)
d = e.translate(decrypt)
print(d)
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
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.