How to encrypt and decrypt? - python

In Python3 I must create two functions, substitutionEncrypt and substitutionDecrypt.
substitutionEncrypt must be revised so that it removes all spaces of plain text before being encrypted and that it will generate a cipher key from a password.(Call genKeyFromPass). psw will replace key as a parameter in the function header.
substitutionDecrypt will have two parameters(cipherText, psw)
I have been given the following codes. it should return the original plainText with spaces removed.
Finally, write a top-level function, main. main should (a) use Python’s built-in input function to get a string to encrypt and a password; (b) call substitutionEncrypt to encrypt the input string; (c) print the value returned by substitutionEncrypt; (d) call substitutionDecrypt to convert the value returned by substitutionEncrypt back to
plaintext; (e) print the value returned by substitutionDecrypt.
Note: subEncrypt and subDecrypt will need to call genKeyFromPass, which call removeDupes and removeMatches. I have been given the codes below.
defSubstitutionEncrypt(plainText, key):
alphabet = "abcdefghijklmnopqrstuvwxyz "
plainText = plainText.lower()
cipherText = " "
for ch in plainText:
idx = alphabet.find(ch)
cipherText = cipherText + key[idx]
return cipherText
def removeDupes(myString):
newStr = " "
for ch in myString:
if ch not in newStr:
newStr = newStr + ch
return newStr
def removeMatches(myString, removeString):
newStr = " "
for ch in myString:
if ch not in removeString:
newStr = newStr + ch
return newStr
def genKeyFromPass(password):
key = 'abcdefghijklmnopqrstuvwxyz'
password = removeDupes(password)
lastChar = password[-1]
lastIdx = key.find(lastChar)
afterString = removeMatches(key[lastIdx+1:], password)
beforeString = removeMatches(key[:lastIdx], password)
key = password + afterString + beforeString
return key
From this code I have created:
def substitutionEncrypt(plainText, psw):
alphabet = "abcdefghijklmnopqrstuvwxyz "
newStr = plainText.lower()
cipherText = " "
genKeyFromPass(newStr)
for ch in newStr:
idx = alphabet.find(ch)
cipherText = cipherText + genKeyFromPass(psw)[idx]
return cipherText.replace(" ","")
def genKeyFromPass(psw):
key = 'abcdefghijklmnopqrstuvwxyz'
psw = removeDupes(psw)
lastChar = psw[-1]
lastIdx = key.find(lastChar)
afterString = removeMatches(key[lastIdx+1:], psw)
beforeString = removeMatches(key[:lastIdx], psw)
key = psw + afterString + beforeString
return key
def removeDupes(myString):
newStr = " "
for ch in myString:
if ch not in newStr:
newStr = newStr + ch
return newStr
def removeMatches(myString, removeString):
newStr = " "
for ch in myString:
if ch not in removeString:
newStr = newStr + ch
return newStr
print(substitutionEncrypt('the quick brown fox', 'ajax'))
I get "nukobjdualhqguyhr" as an output.
The output examples are:
subEncrypt('the quick brown fox', 'ajax')
'qdznrexgjoltkblu'
subDecrypt('qdznrexgjoltkblu', 'ajax')
'thequickbrownfox'
What am I doing wrong with my code? I have been having trouble with calling a value from another function(calling key from genKeyFromPass). Its the line before the return statement in the substitutionEncrypt. Also, how would I go about the substitutionDecrypt? I've gotten this far:
def substitutionDecrypt(cipherText, psw):
alphabet = 'abcdefghijklmnopqrstuvwxyz'
newStr = cipherText.lower()
plainText = " "
genKeyFromPass(cipherText)
for ch in cipherText:
idx = alphabet.find(ch)
return plainText.replace(" ","")

Related

Having issues Decrpyting ciphertext using own alphabet string (python)

I have it set to ask the user a word to encrpyt which works fine using my own alphabet.
My issue is trying to also get it to return the deciphered text.
So far I have it either returning the encrypted message twice or sending back a different version of the encrypted message.
I have tried using - instead of + in my for char, and it gives me a error which I thought was the correct way to do it.
alphabet = "abcdefghijklmnopqrstuvwxyz"
key = "zjrekydnqoluaxmicvpgtfbhws"
def decryptMessage(ciphertext, key):
plaintext = ""
for char in ciphertext:
if alphabet.find(char) < +1:
plaintext += key[alphabet.find(char)]
else:
plaintext += char
return plaintext
def encryptMessage(plaintext, key):
ciphertext = ""
for char in plaintext:
if alphabet.find(char) > -1:
ciphertext += key[alphabet.find(char)]
else:
ciphertext += char
return ciphertext
message = input("Type a message to encrypt: ")
encrypted = encryptMessage(message, key)
decrypted = decryptMessage(encrypted, key)
print("Plaintext message: " + message)
print("Encrypted message: " + encrypted)
print("Decrypted message: " + decrypted)
you should use the builtin str.translate
message = "hello world"
alphabet = b"abcdefghijklmnopqrstuvwxyz"
key = b"zjrekydnqoluaxmicvpgtfbhws"
encrypted = message.translate(dict(zip(alphabet,key)))
print("E:",encrypted)
decrypted = encrypted.translate(dict(zip(key,alphabet)))
print("D:",decrypted)
If you want to keep with the theme of your original code:
You need to modify as follows:
alphabet = "abcdefghijklmnopqrstuvwxyz"
key = "zjrekydnqoluaxmicvpgtfbhws"
def decryptMessage(ciphertext, key):
plaintext = ""
for char in ciphertext:
if key.find(char) > -1:
plaintext += alphabet[key.find(char)]
else:
plaintext += char
return plaintext
def encryptMessage(plaintext, key):
ciphertext = ""
for char in plaintext:
if alphabet.find(char) > -1:
ciphertext += key[alphabet.find(char)]
else:
ciphertext += char
return ciphertext
message = input("Type a message to encrypt: ")
encrypted = encryptMessage(message, key)
decrypted = decryptMessage(encrypted, key)
print("Plaintext message: " + message)
print("Encrypted message: " + encrypted)
print("Decrypted message: " + decrypted)

Caesar Cipher Translating Incorrectly

The Caesar Cipher offset is 21 and the alphabet is "abcdefghijklmnopqrstuvwxyz0123456789."
For example "Xvzcvb" Should be Equal to "Caesar", but instead, the output is "CaeNaM"
ALPHABET = "abcdefghijklmnopqrstuvwxyz0123456789."
def decrpytstr(message):
#declare variables
newString = str()
ALPHABET = int()
oneLetter = str()
newAlphabetValue = int()
#loop to assign new alphabet value
for index in range(0, len(message)):
oneLetter = message[index]
ALPHABET = ord(oneLetter)
#assinging new alphabet value
newAlphabetValue = ALPHABET - 21
#creating the new string
newString = newString + chr(newAlphabetValue)
return newString
def main():
message = input("Enter text: ")
decrpytstr(message)
newString = decrpytstr(message)
print(newString)
input("Press ENTER to exit")
main()
There are several problems
You're not actually using your original ALPHABET values
You don't account for upper case characters
We need to wrap round so that we always find something in the alphabet when we subtract the magic 21 steps
Correcting these gives us something like this...
ALPHABET = "abcdefghijklmnopqrstuvwxyz0123456789."
def decrpytstr(message):
newString = ''
#loop to assign new alphabet value
for index in range(0, len(message)):
oneLetter = message[index]
#assinging new alphabet value
newAlphabetValue = (ALPHABET.find(oneLetter.lower()) - 21) % len(ALPHABET) + (ord('A') if oneLetter.isupper() else ord('a'))
#creating the new string
newString = newString + chr(newAlphabetValue)
return newString
def main():
message = input("Enter text: ")
decrpytstr(message)
newString = decrpytstr(message)
print(newString)
input("Press ENTER to exit")
main()
https://www.asciitable.com/
As I see the ascii table, the value of b 98 will be M 77 by decrementing 21. I guess you have to deal with uppercase and lowercase separately.
[Editted] I don't fully understand what you want to achieve, but how about this?
ALPHABET = "abcdefghijklmnopqrstuvwxyz"
def decrpytstr(message):
new_string = ""
for i in range(len(message)):
character = message[i]
new_character = ALPHABET[ALPHABET.find(character) - 21 % 26]
new_string = new_string + new_character
return new_string
def main():
message = input("Enter text: ")
decrpytstr(message)
newString = decrpytstr(message)
print(newString)
input("Press ENTER to exit")
main()
Enter text: xvznvm
caesar
Press ENTER to exit

How do you reverse this string using a for loop

how do I modify the code so that it reverses the string?
str = "pizza"
def letterReverse(word):
newStr = ""
for letter in word:
newStr += letter
return newStr
print(letterReverse(str))
The problem is in your line newStr += letter. That adds the new letter to the right end of newStr, but you want to add it to the left side. So change that line to newStr = letter + newStr. You also should avoid using str as a variable name, so I changed it to oldstr. Your new code is then
oldstr = "pizza"
def letterReverse(word):
newStr = ""
for letter in word:
newStr = letter + newStr
return newStr
print(letterReverse(oldstr))
The output from that is what you want:
azzip
You can try this:
str = "pizza"
new_str = str[::-1]
If you want to modify your code just add [::-1] in your loop:
str = "pizza"
def letterReverse(word):
newStr = ""
for letter in word[::-1]:
newStr += letter
return newStr
print(letterReverse(str))

Python Pig-Latin translator

import string
def main():
filename = input("Enter the name of a file to translate into Pig Latin: ")
vowels = ['a', 'e', 'i', 'o', 'u','A','E','I','O','U']
regFile = open((filename), 'r')
Output = open('Output.txt', 'w')
for line in regFile.readlines():
pigList = line.split()
t = translate(pigList, vowels)
w = write(t, Output)
regFile.close()
input ("Press ENTER to continue: ")
def translate(pigList, vowels):
PigList2 = []
for word in pigList:
if word[-1] in string.punctuation:
actual_word = word[:-1]
ending = word[-1]
else:
actual_word = word
ending = ""
if word[0] in vowels:
PigList2.append(actual_word + "-yay" + ending)
else:
PigList2.append(actual_word[1:] + "-" + actual_word[0] + "ay" + ending)
return PigList2
def write(pigList, Output):
print(" ".join(pigList))
main()
I believe this has fixed my errors. Thank you for the help. I know have the translator working correctly and translating all the lines at once instead of one line at a time.
You're almost there. I just used used the punctuation check to split up your word into the actual word and the punctuation and then append the '-' before the first letter rather than with the "ay".
def translate(pigList, vowels):
PigList2 = []
for word in pigList:
if word[-1] in string.punctuation:
actual_word = word[:-1]
ending = word[-1]
else:
actual_word = word
ending = ""
if word[0] in vowels:
PigList2.append(actual_word + "-yay" + ending)
else:
PigList2.append(actual_word[1:] + "-" + actual_word[0] + "ay" + ending)
return PigList2

Caesar Cipher Function in Python

I'm trying to create a simple Caesar Cipher function in Python that shifts letters based on input from the user and creates a final, new string at the end. The only problem is that the final cipher text shows only the last shifted character, not an entire string with all the shifted characters.
Here's my code:
plainText = raw_input("What is your plaintext? ")
shift = int(raw_input("What is your shift? "))
def caesar(plainText, shift):
for ch in plainText:
if ch.isalpha():
stayInAlphabet = ord(ch) + shift
if stayInAlphabet > ord('z'):
stayInAlphabet -= 26
finalLetter = chr(stayInAlphabet)
cipherText = ""
cipherText += finalLetter
print "Your ciphertext is: ", cipherText
return cipherText
caesar(plainText, shift)
I realize that this answer doesn't really answer your question, but I think it's helpful anyway. Here's an alternative way to implementing the caesar cipher with string methods:
def caesar(plaintext, shift):
alphabet = string.ascii_lowercase
shifted_alphabet = alphabet[shift:] + alphabet[:shift]
table = string.maketrans(alphabet, shifted_alphabet)
return plaintext.translate(table)
In fact, since string methods are implemented in C, we will see an increase in performance with this version. This is what I would consider the 'pythonic' way of doing this.
You need to move cipherText = "" before the start of the for loop. You're resetting it each time through the loop.
def caesar(plainText, shift):
cipherText = ""
for ch in plainText:
if ch.isalpha():
stayInAlphabet = ord(ch) + shift
if stayInAlphabet > ord('z'):
stayInAlphabet -= 26
finalLetter = chr(stayInAlphabet)
cipherText += finalLetter
print "Your ciphertext is: ", cipherText
return cipherText
This is an improved version of the code in the answer of #amillerrhodes that works with different alphabets, not just lowercase:
def caesar(text, step, alphabets):
def shift(alphabet):
return alphabet[step:] + alphabet[:step]
shifted_alphabets = tuple(map(shift, alphabets))
joined_aphabets = ''.join(alphabets)
joined_shifted_alphabets = ''.join(shifted_alphabets)
table = str.maketrans(joined_aphabets, joined_shifted_alphabets)
return text.translate(table)
Example of usage:
>>> import string
>>> alphabets = (string.ascii_lowercase, string.ascii_uppercase, string.digits)
>>> caesar('Abc-xyZ.012:789?жñç', step=4, alphabets=alphabets)
'Efg-bcD.456:123?жñç'
References:
Docs on str.maketrans.
Docs on str.translate.
Docs on the string library
Using some ascii number tricks:
# See http://ascii.cl/
upper = {ascii:chr(ascii) for ascii in range(65,91)}
lower = {ascii:chr(ascii) for ascii in range(97,123)}
digit = {ascii:chr(ascii) for ascii in range(48,58)}
def ceasar(s, k):
for c in s:
o = ord(c)
# Do not change symbols and digits
if (o not in upper and o not in lower) or o in digit:
yield o
else:
# If it's in the upper case and
# that the rotation is within the uppercase
if o in upper and o + k % 26 in upper:
yield o + k % 26
# If it's in the lower case and
# that the rotation is within the lowercase
elif o in lower and o + k % 26 in lower:
yield o + k % 26
# Otherwise move back 26 spaces after rotation.
else: # alphabet.
yield o + k % 26 -26
x = (''.join(map(chr, ceasar(s, k))))
print (x)
Batteries included
while 1:
phrase = raw_input("Could you please give me a phrase to encrypt?\n")
if phrase == "" : break
print "Here it is your phrase, encrypted:"
print phrase.encode("rot_13")
print "Have a nice afternoon!"
https://docs.python.org/2/library/codecs.html#python-specific-encodings
Python 3 update
The fine docs say
[Now the rot_13] codec provides a text transform: a str to str mapping. It is not supported by str.encode() (which only produces bytes output).
Or, in other words, you have to import encode from the codecs module and use it with the string to be encoded as its first argument
from codecs import decode
...
print(encode(phrase, 'rot13'))
The problem is that you set cipherText to empty string at every cycle iteration, the line
cipherText = ""
must be moved before the loop.
As pointed by others, you were resetting the cipherText in the iteration of the for loop. Placing cipherText before the start of the for loop will solve your problem.
Additionally, there is an alternate approach to solving this problem using Python's Standard library. The Python Standard Library defines a function maketrans() and a method translate that operates on strings.
The function maketrans() creates translation tables that can be used with the translate method to change one set of characters to another more efficiently. (Quoted from The Python Standard Library by Example).
import string
def caesar(plaintext, shift):
shift %= 26 # Values greater than 26 will wrap around
alphabet_lower = string.ascii_lowercase
alphabet_upper = string.ascii_uppercase
shifted_alphabet_lower = alphabet_lower[shift:] + alphabet_lower[:shift]
shifted_alphabet_upper = alphabet_upper[shift:] + alphabet_upper[:shift]
alphabet = alphabet_lower + alphabet_upper
shifted_alphabet = shifted_alphabet_lower + shifted_alphabet_upper
table = string.maketrans(alphabet, shifted_alphabet)
return plaintext.translate(table)
Here, a more functional way:
(if you use shift i to encode, then use -i to decode)
def ceasar(story, shift):
return ''.join([ # concentrate list to string
(lambda c, is_upper: c.upper() if is_upper else c) # if original char is upper case than convert result to upper case too
(
("abcdefghijklmnopqrstuvwxyz"*2)[ord(char.lower()) - ord('a') + shift % 26], # rotate char, this is extra easy since Python accepts list indexs below 0
char.isupper()
)
if char.isalpha() else char # if not in alphabet then don't change it
for char in story
])
plainText = raw_input("What is your plaintext? ")
shift = int(raw_input("What is your shift? "))
def caesar(plainText, shift):
for ch in plainText:
if ch.isalpha():
stayInAlphabet = ord(ch) + shift
if stayInAlphabet > ord('z'):
stayInAlphabet -= 26
finalLetter = chr(stayInAlphabet)
#####HERE YOU RESET CIPHERTEXT IN EACH ITERATION#####
cipherText = ""
cipherText += finalLetter
print "Your ciphertext is: ", cipherText
return cipherText
caesar(plainText, shift)
As an else to if ch.isalpha() you can put finalLetter=ch.
You should remove the line: cipherText = ""
Cheers.
As #I82much said, you need to take cipherText = "" outside of your for loop. Place it at the beginning of the function. Also, your program has a bug which will cause it to generate encryption errors when you get capital letters as input. Try:
if ch.isalpha():
finalLetter = chr((ord(ch.lower()) - 97 + shift) % 26 + 97)
>>> def rotate(txt, key):
... def cipher(i, low=range(97,123), upper=range(65,91)):
... if i in low or i in upper:
... s = 65 if i in upper else 97
... i = (i - s + key) % 26 + s
... return chr(i)
... return ''.join([cipher(ord(s)) for s in txt])
# test
>>> rotate('abc', 2)
'cde'
>>> rotate('xyz', 2)
'zab'
>>> rotate('ab', 26)
'ab'
>>> rotate('Hello, World!', 7)
'Olssv, Dvysk!'
I have a hard time remember the char to int conversions so this could be optimized
def decryptCaesar(encrypted, shift):
minRange = ord('a')
decrypted = ""
for char in encrypted:
decrypted += chr(((ord(char) - minRange + shift) % 26) + minRange)
return decrypted
def encrypt():
plainText = input("What is your plaintext? ")
shift = int(input("What is your shift? "))
cipherText = ""
for ch in plainText:
if ch.isalpha():
stayInAlphabet = ord(ch) + shift
if stayInAlphabet > ord('z'):
stayInAlphabet -= 26
finalLetter = chr(stayInAlphabet)
cipherText += finalLetter
print ("Your ciphertext is: ", cipherText,"with a shift of",shift)
def decrypte():
encryption=input("enter in your encrypted code")
encryption_shift=int(input("enter in your encryption shift"))
cipherText1 = ""
for c in encryption:
if c.isalpha():
stayInAlphabet1 = ord(c) - encryption_shift
if stayInAlphabet1 > ord('z'):
stayInAlphabet1 += 26
finalLetter1 = chr(stayInAlphabet1)
cipherText1 += finalLetter1
print ("Your ciphertext is: ", cipherText1,"with negative shift of",encryption_shift)
from tkinter import *
menu=Tk()
menu.title("menu")
menu.geometry("300x300")
button1= Button(menu,text="encrypt",command=encrypt)
button1.pack()
button2= Button(menu,text="decrypt",command=decrypte)
button2.pack()
button3= Button(menu,text="exit",command=exit)
button3.pack()
menu.mainloop()
message = 'The quick brown fox jumped over the lazy dog. 1234567890 !##$%^&*()_+-'
encrypted = ''.join(chr(ord(char)+3) for char in message)
decrypted = ''.join(chr(ord(char)-3) for char in encrypted)
print(encrypted)
print(decrypted)
# Wkh#txlfn#eurzq#ir{#mxpshg#ryhu#wkh#od}|#grj1#456789:;<3#$C&'(a)-+,b.0
# The quick brown fox jumped over the lazy dog. 1234567890 !##$%^&*()_+-
def encrypt(text,shift):
'''
INPUT: text as a string and an integer for the shift value.
OUTPUT: The shifted text after being run through the Caeser cipher.
'''
# Create a placeholder list
encrypted_text = list(range(len(text)))
alphabet = string.ascii_lowercase
# Create shifted alphabet
first_half = alphabet[:shift]
second_half = alphabet[shift:]
shifted_alphabet = second_half+first_half
for i,letter in enumerate(text.lower()):
# Check for spaces or punctuation
if letter in alphabet:
# Find the original index position
original_index = alphabet.index(letter)
# Shifted letter
new_letter = shifted_alphabet[original_index]
encrypted_text[i] = new_letter
# Punctuation or space
else:
encrypted_text[i] = letter
return ''.join(encrypted_text)
For example, decod string:
"uo jxuhu! jxyi yi qd unqcfbu ev q squiqh syfxuh. muhu oek qrbu je tusetu yj? y xefu ie! iudt cu q cuiiqwu rqsa myjx jxu iqcu evviuj!".
This message has an offset of 10.
Code below:
import string
alphabet = list(string.ascii_lowercase)
print(alphabet, len(alphabet))
messege = "xuo jxuhu! jxyi yi qd unqcfbu ev q squiqh syfxuh. muhu oek qrbu je tusetu yj? y xefu ie! iudt cu q cuiiqwu rqsa myjx jxu iqcu evviuj!"
messege_split = messege.split()
print(messege_split)
encrypted_messege = ""
position = 0
for i in messege_split:
for j in i:
if ord(j) < 65:
encrypted_messege += j
else:
for k in alphabet:
if j == k:
position = alphabet.index(k)
if (position + 10) >= len(alphabet):
encrypted_messege += alphabet[abs((position + 10) - len(alphabet))]
else:
encrypted_messege += alphabet[position + 10]
encrypted_messege += " "
print(encrypted_messege)
Decoded string:
"hey there! this is an example of a caesar cipher. were you able to decode it? i hope so! send me a message back with the same offset!"
TRY IT!
Using cyclic generator:
import string
from itertools import cycle
def caesarCipherEncryptor(s, key):
def generate_letters():
yield from cycle(string.ascii_lowercase)
def find_next(v, g, c):
# Eat up characters until we arrive at the plaintext character
while True:
if v == next(g):
break
# Increment the plaintext character by the count using the generator
try:
for _ in range(c):
item = next(g)
return item
except UnboundLocalError:
return v
return "".join([find_next(i, generate_letters(), key) for i in s])
# Outputs
>>> caesarCipherEncryptor("xyz", 3)
>>> 'abc'
from string import ascii_lowercase as alphabet
class CaesarCypher:
alpha_len = len(alphabet)
min_guess_rate = 0.2
Encryption and decryption is a same stuff. when you want to decrypt for example with shift 10 that means that you can encrypt it with shift 26 - 10. In this case cycle will repeat at if you going to shift whole alphabet it will be the same. Also here i've proceed upper case and non chars
def __call__(self, text, offset, encrypt=True):
if not encrypt:
offset = self.alpha_len - offset
result = []
for letter in text:
if not letter.isalpha():
result.append(letter)
continue
letter_to_process = letter.lower()
processed_letter = self._encrypt_letter(letter_to_process, offset)
if letter.isupper():
processed_letter = processed_letter.upper()
result.append(processed_letter)
return ''.join(result)
all encryption goes here at most.
def _encrypt_letter(self, letter, offset=0):
position = (alphabet.find(letter) + offset) % self.alpha_len
return alphabet[position]
this part is for broot force and guess throug dictionary frequency.
#staticmethod
def __how_many_do_i_know(text):
clean_words = filter(lambda x: x.isalpha(), text.split())
clean_words = ['\'{}\''.format(x) for x in clean_words]
cursor = conn.cursor()
query = 'SELECT COUNT(*) FROM mydictionary WHERE word IN ({})'.format(",".join(clean_words))
cursor.execute(query)
response = cursor.fetchone()[0]
return response / len(clean_words)
def guess_encode(self, text):
options = [self(text, offset, encrypt=False) for offset in range(self.alpha_len)]
best_option = [self.__how_many_do_i_know(option) for option in options]
best_key, guess_rate = max(enumerate(best_option), key=lambda x: x[-1])
guess_text = options[best_key]
return best_key, guess_rate, guess_text
import string
wrd=raw_input("Enter word").lower()
fwrd=""
for let in wrd:
fwrd+=string.ascii_lowercase[(string.ascii_lowercase).index(let)+3]
print"Original word",wrd
print"New word",fwrd
according to me this answer is useful for you:
def casear(a,key):
str=""
if key>26:
key%=26
for i in range(0,len(a)):
if a[i].isalpha():
b=ord(a[i])
b+=key
#if b>90: #if upper case letter ppear in your string
# c=b-90 #if upper case letter ppear in your string
# str+=chr(64+c) #if upper case letter ppear in your string
if b>122:
c=b-122
str+=chr(96+c)
else:
str+=chr(b)
else:
str+=a[i]
print str
a=raw_input()
key=int(input())
casear(a,key)
This function shifts all letter to right according to given key.
Why not use the function reverse on the shift input, and and join the plain_text with the shift, and input it as the cipher text:
Plain = int(input("enter a number "))
Rev = plain[::-1]
Cipher = " ".join(for cipher_text in Rev)
The code is very large, but easy to understand. I think it fits your situation.
alphabet = "abcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyz"
class CaesarCipher(object):
def __init__(self, shift):
self.shift = shift
def encode(self, str):
encode = ''
str = str.lower()
for i in str:
if i in alphabet:
encode += alphabet[alphabet.index(i) + self.shift]
else:
encode += i
return encode.upper()
def decode(self, str):
decode = ''
str = str.lower()
for i in str:
if i in alphabet:
decode += alphabet[alphabet.index(i) - self.shift]
else:
decode += i
return decode.upper()
Using map:
def caesar(text, key):
return ''.join(map(lambda c:
chr((ord(c.lower()) - ord('a') + key) % 26 + ord('a')) if c.isalpha() else ''
, text))
This solution is more intuitively without the use of ord function:
def caesar_cipher(raw_text, key):
alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
shifted_alphabet = alphabet[26-key:]+alphabet[0:(26-key)]
cipher_text = ""
for i in range(len(raw_text)):
char = raw_text[i]
idx = alphabet.find(char.upper())
if idx == -1:
cipher_text = cipher_text + char
elif char.islower():
cipher_text = cipher_text + shifted_alphabet[idx].lower()
else:
cipher_text = cipher_text + shifted_alphabet[idx]
return(cipher_text)
And an example:
plain_text = "The quick brown fox jumps over the lazy dog!"
caesar_cipher(plain_text,3)
And we get:
'Qeb nrfzh yoltk clu grjmp lsbo qeb ixwv ald!'
If we want to decrypt it:
caesar_cipher(caesar_cipher(plain_text,3),26-3)
and we get:
'The quick brown fox jumps over the lazy dog!'
More details here:https://predictivehacks.com/caesar-cipher-in-python/
caesar-cipher
message = str(input("Enter you message:"))
shift = int(input("Enter a number:"))
# encode
stringValue = [ord(message) - 96 for message in message]
print(stringValue)
encode_msg_val = []
[encode_msg_val.append(int(stringValue[i])+shift) for i in
range(len(stringValue))]
encode_msg_array = []
for i in range(len(encode_msg_val)):
encode_val = encode_msg_val[i] + 96
encode_msg_array.append(chr(encode_val))
print(encode_msg_array)
encode_msg = ''.join(encode_msg_array)
# dedcode
[deocde_msg_val = [ord(encode_msg) - 96 for encode_msg in encode_msg]
decode_val = []
[decode_val.append(deocde_msg_val[i] - shift) for i in
range(len(deocde_msg_val))]
decode_msg_array = []
[decode_msg_array.append(decode_val[i] + 96) for i in range(len(decode_val))]
decode_msg_list = []
[decode_msg_list.append(chr(decode_msg_array[i])) for i in
range(len(decode_msg_array))]
decode_msg = ''.join(decode_msg_list)
print(decode_msg)
alph = 'abcdefghijklmnopqrstuvwxyz'
# shift = int(input("Please enter the number of places to shift:"))
shift = 15
text = "python is fun!"
alph_len = len(alph)
if shift >=0 and shift <= alph_len:
# text = input("Please enter a sentence:")
shifted_alph = alph[shift:] + alph[:shift] # rotate
text = text.lower()
crypted_text = ""
for letter in text:
if letter in alph:
ind = alph.index(letter)
crypted_letter = shifted_alph[ind]
else:
crypted_letter = letter
crypted_text += crypted_letter
print(crypted_text)
else:
print(f"You need to enter a number between 0 and {alph_len}!")
# eniwdc xh ujc! # output
key = 3
def wub():
def choice():
choice = input("Do you wish to Encrypt of Decrypt?")
choice = choice.lower()
if choice == "e" or "encrypt":
return choice
elif choice == "d" or "decrypt":
return choice
else:
print("Invalid response, please try again.")
choice()
def message():
user = input("Enter your message: ")
return user
def waffle(choice, message, key):
translated = ""
if choice == "e" or "encrypt":
for character in message:
num = ord(character)
num += key
translated += chr(num)
derek = open('Encrypted.txt', 'w')
derek.write(translated)
derek.close()
return translated
else:
for character in message:
num = ord(character)
num -= key
translated += chr(num)
return translated
choice = choice() #Runs function for encrypt/decrypt selection. Saves choice made.
message = message() #Run function for user to enter message. Saves message.
final = waffle(choice, message, key) #Runs function to translate message, using the choice, message and key variables)
print("\n Operation complete!")
print(final)
wub()

Categories

Resources