How to repeat alphabet Ceaser Cipher [closed] - python

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!

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

Python Encryption program

I am trying to write a substitution encryption program where it shifts the alphabet according to a random number. This is done letter by letter or character by character
This is the error in which I get.
File "./encrypt.py", line 35, in <module>
print("after encryption: ", encrypt(text))
File "./encrypt.py", line 26, in encrypt
cipher = cipher + chr((ord(char) + str(function1()) - 65) % 27 + 65) TypeError: unsupported operand type(s) for +: 'int' and 'str'
Is there any solutions out there????
import random
text = input("enter string: ")
number = 0
number += len(text)
def encrypt(string):
def otp(filename):
file = open(filename + ".txt", "a")
file.write(str(function1()) + "\n")
file.close()
def function1():
for num in range(number):
shift = str(random.randint(1,26))
print(shift)
cipher = ''
for char in string:
if char == ' ':
cipher = cipher + chr((ord(char) + str(function1()) - 65) % 27 + 65)
otp("onetimepad")
elif char.isupper():
cipher = cipher + chr((ord(char) + str(function1()) - 65) % 27 + 65)
otp("onetimepad")
else:
cipher = cipher + chr((ord(char) + str(function1()) - 97) % 27 + 97)
otp("onetimepad")
return cipher
print("original string: ", text)
print("after encryption: ", encrypt(text))
The error message is quite clear. The cited line of code has only two + operations, and the first one clearly violates the available definitions of +
ord(char) + str(function1())
You have an integer on the left; on the right, you explicitly converted the return value to string. Decide what you're trying to do and fix your expression. It seems that you're trying to do an integer calculation of a new ordinal value. The solution may be simply to not convert the function's return value.

Caesar Cypher Python using RAD software

So currently I am working on a Caesar cypher app, my code looks like this (coded by RAD software https://anvil.works/)
The problem is that I don't get any output when I try to run the program and I think that it could be self.text_area_2 = cipher_encrypt(plain_text, key). I'm not sure if I'm using the correct statement to display the output correctly.
What statement should I use instead? Am I doing the right thing?
from ._anvil_designer import Form2Template
from anvil import *
class Form2(Form2Template):
def __init__(self, **properties):
# Set Form properties and Data Bindings.
self.init_components(**properties)
def button_1_click(self, **event_args):
def cipher_encrypt(plain_text, key):
plain_text = self.text_area_1.text
key = self.text_box_1.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 + key) % 26 + ord('A')
c_new = chr(c_shifted)
encrypted += c_new
elif c.islower(): #check if its a lowecase character
# subtract the unicode of 'a' to get index in [0-25) range
c_index = ord(c) - ord('a')
c_shifted = (c_index + key) % 26 + ord('a')
c_new = chr(c_shifted)
encrypted += c_new
elif c.isdigit():
# if it's a number,shift its actual value
c_new = (int(c) + key) % 10
encrypted += str(c_new)
else:
# if its neither alphabetical nor a number, just leave it like that
encrypted += c
return encrypted
self.text_area_2 = cipher_encrypt(plain_text, key)

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 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

Categories