Caesar Cipher with capital letters - python

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)

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

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.

Encrypt message using recursion, python

I need to write a recursive function to encrypt a message by
converting all lowercase characters to the next character (with z transformed to a) in python.
This is my code so far, but I don't know how to go farther, or how to correct the error.
sentence = input("Enter a message: \n")
letter_number = 0
def encrypt_sentence (s, number):
if letter_number == len(sentence) - 1:
return(s)
else:
if s[letter_number] == chr(122):
return encrypt_sentence(chr(ord(s[letter_number])-25), letter_number + 1)
else:
return encrypt_sentence(chr(ord(s[letter_number])+1), letter_number + 1)
print("Encrypted message")
print(encrypt_sentence(sentence, letter_number))
I've fixed your code and now it works.
sentence = input("Enter a message: \n")
letter_number = 0
def encrypt_sentence (sentence):
if sentence:
if sentence == chr(122):
return chr(ord(sentence[letter_number])-25)
else:
return chr(ord(sentence[letter_number])+1)
print("Encrypted message")
ris = ''
for word in sentence:
ris += encrypt_sentence(word)
print(ris)

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.

New Hangman Python

I am working on a Hangman game, but I am having trouble replacing the dashes with the guessed letter. The new string just adds on new dashes instead of replacing the dashes with the guessed letter.
I would really appreciate it if anyone could help.
import random
import math
import os
game = 0
points = 4
original = ["++12345","+*2222","*+33333","**444"]
plusortimes = ["+","*"]
numbers = ["1","2","3"]
#FUNCTIONS
def firstPart():
print "Welcome to the Numeric-Hangman game!"
def example():
result = ""
ori = random.choice(original)
for i in range(2,len(ori)):
if i % 2 == 0:
result = result + ori[i] + ori[0]
else:
result = result + ori[i] + ori[1]
return ori
# def actualGame(length):
#TOP LEVEL
firstPart()
play = raw_input("Do you want to play ? Y - yes, N - no: ")
while (play == "Y" and (points >= 2)):
game = game + 1
points = points
print "Playing game #: ",game
print "Your points so far are: ",points
limit = input("Maximum wrong guesses you want to have allowed? ")
length = input("Maximum length you want for the formulas (including symbols) (must be >= 5)? ")
result = "" #TRACE
ori = random.choice(original)
for i in range(2,len(ori)):
if i % 2 == 0:
result = result + ori[i] + ori[0]
else:
result = result + ori[i] + ori[1]
test = eval(result[:-1])
v = random.choice(plusortimes) #start of randomly generated formula
va = random.choice(plusortimes)
formula = ""
while (len(formula) <= (length - 3)):
formula = formula + random.choice(numbers)
formula2 = str(v + va + formula)
kind = ""
for i in range(2,len(formula2)):
if i % 2 == 0:
kind = kind + formula2[i] + formula2[0]
else:
kind = kind + formula2[i] + formula2[1]
formula3 = eval(kind[:-1])
partial_fmla = "------"
print " (JUST TO TRACE, the program invented the formula: )" ,ori
print " (JUST TO TRACE, the program evaluated the formula: )",test
print "The formula you will have to guess has",length,"symbols: ",partial_fmla
print "You can use digits 1 to 3 and symbols + *"
guess = raw_input("Please enter an operation symbol or digit: ")
a = 0
new = ""
while a<limit:
for i in range(len(formula2)):
if (formula2[i] == partial_fmla[i]):
new = new + partial_fmla[i]
elif (formula2[i] == guess):
new[i] = guess
else:
new[i] =new + "-"
a = a+1
print new
guess = raw_input("Please enter an operation symbol or digit: ")
play = raw_input("Do you want to play ? Y - yes, N - no: ")
The following block seems problematic:
elif (formula2[i] == guess):
new[i] = guess
else:
new[i] =new + "-"
Python does not allow modification of characters within strings, as they are immutable (cannot be changed). Try appending the desired character to your new string instead. For example:
elif formula2[i] == guess:
new += guess
else:
new += '-'
Finally, you should put the definition of new inside the loop directly under, as you want to regenerate it after each guess.

Categories