Caesar Cipher Function in Python

Caesar Cipher encryption in Python

You just need to move it forward an indentation to be in the function

def encrypt(plaintext):
ciphertext = ""
for i in range(0, len(plaintext)):
for j in range(0, len(alphabet)):
if plaintext[i] == alphabet[j]:
ciphertext += alphabet[(j+3) % 26]
print("Encrypted Message:", ciphertext)

Or you could return the value and print it:

def encrypt(plaintext):
ciphertext = ""
for i in range(0, len(plaintext)):
for j in range(0, len(alphabet)):
if plaintext[i] == alphabet[j]:
ciphertext += alphabet[(j+3) % 26]
return "Encrypted Message: " + ciphertext

print(encrypt("xyza"))

Caesar Cipher python with alphabet input

I see this is your first question. Thanks for asking.

I think what you want your code to encrypt a full length script using the function you built above. So, what your function does is it takes a letter as target and shifts it.

This can easily be applied to a string by iterating over its elements.

I have provided the correct implementation for your query with some tweaks here :

alphabet = "abcdefghijklmnopqrstuvwxyz"

def cypher(target, shift):
for index in range(len(alphabet)):
if alphabet[index] == target:
x = index + shift
y = x % len(alphabet)
return (alphabet[y])

string = "i am joe biden"
shift = 3 # Suppose we want to shift it for 3
encrypted_string = ''
for x in string:
if x == ' ':
encrypted_string += ' '
else:
encrypted_string += cypher(x, shift)

print(encrypted_string)

shift = -shift # Reverse the cypher
decrypted_string = ''
for x in encrypted_string:
if x == ' ':
decrypted_string += ' '
else:
decrypted_string += cypher(x, shift)

print(decrypted_string)

How to write a Ceaser Cipher Python

Mathematically, if we see encryption technique in Caesar cipher, then the formula to get encrypted letter is:

c = (x+n) mod 26, 

where c is place value of encrypted letter, x is place value of actual letter and n is the shift.
Similarly, to decrypt each letter, we use the formula given below:

c = (x-n) mod 26

You can use my below code to get an idea of how to implement Caesar Cipher:

def encrypt(plain_text, s):
encrypted_text = ''
for i in range(len(plain_text)):
if plain_text[i] == ' ':
encrypted_text = encrypted_text + plain_text[i]
elif plain_text[i].isupper():
encrypted_text = encrypted_text + chr((ord(plain_text[i])+s-65)%26+65)
else:
encrypted_text = encrypted_text + chr((ord(plain_text[i])+s-97)%26+97)
return encrypted_text

def decrypt(encrypt_text, s):
decrypted_text = ''
for i in range(len(encrypt_text)):
if encrypt_text[i] == ' ':
decrypted_text = decrypted_text + encrypt_text[i]
elif encrypt_text[i].isupper():
decrypted_text = decrypted_text + chr((ord(encrypt_text[i])-s-65)%26+65)
else:
decrypted_text = decrypted_text + chr((ord(encrypt_text[i])-s-97)%26+97)
return decrypted_text

plain_text = input("Input the text you would like encrypted:")
s = int(input("Enter shift:"))
encrypt_text = encrypt(plain_text, s)
print("Encrypted text: {}".format(encrypt_text))
print("Decrypted text: {}".format(decrypt(encrypt_text, s)))

Sample Output:

Input the text you would like encrypted:Taj Mahal

Enter shift:3
Encrypted text: Wdm Pdkdo
Decrypted text: Taj Mahal

caesar cipher in python no output

The function encrypt() returns a value instead of printing a value. Because of that, you must put the function inside print() when calling it so that the value returned, gets outputted to the standard output.

print(encrypt(password, encryption_digit))

A caesar cipher function that shift vowels aeiou

This will make the shifts that you require, I believe.

vowels = "aeiouAEIOU"

def encrypt(message, shift):
output = ''
for char in message:
index = vowels.find(char)
if index < 0:
output += char

else:
shift %= 5

if index >= 5:
new_index = (index + shift) % 5 + 5
else:
new_index = (index + shift) % 5
# Or, alternatively to the above 4 lines:
# new_index = (index + shift) % 5 + 5 * int(index >= 5)
new_character = vowels[new_index]
output += new_character
return output
encrypt('the quick brown fox jumped over the lazy dogs', 1)
Out[3]: 'thi qaock bruwn fux jampid uvir thi lezy dugs'
encrypt('the quick brown fox jumped over the lazy dogs'.upper(), 1)
Out[4]: 'THI QAOCK BRUWN FUX JAMPID UVIR THI LEZY DUGS'
encrypt('the quick brown fox jumped over the lazy dogs'.upper(), 13)
Out[5]: 'THU QIACK BREWN FEX JIMPUD EVUR THU LOZY DEGS'

You can simplify the 4 line if statement by embedding the check for it being upper case into the addition, using the quality that int(True) is 1 and int(False) is 0

new_index = (index + shift) % 5 + 5 * int(index >= 5)

Caesar Cipher Python Project

The big problem is not understanding group / modulus operation and some one-off errors.


In the encryption operation:

if index > len(symbols):

Indices start at zero, so if you have the normal ABC alphabet with 26 characters then Z, the character with the highest index would be at index 25. In the above code there is a highest index of 26 assumed; you'd need to use >=.

index = index - (len(symbols) + 1)

I've a strong idea that this was to make up for the previous mistake, but failed. Any operations in a group of size N will use modulo N operations. In other words, for the ABC you'd subtract N=26 here, not N=27, the + 1 should be removed (as well as a pair of parentheses as they are not needed anymore).


In the decryption operation:

if index < len(symbols):

This is the wrong assumption; indices in the range [0, N) are fine. You'd need to compare with zero here, as subtraction can lead to negative values.

index = index + len(symbols)

Now this is where the error occurs, as you now try to fix values that are already in the correct range. Fortunately you did correctly use len(symbols) instead of len(symbols) + 1.


Generally we program group operators using the modulus operator.

So you just need:

index = (symbols.find(letter) + key) % len(symbols)

during encryption, and:

index = (symbols.find(letter) - key) % len(symbols)

during decryption - without any if statements. But as you now have implemented group operations, you can also feed the encryption routine -key instead of key and get the decryption routine "for free".


Notes:

  • other (C-based) languages such as Java may have % represent a remainder, which may end up giving a negative result, so you'd have to use another mod function - Python fortunately uses an actual modulus operation;
  • if you are going to multiply or perform exponentiation in a group then you should be using functions such as modmul or modpow (i.e. pow() with 3 arguments in Python) for efficiency reasons.


Related Topics



Leave a reply



Submit