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)
Related
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
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!
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)
def encrypt(string, new_string):
i = 0
if i < len(string):
if ord(string[i]) > 65 and ord(string[i]) < 97:
new_string = string[i] + encrypt(string[1:], new_string)
if ord(string[i]) >= 97 or ord(string[i]) == 32:
if not(ord(string[i])) == 32:
x = ord(string[i])
x = x + 1
y = chr(x)
new_string = new_string + y
new_string = encrypt(string[1:], new_string)
else:
new_string = new_string + ' '
new_string = encrypt(string[1:], new_string)
return new_string
string = input("Enter a message: \n")
new_string = ''
print("Encrypted message:")
print(encrypt(string, new_string))
If there is more than one uppercase letter, it will output the uppercase letters at the front of the encrypted message.
For example: 'Hello World' becomes 'HWfmmp psme'. However, the output should have been 'Hfmmp Xpsme'
translate can help you to do this kind of conversion.
from string import ascii_lowercase
def encrypt(data):
transmap = str.maketrans(ascii_lowercase, ascii_lowercase[1:] + ascii_lowercase[0])
return data.translate(transmap)
value = 'Hello World'
print(encrypt(value))
The result is Hfmmp Wpsme.
It's easy to change the encrypt function to work with a flexible offset.
from string import ascii_lowercase
def encrypt(data, offset=1):
transmap = str.maketrans(ascii_lowercase, ascii_lowercase[offset:] + ascii_lowercase[0:offset])
return data.translate(transmap)
value = 'Hello World'
print(encrypt(value, offset=2))
print(encrypt(value, offset=-1))
This will print Hgnnq Wqtnf and Hdkkn Wnqkc.
>>> import re
>>> re.sub('[a-z]',lambda x:chr(ord(x.group(0))+1),'Hello World')
'Hfmmp Wpsme'
>>>
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))