• Register
search
Log In
0 votes
51 views

Problem :

I need to write a program that can encode and decode caesar cipher python.
6.9k points

2 Answers

0 votes

Solution:

PFB the program that can encode and decode caesar ciphar python

def main():
    print("This program can encode and decode Caesar Ciphers")
    inputText = input("Please enter a string of plaintext:").lower()
    inputValue = int(input("Please enter the value of the key:")) # use int(), don't eval unless you read more about it
    inputEorD = input("Please enter e (to encrypt) or d (to decrypt) ")
    codedMessage = ""

    if inputEorD == "e":
        for ch in inputText:
            codedMessage += chr((ord(ch) - 97 + inputValue)%26 + 97)
    elif inputEorD =="d":
            codedMessage += chr((ord(ch) - 97 - inputValue)%26 + 97)
    else:
        print("You did not enter E/D! Try again!!")
    print("The text inputed:", inputText,  ".Is:", inputEorD, ".By the key of",inputValue, ".To make the message", codedMessage)

main()

Further Readings:

36.1k points
edited by
0 votes

Solution:

Because you're dealing with .lower()-case letters, it's right to know that their ASCII range is [97-122].

A proper way to do the shifting circular would be to represent each letter with the range [0-25], which is done by ord(ch) - 97, and then include the key, then modulo the result with 26 so it becomes (ord(ch) - 97 + key)%26, we'll then have a result in range [0-25], including 97 will then obtain it's ASCII code:

def main():
    print("This program can encode and decode Caesar Ciphers")
    inputText = input("Please enter a string of plaintext:").lower()
    inputValue = int(input("Please enter the value of the key:")) # use int(), don't eval unless you read more about it
    inputEorD = input("Please enter e (to encrypt) or d (to decrypt) ")
    codedMessage = ""

    if inputEorD == "e":
        for ch in inputText:
            codedMessage += chr((ord(ch) - 97 + inputValue)%26 + 97)
    elif inputEorD =="d":
            codedMessage += chr((ord(ch) - 97 - inputValue)%26 + 97)
    else:
        print("You did not enter E/D! Try again!!")
    print("The text inputed:", inputText,  ".Is:", inputEorD, ".By the key of",inputValue, ".To make the message", codedMessage)

main()

Program that accepts a Text (string) and Shift value( integer) and returns the encrypted text.

// A C++ program to illustrate Caesar Cipher Technique 
#include <iostream> 
using namespace std; 

// This function receives text and shift and 
// returns the encrypted text 
string encrypt(string text, int s) 
{ 
	string result = ""; 

	// traverse text 
	for (int i=0;i<text.length();i++) 
	{ 
		// apply transformation to each character 
		// Encrypt Uppercase letters 
		if (isupper(text[i])) 
			result += char(int(text[i]+s-65)%26 +65); 

	// Encrypt Lowercase letters 
	else
		result += char(int(text[i]+s-97)%26 +97); 
	} 

	// Return the resulting string 
	return result; 
} 

// Driver program to test the above function 
int main() 
{ 
	string text="ATTACKATONCE"; 
	int s = 4; 
	cout << "Text : " << text; 
	cout << "\nShift: " << s; 
	cout << "\nCipher: " << encrypt(text, s); 
	return 0; 
} 

In cryptography, a Caesar cipher, also known as Caesar's cipher, the shift cipher, Caesar's code or Caesar shift, is one of the easiest and most broadly known encryption techniques. It is a type of substitution cipher in which every letter in the plaintext is replaced by a letter few fixed number of positions down the alphabet. Example given- with a left shift of 3, D would be replaced by A, E would become B, and so on. The process is named after Julius Caesar, who employed it in his private conformation.

Python Code:

#https://gist.github.com/nchitalov/2f2b03e5cf1e19da1525
def caesar_encrypt(realText, step):
	outText = []
	cryptText = []
	
	uppercase = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z']
	lowercase = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z']

	for eachLetter in realText:
		if eachLetter in uppercase:
			index = uppercase.index(eachLetter)
			crypting = (index + step) % 26
			cryptText.append(crypting)
			newLetter = uppercase[crypting]
			outText.append(newLetter)
		elif eachLetter in lowercase:
			index = lowercase.index(eachLetter)
			crypting = (index + step) % 26
			cryptText.append(crypting)
			newLetter = lowercase[crypting]
			outText.append(newLetter)
	return outText

code = caesar_encrypt('abc', 2)
print()
print(code)
print()

Program for Caesar Cipher in Python

def encrypt(string, shift):
 
  cipher = ''
  for char in string: 
    if char == ' ':
      cipher = cipher + char
    elif  char.isupper():
      cipher = cipher + chr((ord(char) + shift - 65) % 26 + 65)
    else:
      cipher = cipher + chr((ord(char) + shift - 97) % 26 + 97)
  
  return cipher
 
text = input("enter string: ")
s = int(input("enter shift number: "))
print("original string: ", text)
print("after encryption: ", encrypt(text, s))

 

12.8k points
edited by

Related questions

1 vote
1 answer 12 views
12 views
Problem: I am begginer in python programming language and I a very noob at it. I need a program which can can encode and decode caesar cipher in python. Can anyone help me or provide me with some sample code. Thanks in advance.
asked Apr 7 LizzyM 5.7k points
1 vote
1 answer 15 views
15 views
Problem: I wrote a program that asks the user to enter the amount of a purchase and then it sums up the total bill with 15% vat and 0.07% service tax. I wrote the program in python: vat = 0.15 sales_tax = 0.075 product_price = float(input("Please enter the ... not defined I can not solve this thing. I am new in python programming language so please help me to solve this error. Thanks in advance.
asked May 6 samhaz 5k points
1 vote
1 answer 11 views
11 views
Problem: I wrote a program in python that asks the user for a number n and prints the sum of the numbers 1 to n: x = 1, addition = 0 n = int(input('Please enter a number:')) for i in range(x, n): addition = addition + i print (addition) But when ... n): TypeError: 'tuple' object cannot be interpreted as an integer Is there any thing that is missing from my code. Please help me to solve this out.
asked Jun 10 samhaz 5k points
1 vote
1 answer 20 views
20 views
Problem: I am new in python programming language and I am very confused about programming logics. Supose, someone has given two already defined variables, i and j, write a statement that swaps their associated values. Can anyone help me with this problem?
asked Apr 9 LizzyM 5.7k points
1 vote
1 answer 16 views
16 views
Problem: I have got an assignment from my online java class and doing the assignment and can't quite figure out what I'm doing wrong. I have to write a program that finds the sum of all squares between 1 and 100. As part of the assignment, I'm required to use a "while" ... ); a++; sum = (sum + a); } System.out.println(sum); } Thanks for your positiveness and effort. I must recognise your help.
asked Mar 28 Gavin 15.2k points