Caesar Cipher Code Python printing on separate lines - python

The code below works fine, however the message prints onto separate lines once it has been encrypted. For example if I type: abc with the shift of 1 it encrypts it but prints it back as:
b
c
d
And I don't understand why. I want it to print as:
bcd
Here is the code:
print("Welcome to the Code-Breaking/Making Software")
print("This program uses something called a Caesar Cipher.")
Message = (input("Please enter the message you wish to Encrypt >> "))
Shift = int(input("Please enter the shift for your message >> "))
for x in Message:
OrdMessage = ord(x)
ShiftedMessage = OrdMessage + Shift
NewMessage = chr(ShiftedMessage)
NewMessageList = list(NewMessage)
print("".join(NewMessageList))

Indentation matters and you shouldn't create new list of NewMessage everytime
print("Welcome to the Code-Breaking/Making Software")
print("This program uses something called a Caesar Cipher.")
Message = (input("Please enter the message you wish to Encrypt >> "))
Shift = int(input("Please enter the shift for your message >> "))
NewMessageList = []
for x in Message:
OrdMessage = ord(x)
ShiftedMessage = OrdMessage + Shift
NewMessage = chr(ShiftedMessage)
NewMessageList.append(NewMessage)
print("".join(NewMessageList))

you should change the following part;
print("".join(NewMessageList), end="")

What happening was is that for each charachter it was running the loop and printing the answer, now I have collected all the encrypted letter and clubbed them as one in the end and printed it.
it at first initialize an empty list with NewMessage = [] and then for every letter that we get encrypted it adds to that empty list using .append() and at end print all by ''.join(NewMessage)
print("Welcome to the Code-Breaking/Making Software")
print("This program uses something called a Caesar Cipher.")
Message = (input("Please enter the message you wish to Encrypt >> "))
Shift = int(input("Please enter the shift for your message >> "))
NewMessage = []
for x in Message:
OrdMessage = ord(x)
ShiftedMessage = OrdMessage + Shift
NewMessage.append(chr(ShiftedMessage))
print(''.join(NewMessage))

Related

How do I make this code not encrypt messages if it finds a special character or number inputted?

I'm not sure how to make this code print a message if it finds the user types a special character and/or number and exits the code instead of just printing out the special character and/or number again.
I'm quite new to here, any help would be appreciated. My code is below:
#!/bin/python3
alphabet = 'abcdefghijklmnopqrstuvwxyz'
special = '[#_!#$%^&*()<>?/\|}{~:]1234567890'
newMessage = ''
message = input('Please enter a message to encyrpt: ').lower()
key = input('Please enter a key from 1-26: ')
key = int(key)
for character in message:
if character in alphabet:
position = alphabet.find(character)
newPosition = (position + key) % 26
newCharacter = alphabet[newPosition]
#print('The new character is is:', newCharacter)
newMessage += newCharacter
else:
newMessage += character
print('Your new encrypted message is:', newMessage)
The below example:
Checks each character of the string message given by the user at runtime and passes it into a list specialInMessage = [c for c in special if c in message]
Checks the list (if specialInMessage:), printing a message to the console and exiting the execution of any further code using the builtin sys module (sys.exit()) if there are any characters that made it through the above list comprehension into specialInMessage
If the above conditional (if specialInMessage) does not pass - i.e. there are no values from special present in message - the code will not execute the block exiting the program and continue to ask for a key value, encrypt message etc.
import sys # Import builtin sys module
alphabet = 'abcdefghijklmnopqrstuvwxyz'
special = '[#_!#$%^&*()<>?/\|}{~:]1234567890'
newMessage = ''
message = input('Please enter a message to encyrpt: ').lower()
specialInMessage = [c for c in special if c in message] # Make a list of characters from special that are present in message
if specialInMessage: # If new list has any characters in it
print('Invalid character found in message, exiting program') # Message to console
sys.exit() # End execution of code
key = input('Please enter a key from 1-26: ')
key = int(key)
for character in message:
if character in alphabet:
position = alphabet.find(character)
newPosition = (position + key) % 26
newCharacter = alphabet[newPosition]
newMessage += newCharacter
else:
newMessage += character
print(f'Your new encrypted message is: {newMessage}')
If you want to tell the user specifically which character(s) from their input are invalid these can be accessed directly from the specialInMessage list - probably best from within the if specialInMessage block to ensure that list index access is only attempted when there are actually invalid characters at runtime.
you can simply use break
alphabet = 'abcdefghijklmnopqrstuvwxyz'
special = '[#_!#$%^&*()<>?/\|}{~:]1234567890'
newMessage = ''
message = input('Please enter a message to encyrpt: ').lower()
key = input('Please enter a key from 1-26: ')
key = int(key)
for character in message:
if character in alphabet:
position = alphabet.find(character)
newPosition = (position + key) % 26
newCharacter = alphabet[newPosition]
#print('The new character is is:', newCharacter)
newMessage += newCharacter
elif character in special:
newMessage = 'encrypting Error'
break
else:
newMessage += character
print('Your new encrypted message is:', newMessage)

Why am I getting a type error in my code?

I am trying to write a vigenere cipher code. My psuedo for this is :
- find the index for each letter in plaintext
- find the index for each letter in the key message
- add together the indexes
- new letters will be at the position of the sum of the indexes
I believe I got my code correctly organized but I'm not sure if I'm missing something because I'm getting a type error.
# global constants:
ALPHABET = "abcdefghijklmnopqrstuvwxyz"
ALPHABET_SIZE = len(ALPHABET)
# main function definition:
def main():
# User interface:
print("Welcome to the Vigenere Cipher!")
keep_running = True
while(keep_running):
print("Enter 1 to encrypt a message")
print("Enter 2 to decrypt a message")
print("Enter 0 to exit")
print()
user_choice = int(input("What would you like to do? " ))
if user_choice == 0:
keep_running = False
if user_choice == 1:
plaintext = input("Enter a plaintext message to encrypt: ")
key = str(input("Enter a message to use as the key: "))
ciphertext = enc(key, plaintext)
print("Resulting cipertext:", ciphertext)
print()
if user_choice == 2:
ciphertext = str(input("Enter a ciphertext message to decrypt: "))
key = str(input("Enter a message to use as the key: "))
plaintext = dec(key, ciphertext)
print("Resulting plaintext:", plaintext)
print()
def enc(key, plaintext):
ciphertext = []
for cipher_char in plaintext:
char_pos = ALPHABET.index(cipher_char)
for key_char in key:
message_pos = ALPHABET.index(key_char)
new_pos = (char_pos + key_char)
enc_char = ALPHABET(new_pos)
plaintext += enc_char
return plaintext
# call to main:
main()
The error is at this line
new_pos = (char_pos + key_char)
char_pos is a position and is of type int. key_char is a character and is of type string. You can't add one to the other.
Also in these lines directly above:
for cipher_char in plaintext:
char_pos = ALPHABET.index(cipher_char)
for key_char in key:
message_pos = ALPHABET.index(key_char)
Each of the for loops set the variables (char_pos and message_pos respectively) over and over again. So only the positions of the last character in each string (plaintext and key respectively) in the alphabet are taken into account. So you need to rethink the logic somewhat.
Finally I suggest you include upper case characters in ALPHABET. I got a value error the first time I tried it because I tried upper case input.

How to remove characters from a specific place in a string(not by index) in Python

So I have this code:
def myprogram():
import string
import random
import getpass
inputpasswd = getpass.getpass("Password: ")
passwd = ("I<3StackOverflow")
if passwd == inputpasswd:
qwerty = input("Type something: ")
def add_str(lst):
_letters = ("1","2","3","4","5","6","7","8","9","0","q","w","e","r","t","z","u","i","o","p","a","s","d","f","g","h","j","k","l","y","x","c","v","b","n","m","!","#","$","%","&","/","(",")","=","?","*","+","_","-",";"," ")
return [''.join(random.sample(set(_letters), 1)) + letter + ''.join(random.sample(set(_letters), 1))for letter in lst]
print(''.join(add_str(qwerty)))
input("")
else:
print("Wrong password")
input("")
My question is: How can I make an opposite program, so it accepts the bunch of junk letters and converts it to text that makes sense?
Example:
If I type something like "aaaaaaa" in this program it will convert it to something like "mapma&)at7ar8a2ga-ka*"
In this new program I want to type "mapma&)at7ar8a2ga-ka*" and get output "aaaaaaa".
Does this work for you?:
s="1a23a45a6"
print(s[1::3]) # aaa
Do so: initial_str = random_str[1:-1:3], where random_str is string with junk

how to write an encryption program in python

I am needing a bit of help on my encryption program. Instead of having the program just move the letters by two (c would become a or r would become p) I'd like to be able to have it reference 2 lists, the first one going from a-z normally and the other with letters in different order to act as the encrypt/decrypt side. Hopefully that makes sense. Here's what i have so far.
result = ''
choice = ''
message = ''
while choice != 0:
choice = input("\n Do you want to encrypt or decrypt the message?\n 1 to encrypt, 2 to decrypt or 0 to exit program. ")
if choice == '1':
message = input('\nEnter message for encryption: ')
for i in range(0, len(message)):
result = result + chr(ord(message[i]) - 2)
print(result + '\n\n')
result = ''
if choice == '2':
message = input('\nEnter message to decrypt: ')
for i in range(0, len(message)):
result = result + chr(ord(message[i]) + 2)
print(result + '\n\n')
result = ''
elif choice != '0':
print('You have entered an invalid input, please try again. \n\n')
This works fine and dandy but i'd like to have the lists. Lets say list 1 is A,B,C,D,E and list 2 would be W,N,U,D,P. just for ease of use purposes.
Here is a solution, for small letters only. It can easily be modified to handle also capital letters, by adding them to the text strings.
As can be seen, the space character is at the same position in both lists. This is not necessary, as any character can be translated to any other. However if the decrypted or encrypted is not containing unique characters only, the program will break down.
decrypted = b"abcdefghijklmnopqrstuvwxyz "
encrypted = b"qwertyuiopasdfghjklzxcvbnm "
encrypt_table = bytes.maketrans(decrypted, encrypted)
decrypt_table = bytes.maketrans(encrypted, decrypted)
result = ''
choice = ''
message = ''
while choice != '0':
choice = input("\n Do you want to encrypt or decrypt the message?\n 1 to encrypt, 2 to decrypt or 0 to exit program. ")
if choice == '1':
message = input('\nEnter message for encryption: ')
result = message.translate(encrypt_table)
print(result + '\n\n')
elif choice == '2':
message = input('\nEnter message to decrypt: ')
result = message.translate(decrypt_table)
print(result + '\n\n')
elif choice != '0':
print('You have entered an invalid input, please try again. \n\n')
Ok, so a few things here...
First I'll give you exactly what you were looking for and explain what I used and some of the changes that needed to be made to your original code. Then I'll explain some inherent issues what what you're trying to do and suggest some areas to read up on/some ways you might want to improve what you've got.
Here's the code you're looking for (while retaining the same flow as what you submitted put above):
import random
result = ''
choice = ''
message = ''
characters_in_order = [chr(x) for x in range(32,127)]
while choice != 0:
choice = input("\n Do you want to encrypt or decrypt the message?\n 1 to encrypt, 2 to decrypt or 0 to exit program. ")
if str(choice) == '1':
message = input('\nEnter message for encryption: ')
r_seed = input('Enter an integer to use as a seed: ')
random.seed(r_seed)
shuffled_list = [chr(x) for x in range(32,127)]
random.shuffle(shuffled_list)
for i in range(0, len(message)):
result += shuffled_list[characters_in_order.index(message[i])]
print(result + '\n\n')
result = ''
elif str(choice) == '2':
message = input('\nEnter message to decrypt: ')
r_seed = input('Enter an integer to use as a seed (should be the same one used to encrypt): ')
random.seed(r_seed)
shuffled_list = [chr(x) for x in range(32,127)]
random.shuffle(shuffled_list)
for i in range(0, len(message)):
result += characters_in_order[shuffled_list.index(message[i])]
print(result + '\n\n')
result = ''
elif str(choice) != '0':
print('You have entered an invalid input, please try again. \n\n')
You'll notice that I set a global 'characters in order' list, which is just every ASCII character (32-126) in order. I also imported the 'random' module and used this to shuffle the characters in order according to a seed that the user inputs. As long as this seed is the same on the encryption and decryption end, it will produce the same shuffled list and it should work to encrypt or decipher the same string. Also notice the str() around your input choices. Without that, the user had to input '1', rather than 1 to submit a choice without an error.
All of that said...
Notice that the way the new function works is by looking at a character's index in one list and pulling out the character at that index in another. The method you were using, of incrementing or decrementing a character's ASCII code is basic (though not much more basic than this), but it also has a pretty critical flaw, which is that characters on one end or another of the ASCII set wouldn't return ASCII characters. If you were encrypting it at a bit-level, which would be preferred, this wouldn't matter/would be irrelevant, but here you're not going to get the kind of string back that you want if you were to, for example, enter a [space] (ASCII 32) into your plaintext to be encrypted.
If you're interested, you might want to read up on symmetric key encryption/DES for some ideas on how encryption is really done, though props on the start/interest and this can certainly be a fun way to create some sort of cryptogram puzzle or something along those lines. I won't pretend to be any kind of expert, but I can at least point you in the write direction. (https://en.wikipedia.org/wiki/Data_Encryption_Standard https://en.wikipedia.org/wiki/Symmetric-key_algorithm)
Consider having your code read in a .txt file and print out to a .txt file, rather than using user input for the message.
Again, I'm not an expert by any means and there are definitely some fun uses of the kind of program you're aiming for, just trying to point you in the right direction if this is something that you're interested in. Hope all of that is helpful!
Here is my solution. It uses a randomizer to encrypt the file by assigning a ASCII value to the plain text and randomly shifts it around.
from random import randint
import sys
def menu():
input1=int(input(""" please select what you want to do:
1.Encrypt
2.Decrypt
3.Extended Encryption
4.exit
"""))#menu to choose what you want to do
if input1==1:
encrypt() #takes you to the encrypt function
elif input1==2:
decrypt()#takes you to the decrypt function
elif input1==3:
enxtended()#takes you to the extended encryption function
elif input1==4:
sys.exit #exits the program
else:
print("invalid entry try again")
menu()
def encrypt():
file_name=str(input("please enter the name of the file that you want to open\n"))
try:
text_file=open(file_name + ".txt","r")#puts the text file into read
text_file=text_file.read()#reads the text file
print(text_file)#prints the strings in the document
except:
print("error try again")
encrypt()
random(text_file)
def random(text_file):
list1=("")#creates blank string
for x in range (0,8):
num=(randint(33,126))#generates a random number between33 and 126
ascii1=chr(num) #converts it into an ascii character
list1=list1+ascii1#adds the ascii character to the blank string list1
print (f"your 8 key code is {list1}") #prints 8 character code
offset(list1,text_file)
def offset(list1,text_file):
total=0
for x in range (8,):
total=total+ord(list1[x]) #turns each character into an ascii value
total=total/8 #divides it by
total=round(total,0)#rounds it to 0 decimel places
print(total)
total=total-32#minuses 32 from total
print(f"your offset factor is {total}")
encrypting(total,text_file)
def encrypting(total,text_file):
length=len(text_file)
string1=("")
for x in range (length,):
numascii=ord(text_file[x])#turns the characters into its ascii value
numascii=int(numascii)#makes sure they are integers
if numascii==32:
letter=chr(32)#converts spaces back into spaces
string1=string1+letter#adds space to thestring
else:
numascii1=numascii+total#adds the character value to the offset factor
numascii1=int(numascii1)#makes sure it is an integer
if numascii1>126:# if the ascii value is great then 126
numascii1=numascii1-94#minus 94 from it
letter=chr(numascii1)#turn it into a character
string1=string1+letter#add it to the string
else:
letter=chr(numascii1)#turn the ascii value into a character
string1=string1+letter#add it to the string
print(f"your encrypted file is {string1}")
savefile(string1)
menu()
I have written separate programs for encryption and decryption. Both of these use file manipulation techniques. Use the username 'eggs' and password 'chicks' so that not anyone can see my secret code. I have used hashlib for more security. Just change the User 'Soumajit' to your respective Username to make it work. The first one is encryption and the next one is for decryption.
#ENCRYPTION
from time import sleep
import subprocess
import hashlib
def copy2clip(txt):
cmd='echo '+txt.strip()+'|clip'
return subprocess.check_call(cmd, shell=True)
def en():
alphabet = "abcdefghijklmnopqsrtuwvxyzABCDEFGHIJKLMNOPQSRTUVWXYZ,./?:;!##$%_&* ()`-+=1234567890"
encrypt = ""
decrypt = ""
print
print "Type y for yes and anything else for no"
start = raw_input("Do you want to import file from desktop? ")
if start == "y":
Open = raw_input("Enter the .txt file you want to open in desktop: ")
a = open("C://Users//Soumajit//Desktop//" + Open + ".txt", "r")
print
x = (a.read())
copy2clip(x)
a.close()
print "Right click and select paste below to encrypt"
print
message = raw_input()
for i in message:
x = alphabet.find(i)
new = (x - 5) % 74
encrypt += alphabet[new]
e2 = encrypt[::-1]
else:
print "Type your message below"
message = raw_input("")
for i in message:
x = alphabet.find(i)
new = (x - 5) % 74
encrypt += alphabet[new]
e2 = encrypt[::-1]
print
a = raw_input("By what name do you want to save it?: ")
file = open(a + ".txt", 'wb')
file.write(e2)
file.close()
copy = raw_input("Do you want to copy your file? ")
if copy == 'y':
copy2clip(e2)
print 'Your encrypted file has been copied to the clipboard'
else:
print "Your encrypted file has been saved with the name " + str(a) + " in desktop"
print "To decrypt it, use my other program"
sleep(3)
u = 'e415bf03b4d860dccba57cea46371f831d772ba1deca47f28fa7d1f7'
p = 'c35f7f79dc34a678beb2b4106c84c9963561e7c64bc170e50c429b9a'
ur = raw_input('Enter your username: ')
ur1 = hashlib.sha224(ur).hexdigest()
pr = raw_input('Enter your password: ')
pr1 = hashlib.sha224(pr).hexdigest()
if ur1 == u and pr1 == p:
print 'Access granted'
sleep(1)
en()
else:
print "Incorrect username or password"
sleep(1)
#DECRYPTION
from time import sleep
import subprocess
import hashlib
def copy2clip(txt):
cmd='echo '+txt.strip()+'|clip'
return subprocess.check_call(cmd, shell=True)
def de():
print "Type y for yes and anything else for no"
start = raw_input("Do you want to import file from desktop? ")
if start == "y":
Open = raw_input("Enter the .txt file you want to open from folder: ")
a = open("C://Users//Soumajit//Desktop//" + Open + ".txt", "r")
x = (a.read())
#print x
copy2clip(x)
print "Right click and select paste below to decrypt"
print
message = raw_input()
a.close()
alphabet = "abcdefghijklmnopqsrtuwvxyzABCDEFGHIJKLMNOPQSRTUVWXYZ,./?:;!##$%_&*()`-+=1234567890"
decrypt = ''
for i in message:
x = alphabet.find(i)
new = (x + 5) % 74
decrypt += alphabet[new]
d2 = decrypt[::-1]
d3 = d2.replace("`", " ")
final = d3.replace("2", " ")
print
print final
else:
print "Type or paste your encrypted text below"
print
message = raw_input()
alphabet = "abcdefghijklmnopqsrtuwvxyzABCDEFGHIJKLMNOPQSRTUVWXYZ,./?:;!##$%_&*()`-+=1234567890"
decrypt = ''
for i in message:
x = alphabet.find(i)
new = (x + 5) % 74
decrypt += alphabet[new]
d2 = decrypt[::-1]
d3 = d2.replace("`", " ")
final = d3.replace("2", " ")
print
print final
u = 'e415bf03b4d860dccba57cea46371f831d772ba1deca47f28fa7d1f7'
p = 'c35f7f79dc34a678beb2b4106c84c9963561e7c64bc170e50c429b9a'
ur = raw_input('Enter your username: ')
ur1 = hashlib.sha224(ur).hexdigest()
pr = raw_input('Enter your password: ')
pr1 = hashlib.sha224(pr).hexdigest()
if ur1 == u and pr1 == p:
print 'Access granted'
sleep(1)
de()
print
end = raw_input('press q to quit: ')
while end != 'q':
print 'You did not type q'
end = raw_input('press q to quit: ')
if end == 'q':
quit()
else:
print 'Incorrect username or password'
sleep(1)
quit()

Python Auto Encryption Program

Hello guys I am a beginner at python and was trying to make an Encryption code which uses an encryption key defined by me for example I made this code but it isn't working:
def encrypt():
A = "f"
B = "d"
C = "z"
T = "x"
first = input()
print(first)
I want the program to function like when a user enters CAT in the input the output should be zax but when I input even A in my current program it prints
A as it is.
Any help would be appreciated!
You can just use string.translate method. A sample code would be:
def encrypt():
encryption_table = {
ord('A'):ord('f'),
ord('B'):ord('d'),
ord('C'):ord('z'),
ord('T'):ord('x'),
}
first = input()
print(first.translate(encryption_table))
For this code an input CAT will return zfx.
First you should make a dictionary to map your letter substitution , eg :
my_dict = { 'A':'f', 'B':'d', 'C':'z', 'T':'x', ... }
Then you need an encrypt function to return the values of this dictionary :
def encrypt(data):
return ''.join( my_dict[d] if d in my_dict else d for d in data )
And a decrypt function that does the opposite :
def decrypt(data):
my_dict_rev = dict((v,k) for k,v in my_dict.items())
return ''.join( my_dict_rev[d] if d in my_dict_rev else d for d in data )
Now lets test it :
my_data = 'TEST DATA'
enc_data = encrypt(my_data)
dec_data = decrypt(enc_data)
Output :
print(my_data)
print(enc_data)
print(dec_data)
TEST DATA
xESx Dfxf
TEST DATA
Here is a simple encryption and decryption script if you want to use it. The password part can be left out or you can leave it in. The same goes with the loading bar. the loading bar is on lines 1-4 and the password is on the last 9 lines. If you do take out the password make sure to call start. you will also need to install tqdm through pip.
import time
from tqdm import *
for i in tqdm(range(1000)):
time.sleep(0.001)
def encrypt(some_string):
alphabet = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'
cipher = 'bcdefghijklmnopqrstuvwxyzaBCDEFGHIJKLMNOPQRSTUVWXYZA'
encryption = ''
for char in some_string:
if(alphabet.find(char) == -1):
encryption = encryption + char
else:
position = alphabet.index(char)
encryption = encryption + cipher[position]
return encryption
def decrypt(some_string):
cipher = 'bcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZa'
alphabet = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'
decryption = ''
for char in some_string:
if(cipher.find(char) == -1):
decryption = decryption + char
else:
position = cipher.index(char)
decryption = decryption + alphabet[position]
return decryption
def restart():
print('Would you like to restart.')
print('1: Yes.')
print('2: No.')
c = float(input('Type a 1 or a 2: '))
if c == 1:
print('Ok you can restart.')
start()
if c == 2:
print('Sorry to see you leave.')
quit()
else:
print('Invalid response.')
restart()
def start():
print('1: Encryption')
print('2: Decryption')
e = float(input('Type a 1 or a 2: '))
if e == 1:
print('Type your message here.')
e = str(input('Enter message to encrypt: '))
print(encrypt(e))
restart()
if e == 2:
print('Type your messed up message here.')
e = str(input('Enter your messed up message: '))
print(decrypt(e))
restart()
else:
print('Please type a 1 or a 2.')
start()
def password():
a = float(input('Enter the correct password please: '))
if a == 5194703:
print('Correct!')
start()
else:
print('Invalid Password, try again!')
password()
password()

Categories