Why won't my caesar shift work properly? - python

This is the code:
text = input("What's your text: ")
shift = int(input("What's your shift: "))
def caesar_shift(text, shift):
cipher = ""
for i in text:
if i.isalpha():
stayIn = ord(i) + shift
if stayIn > ord('z'):
stayIn -= 26
lastLetter = chr(stayIn)
cipher += lastLetter
print("Your ciphertext is: ", cipher)
return cipher
caesar_shift(text, shift)
When I run it, and for example, the test is hello world, and the shift is 1, I get:
What's your text: hello world
What's your shift: 1
Your ciphertext is: i
Your ciphertext is: if
Your ciphertext is: ifm
Your ciphertext is: ifmm
Your ciphertext is: ifmmp
Your ciphertext is: ifmmpp
Your ciphertext is: ifmmppx
Your ciphertext is: ifmmppxp
Your ciphertext is: ifmmppxps
Your ciphertext is: ifmmppxpsm
Your ciphertext is: ifmmppxpsme
Why is this? Am I doing something wrong, thanks in advance!

You do
if i.isalpha():
but you have no else-clause for that if. That means that you add the last letter also when it is not a letter. Hence ifmmpp instead of ifmmp for hello.
That bit should be changed to:
if i.isalpha():
stayIn = ord(i) + shift
if stayIn > ord('z'):
stayIn -= 26
lastLetter = chr(stayIn)
cipher += lastLetter
else:
cipher += i
If you don't want the result to be printed out once for every loop, move it outside the loop.

To fix the print problem, you have:
def caesar_shift(text, shift):
cipher = ""
for i in text:
...
print("Your ciphertext is: ", cipher)
return cipher
caesar_shift(text, shift)
But you should have
def caesar_shift(text, shift):
cipher = ""
for i in text:
...
print("Your ciphertext is: ", cipher)
return cipher
caesar_shift(text, shift)
Or better yet
def caesar_shift(text, shift):
cipher = ""
for i in text:
...
return cipher
print("Your ciphertext is: ", caesar_shift(text, shift))

Related

Decrypting a Caesar Cypher password in 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

How to format output of Ceaser Cipher program python

I am trying to make a simple Ceaser cipher and have it mostly working the way I want. Except, I want to only shift the letters in the message that are uppercase and keep the lowercase letters the same. For example, if the message is "HeLLo" the program should only shift "H LL" and keep "e o" the same. As shown below.
Current output:
Message: HeLLo
Shift: 1
IFMMP
Desired output:
Message: HeLLo
Shift: 1
IeMMo
The code:
plain_text = input("Message: ")
shift = int(input("Shift: "))
def caesar(plain_text, shift):
cipher_text = ""
for ch in plain_text:
if plain_text.lower():
plain_text = plain_text
if ch.isalpha():
final_letter = chr((ord(ch) + shift - ord('A')) % 26 + ord('A'))
cipher_text += final_letter
else:
cipher_text += ch
print(cipher_text)
return cipher_text
caesar(plain_text, shift)
You could add ch != ch.lower() condition to check that the character is not a lowercase character and encrypt it only when it isn't a lowercase character.
plain_text = input("Message: ")
shift = int(input("Shift: "))
def caesar(plain_text, shift):
cipher_text = ""
for ch in plain_text:
if ch.isalpha() and ch != ch.lower():
final_letter = chr((ord(ch) + shift - ord('A')) % 26 + ord('A'))
cipher_text += final_letter
else:
cipher_text += ch
print(cipher_text)
return cipher_text
caesar(plain_text, shift)
I think you need:
def caesar(plain_text, shift):
return "".join([chr(ord(i)+shift) if i.isupper() else i for i in plain_text])
caesar(plain_text, shift)

How to repeat alphabet Ceaser Cipher [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 3 years ago.
Improve this question
I saw someone's Ceaser cipher problem and tried to write my own. I got everything done except for the fact that my alphabet needs to wrap around
#User input
user_message = input("Input the text you would like encrypted (no
characters)")
#Cipher function
def Ciphertext(message):
cipher = ""
for i in message:
#takes each letter in message
number_code = ord(i) + 3
letter_code = chr(number_code)
cipher = cipher + letter_code
return cipher
#Unencrypted function
def Plaintext(cipher):
text = ""
#loops to get each number
for i in cipher:
#takes each letter in cipher
unencrypted_code = ord(i) - 3
unencrypted_letter_code = chr(unencrypted_code)
text = text + unencrypted_letter_code
print(text)
#Prints
print("Encrypted message")
print(Ciphertext(user_message))
print("Unencrypted message")
Plaintext(Ciphertext(user_message))
Ok so I changed my code to this:
#User input
user_message = input("Input the text you would like encrypted (no
characters)")
#Cipher function
def Ciphertext(message):
cipher = ""
for i in message:
#takes each letter in message then coverts it to number subtracts the
diffrence then converts it back into characters
number_code = ord(i) + 3
letter_code = chr(number_code)
if number_code >= ord("z"):
number_code = number_code - 123
number_code = number_code + ord("a")
letter_code = chr(number_code)
cipher = cipher + letter_code
return cipher
cipher = Ciphertext(user_message)
#Unencrypted function
def Plaintext():
text = ""
#loops to get each number
for i in cipher:
#takes each letter in cipher
unencrypted_code = ord(i) - 3
if unencrypted_code >= ord("z"):
unencryted_code = unencrypted_code + 26
unencrypted_letter_code = chr(unencrypted_code)
text = text + unencrypted_letter_code
print(text)
#Prints
print("Encrypted message")
print(Ciphertext(user_message))
print("Unencrypted message")
Plaintext()
But it continues to run this:^_` when it type in xyz
The modulo operator % returns the remainder of the division of two numbers, essentially "wrapping around" a value.
You can use this behavior to wrap your cipher around. Note that if you're using ord(), you'll be given the ASCII representation of a number - note that this is different for uppercase and lowercase letters. For example, 'A' is 65, and 'a' is 97. If you plan for your cipher to preserve the case of your letters, you'll need to subtract 65 and 97, depending on case, to properly use modulo. Try something like this:
def Ciphertext(message):
cipher = ""
for i in message:
#determine if this is an uppercase or lowercase character, and treat it accordingly
number_code = 0
if i.isupper():
number_code = (((ord(i) - 65) + 3) % 26) + 65
elif i.islower():
number_code = (((ord(i) - 97) + 3) % 26) + 97
else:
number_code = ord(i)
letter_code = chr(number_code)
cipher += letter_code
return cipher
def Plaintext(cipher):
text = ""
for i in cipher:
unencrypted_code = 0
if i.isupper():
unencrypted_code = (((ord(i) - 65) - 3) % 26) + 65
elif i.islower():
unencrypted_code = (((ord(i) - 97) - 3) % 26) + 97
else:
unencrypted_code = ord(i)
letter_code = chr(unencrypted_code)
text += letter_code
return text
print (Ciphertext("Hello world! wxyz"))
print (Plaintext("Khoor zruog! zabc"))
Try it here!

Caesar Cipher with capital letters

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)

Caesar cipher python error

I am new to cryptography so I try to make a simple Caesar cipher program with python
but it keeps returning only one letter. Can anyone help please? Here's my code:
def main():
text = raw_input('input plainteks:')
key = int(raw_input('input key:'))
print("plain teks :"+text)
print("key :" +str(key))
print("hasil cipher:", encrypt(text,key))
def encrypt(text,key):
hasil = ''
for i in range(len(text)): #
char = text[i]
if (char.isupper()):
hasil += chr((ord(char) + key-65)%26 + 65)
else:
hasil += chr((ord(char) + key-97)%26 + 97)
return hasil
Here when I try to run it:
input plainteks:melody
input key:3
plain teks :melody
key :3
hasil cipher: b
Your if is not in the loop.
The following code works:
def main():
text = raw_input('input plainteks:')
key = int(raw_input('input key:'))
print("plain teks: "+text)
print("key: " +str(key))
print("hasil cipher: "+encrypt(text,key))
def encrypt(text,key):
hasil = ''
for i in range(len(text)): #
char = text[i]
if (char.isupper()):
hasil += chr((ord(char) + key-65)%26 + 65)
else:
hasil += chr((ord(char) + key-97)%26 + 97)
return hasil
main()
Also you can use the secretpy module
from secretpy import Caesar
text = 'melody'
key = 3
print(text)
cipher = Caesar()
enc = cipher.encrypt(text, key)
print(enc)

Categories