• Register
0 votes
156 views

Problem :

I need to write a program that can encode and decode caesar cipher python.
6 5 3
6,930 points

Please log in or register to answer this question.

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:

9 7 4
38,600 points
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))

 

10 6 4
31,120 points

Related questions

1 vote
1 answer 17 views
17 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, 2020 LizzyM 6.1k points
0 votes
1 answer 36 views
36 views
Problem: how java provides a class Base64 to deal with encryption? You can encrypt and decrypt your data by using provided methods. You need to import java.util.Base64 in your source file to use its methods. how much class provides different encoders and decoders to encrypt information at each level.
asked Nov 6, 2020 Mashhoodch 6.7k points
1 vote
1 answer 110 views
110 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, 2020 samhaz 5k points
0 votes
1 answer 6 views
6 views
Problem: Write a Python program to get next day of a given date.Date is provided as day, month and year The input provided is always valid. Output should be day-month-year. Hint: print(day,"-",month,"-",year) will display day-month-yearAlso identify the test data and use it to test the program.
asked Jan 21 Mashhoodch 6.7k points
1 vote
1 answer 370 views
370 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, 2020 samhaz 5k points
1 vote
1 answer 155 views
155 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, 2020 LizzyM 6.1k points
0 votes
1 answer 11 views
11 views
I'm stuck in below question plz explain it. Suppose u and v both denote sets in Python. Under what condition can we guarantee that u|v == u^v? I have tried by considering set values as 1,2,3 & 4,5,6.I'm getting answer as v should be subset of u.likewise what should be the correct condition
asked Oct 25, 2020 psandprop 2.4k points
0 votes
1 answer 10 views
10 views
Problem: Guys i am struggling to calculate subtotal and gratuaty?Please suggest any code.
asked Nov 2, 2020 Mubashi-Question 1.7k points
1 vote
1 answer 30 views
30 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, 2020 Gavin 15.3k points
3 votes
1 answer 2.9K views
2.9K views
Problem: Hello good soul, I am a student of basic java programming. I was solving beginner-level problems from there. Right now I got a problem that says, write a program that squares an integer and prints the result. Well, I am not one of those who always look solution for their assignment on StackOverflow or other sites. I just want to learn the process. Thanks for your help.
asked Mar 24, 2020 Gavin 15.3k points