The following Caesar Cypher code is not working (Python 3). The text file is being written, but with incorrect cipher.
e.g. Input text as 'Hello' should be written as 'Uryyb!' with a key of 13. Instead it is being written as 'b'
# Caesar cypher function
def rot(text, key):
# Iterate through each character in the message.
for char in text:
# Set cypher_text to an empty string to add to later
cypher_text = ''
# Check if the character is a letter (A-Z/a-z).
if char.isalpha():
# Get the Unicode number from of the character.
num = ord(char)
# If the final number is greater than 'z'/122..
if (num + key) > 122:
# If we go too far, work out how many spaces passed
# 'a'/97 it should be using the proper key.
x = (num + key) - 122
# Add the chr version of x more characters passed
# 'a'/97, take 1 to account for the 'a' position.
# This adds a string character on to the cypher_text
# variable.
cypher_text += chr(x + ord('a') - 1)
# If the rotated value doesn't go passed 'z'/122
elif ((num + key <= 122)):
# Use the key to add to the decimal version of the
# character, add the chr version of the value to the
# cypher text.
cypher_text += chr(num + key)
# Else, if the chracter is not a letter, simply add it as is.
# This way we don't change symbols or spaces.
else:
cypher_text += char
# Return the final result of the processed characters for use.
return cypher_text
# Ask the user for their message
plain_input = input('Input the text you want to encode: ')
# Aks the user for the rotation key
rot_key = int(input('Input the key you want to use from 0 to 25: '))
# Secret message is the result of the rot function
secret_message = rot(plain_input, rot_key)
# Print out message for feedback
print('Writing the following cypher text to file:', secret_message)
# Write the message to file
with open('TestFile.txt', 'a+') as file:
file.write(secret_message)
Related
I am working on an assignment for an introductory Python class and the objective is to prompt the user for a password, determine it fits the given criteria, then encrypt the password by converting the characters to decimal, incrementing the letters and numbers, and decrementing the characters "!##$" then return the new encrypted password. EX. an input of "123ABCabc$" should output "234BCDbcd#" **EDIT -> fixed this output per #gimix
I have everything up to the step of incrementing/decrementing and this last step has me pulling my hair out. I have tried a gang of different things but the two closest to successful attempts I have are as follows.
-in the first sample new_input is the users original input
-in the second sample use_ascii is new_input converted to decimal
1)
def encrypt(new_input):
encrypted = ''
for char in new_input:
if chr(ord(char)) in list(range(97,123)): #ive tried different formatting options, thus the inconsistency
encrypted += chr(ord(char) + 1)
if chr(ord(char)) > str(64):
encrypted += chr(ord(char) + 1)
if chr(ord(char)) >= str(48):
encrypted += chr(ord(char) + 1)
if chr(ord(char)) == str(64):
encrypted += chr(ord(char) - 1)
if chr(ord(char)) >= str(32):
encrypted += chr(ord(char) - 1)
return encrypted
def encrypt(use_ascii):
encr = ''
list1 = list(range(97,123))
list2 = list(range(48,58))
list3 = list(range(56,91))
list4 = list(range(30,35))
for i in use_ascii:
if i in list1:
encr = i + 1
if i in list2:
encr = i + 1
if i in list3:
use_ascii = i + 1
if i in list4:
use_ascii = i - 1
return encr
then my main statements are (swapping 'use_ascii' for 'new_pass' when i test different options)...
new_input = input('Please input a password: \n')
new_encr = encrypt(use_ascii)
print('Your encrypted password is: {}'.format(encrypt(use_ascii)))
**EDIT per Jasmijn
Sample 1 outputs: just errors and I havn't been trying to fix it as much as I suspect that is the less-correct way to proceed
Sample 2 outputs: Your encrypted password is: 100
This is dec for the letter 'd' which suggests it is selecting the last character which fits the criteria of the first 'if' statement and incrementing it. I need it to increment each character and output the new decimal based on the ranges provided.
The easiest way is to use the isalnum() string method to distinguish between letters/numbers an special characters. So you could simply do:
def encrypt(instring):
outstring = ''
for ch in instring:
outstring += chr(ord(ch)+1) if ch.isalnum() else chr(ord(ch)-1)
return outstring
Or, if you want a one-liner:
def encrypt(instring):
return ''.join((chr(ord(ch)+1) if ch.isalnum() else chr(ord(ch)-1) for ch in instring))
Hey so i'm trying to encrypt a string, with a shift key. It works perfectly, the only issue i have is with shifting the characters. For example hello, world!0 and the shift will be 5. I want it to return as olssv, dvysk!0 Basically, only the alphabets will get encrypted. The puncutations & numbers, etc won't be shifted.
keymax = 26
def text():
print('What message(s) are you trying to encrypt?')
return input()
def shift():
key = 0;
while True:
print('Enter the key number (1-%s)' % (keymax))
key = int(input())
if (key >= 1 and key <= keymax):
return key
def encrypt(string, shift):
hidden = ''
for char in string:
if char == ' ':
hidden = hidden + char
elif char.isupper():
hidden = hidden + chr((ord(char) + shift - 65) % 26 + 65)
else:
hidden = hidden + chr((ord(char) + shift - 97) % 26 + 97)
return hidden
text = text()
s = shift()
print("original string: ", text)
print("after encryption: ", encrypt(text, s))
I am fairly new to python, sorry for my bad understandings. Any help would gladly be appreciated!
You could replace the first if statement in your encrypt function with if char.isalpha() == False:. So when the character is not an alphabetical character, the charcter doesn't get changed.
Edit: Also to suggest an improvement, if you want to you can even have shifts upwards of 26. If you use key = key % 26 (%, called modulo, is the remainder of the division, in this case key divided by 26).
This allows you to have keys that are more than 26. This doesn't really change much at all, I just personally like it more
Create a function called decrypt that takes two parameters, one tuple parameter called key and one string parameter called cipher_text.
The function shall take text in 'cipher text' i.e. coded text and the values of the key in order to shift the text in the appropriate direction.
The function shall return the cipher text as plain text. (Use the islower() or isupper() function to see if the character is lower or uppercase. Case matters in returning ‘cipher text’).
Def decrypt(key, cipher_text):
for i in cipher_text:
For index in key:
Text = i + index
text.lower()
return text
def decrypt(key, cipher_text):
text = str(cipher_text)
import string
charup = string.ascii_uppercase
chardown = string.ascii_lowecase
newstring = ""
counter = 0
for x in text:
if counter <= len(text) - 1:
pass
else:
counter = 0
if x.islower():
newchar = chardown[(chardown.index(x) + key[counter]) % 25]
elif x.isupper():
newchar = charup[(charup.index(x) + key[counter]) % 25]
newstring = newstring + newchar
counter = counter + 1
While using the following code you need to keep in mind all of the following:
I have assumed that the string does not contain any special character or digit, in which case the islower() and isupper() won't work.
This code will work on at least Python 3.3 and Python 3.4
I do not know which appropriate direction you are talking about.
If you meant going backwards then you only need to change
newchar = chardown[(chardown.index(x) + key[counter]) % 25]
newchar = charup[(charup.index(x) + key[counter]) % 25]
to-
newchar = chardown[(chardown.index(x) - key[counter]) % 25]
newchar = charup[(charup.index(x) + key[counter]) % 25]
I am attempting to create the vigenere cipher in python and there seems to be a problem. Here is my encryption code:
def encryption():
plaintext=input("Please enter the message you wish to encode.")
#This allows the user to enter the message they wish to encrypt.
keyword=input("Please enter your keyword, preferably shorter than the plaintext.")
#This allows the user to enter a keyword.
encoded=""
#This creates a string for the user to input the encrypted message to.
while len(keyword)<len(plaintext):
#This begins a while loop based on the fact that the length of the keyword is shorter than the length of the plaintext.
keyword+=keyword
#This repeats the keyword.
if len(keyword)>len(plaintext):
#This sees if the string length of the keyword is now longer than the string length of the plaintext.
newkey=keyword[:len(plaintext)]
#This cuts the string length of the keyword
for c in range(len(plaintext)):
char=ord(plaintext[c])
temp=ord(keyword[c])
newchar=char+temp
if newchar>ord("Z"):
newchar-=26
newnewchar=chr(newchar)
encoded+=newnewchar
print(encoded)
I cannot seem to find the problem with it, however when I enter the plaintext "hello" and the keyword "hi" it come up with the following symbols: ¶´º»½. I think the addition in the for loop may be going too far.
You need to understand the ord() function, chr() is the inverse of ord()
for i in range(300):
print(str(i) + ' ' + chr(i))
If you don't use Unicode characters, you can use an alphabet string
alphabet = 'abcdefghijklmnopqrstuvwxyz'
for p,k in zip(plaintext,keyword): # you can directly iterate strings
char = alphabet.index(p)
temp = alphabet.index(k)
newchar = char + temp
if newchar > 25:
newchar -= 25
newchar = alphabet[newchar]
I won't just solve the bug for you as there are many other things to improve here !
Put space around operators: a=b should be a = b, same with +, -, etc.
I find it better to use function params than input. You can always have a second function to get input and encrypt the input:
def encryption(plaintext, keyword):
pass # (do nothing)
I'll let you write the auxiliary function.
I, and most, usually put comments on the line above the corresponding code. Also, no need to write This every time, and imperative is generally preferred.
Now let's have a look at your while loop. The condition is len(keyword) < len(plaintext), inside you check len(keyword) > len(plaintext). When can that happen ? Only during the last iteration. So move the code out of the loop.
Also, what you do inside the if doesn't need an if:
any_string[:len(any_string) + n] == any_string (n being a positive int).
Plus you never use newkey!
So we can simplify the loop to:
# Begin a while loop based on the fact that the length of the keyword is
# shorter than the length of the plaintext.
while len(keyword) < len(plaintext):
# Repeat the keyword.
keyword += keyword
# Cut the string length of the keyword
keyword = keyword[:len(plaintext)]
Which is equivalent to:
# Do the operation once
txt_len = len(plaintext)
# Get a string just a bit longer than plaintext
# Otherwise we would have issues when plaintext is not a multiple
# of keyword
keyword *= txt_len // len(keyword) + 1
# Chop of the extra part
keyword = keyword[:txt_len]
Note that both will fail when len(keyword) == 0.
Now to the for loop:
You could use zip, as polku showed you, but I'll assume it's too complicated for now and keep the range.
You could also use the alphabet, but plain arithmetic can do the trick:
alphabet.index(x) == ord(x) - ord('a'), so in your code:
char = ord(plaintext[c]) - ord('a')
temp = ord(keyword[c]) - ord('a')
newchar = char + temp
# Or simply:
newchar = ord(plaintext[c]) + ord(keyword[c]) - 194 # 2 * ord('a')
If we ignore capital letters, we can safely substitute
if newchar > 25:
newchar -= 25
# With
newchar %= 25
Finally:
alphabet[i] == ord(i + ord('a')).
Here's all this put together:
def encryption(plaintext, keyword):
# Do the operation once
txt_len = len(plaintext)
# Get a string just a bit longer than plaintext
# Otherwise we would have issues when plaintext is not a multiple
# of keyword
keyword *= txt_len // len(keyword) + 1 # // is floor division
# Chop of the extra characters (if there are any)
keyword = keyword[:txt_len]
# Create a string to store the encrypted message
encoded = ""
# Now you should change this to work with capital letters
for c in range(txt_len):
# 194 = 2 * ord('a')
newchar = ord(plaintext[c]) + ord(keyword[c]) - 194
newchar %= 25
encoded += chr(newchar + 97) # 97 = ord('a')
return encoded
def encrypt_input():
# This function should use input to get plaintext and keyword
# Then use encryption with those strings and print the result
pass
Indeed the addition goes too far, because ord uses ASCII (where A is 65), while de Vigenère had A in the first position. You could subtract ord('A'). The code also assumes all characters are capital letters. Here's a variation that uses a few of Python's library functions to perform the task.
import string, itertools
def encrypt(text, key='N'): # default to rot13 (:
'''Performs a Vigenere cipher of given plaintext and key'''
result=[]
key=key.upper()
for plain,shift in itertools.izip(text,itertools.cycle(key)):
shiftindex=string.ascii_uppercase.index(shift)
shiftto=(string.ascii_uppercase[shiftindex:] +
string.ascii_uppercase[:shiftindex])
trans=string.maketrans(string.ascii_letters,
shiftto.lower()+shiftto)
result.append(plain.translate(trans))
return ''.join(result)
A more complete variant might only consume key for letters, but this will be fine if your strings only contain letters. The reason I stuck to the ASCII letters is because locale specific alphabets might not have the intended ordering nor a matching set of upper and lower case (for instance, german ß). It's also entirely possible to translate the key into a list of translation tables only once.
After much frustration, I have made my first Caesar Decoder :)
But the problem now is to make the program circular...
For example if we want to shift doge by 1, no problem, it's ephf...
But what about xyz, and the shift was 4???
So programming pros help a first time novice aka newb out :P
Thanks...
import string
def main():
inString = raw_input("Please enter the word to be "
"translated: ")
key = int(raw_input("What is the key value? "))
toConv = [ord(i) for i in inString] #now want to shift it by key
toConv = [x+key for x in toConv]
#^can use map(lambda x:x+key, toConv)
result = ''.join(chr(i) for i in toConv)
print "This is the final result due to the shift", result
Here is Python code that I wrote to be easy to understand. Also, I think the classic Caesar cipher didn't define what to do with punctuation; I think the classic secret messages were unpunctuated and only contained letters. I wrote this to only handle the classic Roman alphabet and pass any other characters unchanged.
As a bonus, you can use this code with a shift of 13 to decode ROT13-encoded jokes.
def caesar_ch(ch, shift):
"""
Caesar cipher for one character. Only shifts 'a' through 'z'
and 'A' through 'Z'; leaves other chars unchanged.
"""
n = ord(ch)
if ord('a') <= n <= ord('z'):
n = n - ord('a')
n = (n + shift) % 26
n = n + ord('a')
return chr(n)
elif ord('A') <= n <= ord('Z'):
n = n - ord('A')
n = (n + shift) % 26
n = n + ord('A')
return chr(n)
else:
return ch
def caesar(s, shift):
"""
Caesar cipher for a string. Only shifts 'a' through 'z'
and 'A' through 'Z'; leaves other chars unchanged.
"""
return ''.join(caesar_ch(ch, shift) for ch in s)
if __name__ == "__main__":
assert caesar("doge", 1) == "ephf"
assert caesar("xyz", 4) == "bcd"
assert caesar("Veni, vidi, vici.", 13) == "Irav, ivqv, ivpv."
The part at the end is a "self-test" for the code. If you run this as a stand-alone program, it will test itself, and "assert" if a test fails.
If you have any questions about this code, just ask and I'll explain.
Just add the key to all the actual character codes, then if the added value is greater than z, modulo with character code of z and add it with the character code of a.
inString, key = "xyz", 4
toConv = [(ord(i) + key) for i in inString] #now want to shift it by key
toConv = [(x % ord("z")) + ord("a") if x > ord("z") else x for x in toConv]
result = ''.join(chr(i) for i in toConv)
print result # cde
I'd recommend using string.translate().
So, we can do the following:
key = 1
table = string.maketrans(string.ascii_lowercase + string.ascii_uppercase, string.ascii_lowercase[key:] + string.ascii_lowercase[:key] + string.ascii_uppercase[key:] + string.ascii_uppercase[:key])
And then we can use it as follows:
'doge'.translate(table) # Outputs 'ephf'
'Doge'.translate(table) # Outputs 'Ephf'
'xyz'.translate(table) # Outputs 'yza'
In particular, this doesn't change characters that are not ascii lowercase or uppercase characters, like numbers or spaces.
'3 2 1 a'.translate(table) # Outputs '3 2 1 b'
in general, to make something "wrap" you use the modulo function (% in Python) with the number you want to wrap, and the range you want it to wrap in. For example, if I wanted to print the numbers 1 through 10 a bajillion times, I would do:
i = 0
while 1:
print(i%10+1)
# I want to see 1-10, and i=10 will give me 0 (10%10==0), so i%10+1!
i += 1
In this case it's a little more difficult because you're using ord, which doesn't have a nice happy "range" of values. If you had done something like string.ascii_lowercase you could do...
import string
codex = string.ascii_lowercase
inString = "abcdxyz"
key = 3
outString = [codex[(codex.index(char)+key)%len(codex)] for char in inString]
However since you're using ord, we're kind of going from ord('A') == 65 to ord('z')==122, so a range of 0 -> 57 (e.g. range(58), with a constant of 65. In other words:
codex = "ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz"
# every char for chr(65) -> chr(122)
codex = ''.join([chr(i+65) for i in range(58)]) # this is the same thing!
we can do this instead, but it WILL include the characters [\]^_`
inString, key = 'abcxyzABCXYZ', 4
toConv = [(ord(i)+key-65)%58 for i in inString]
result = ''.join(chr(i+65) for i in toConv)
print(result)
# "efgBCDEFG\\]^"
I know this is kind of an old topic, but I just happened to be working on it today. I found the answers in this thread useful, but they all seemed to use a decision to loop. I figured a way to accomplish the same goal just using the modulus(remainder) operator (%). This allows the number to stay within the range of a table and loop around. It also allows for easy decoding.
# advCeaser.py
# This program uses a ceaser cypher to encode and decode messages
import string
def main():
# Create a table to reference all upper, lower case, numbers and common punctuation.
table = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ abcdefghijklmnopqrstuvwxyz1234567890,.!?-#'
print 'This program accepts a message and a key to encode the message.'
print 'If the encoded message is entered with the negative value of the key'
print 'The message will be decoded!'
# Create accumulator to collect coded message
code =''
# Get input from user: Message and encode key
message = raw_input('Enter the message you would like to have encoded:')
key = input('Enter the encode or decode key: ')
# Loop through each character in the message
for ch in message:
# Find the index of the char in the table add the key value
# Then use the remainder function to stay within range of the table.
index = ((table.find(ch)+key)%len(table))
# Add a new character to the code using the index
code = code + table[index]
# Print out the final code
print code
main()
The encode and decode output look like this.
encode:
This program accepts a message and a key to encode the message.
If the encoded message is entered with the negative value of the key
The message will be decoded!
Enter the message you would like to have encoded:The zephyr blows from the east to the west!
Enter the encode or decode key: 10
croj0ozr92jlvy73jp2ywj4rojok34j4yj4roj7o34G
decode:
This program accepts a message and a key to encode the message.
If the encoded message is entered with the negative value of the key
The message will be decoded!
Enter the message you would like to have encoded:croj0ozr92jlvy73jp2ywj4rojok34j4yj4roj7o34G
Enter the encode or decode key: -10
The zephyr blows from the east to the west!
Sorry if my formatting looks catywompus I literally found stackoverflow yesterday! Yes, I literally mean literally :)