encryption with ceasar principal - python

I want to code a short programme. My idea was to code a login window. Then the next window opens and then I should be able to encrypt a text I wrote into a ScrolledText. The whole encryption should be done with the ceasar principal. I combined my code(at the bottom) with this one:
def caesar(text, schluessel):
geheim = ''
for i in text:
number = ord(i) + schluessel #122 = 119+3
if number > 122:
number -= 26
elif number == 32 + schluessel: #whitespace
number = 32
letter = chr(number)
geheim += letter
print(geheim)
I recieved this error message:
Exception in Tkinter callback
Traceback (most recent call last):
File "C:\Program Files\Python38\lib\tkinter\__init__.py", line 1883, in __call__
return self.func(*args)
File "C:/Users/pc/PycharmProjects/test_22_11_22/main.py", line 77, in caesar
for i in encryptiontextentry:
File "C:\Program Files\Python38\lib\tkinter\__init__.py", line 1643, in cget
return self.tk.call(self._w, 'cget', '-' + key)
TypeError: can only concatenate str (not "int") to str
This is my code:
from tkinter import *
from tkinter.scrolledtext import ScrolledText
class Login:
def __init__(self):
self.user ={'1':'1'}
self.loginwindow = Tk()
self.loginwindow.geometry("500x300")
self.loginwindow.resizable(width= False, height= False)
self.loginlabel = Label(text="Login",font= ("arial",50))
self.loginausgabe = Label(self.loginwindow)
self.loginusernamelabel = Label(self.loginwindow, text="Username",font= ("arial",12))
self.loginusernameentry = Entry(self.loginwindow,font= ("arial",12))
self.loginpasswordlabel = Label(self.loginwindow,text="Password",font= ("arial",12))
self.loginpasswordentry = Entry(self.loginwindow,font= ("arial",12), show="*")
self.loginbtn = Button(self.loginwindow,text="login",width= 38, command=self.login)
self.loginlabel.place(x="140",y="0")
self.loginausgabe.place(x="140",y="140")
self.loginusernamelabel.place(x="140",y ="80")
self.loginusernameentry.place(x="230",y="80")
self.loginpasswordlabel.place(x="140",y ="100")
self.loginpasswordentry.place(x="230",y="100")
self.loginbtn.place(x="140",y="120")
self.loginwindow.mainloop()
def login(self):
loginusernameentry = self.loginusernameentry.get()
if loginusernameentry in self.user.keys():
if self.loginpasswordentry.get() == self.user[loginusernameentry]:
self.loginausgabe.config(text="Welcome!")
self.encryption()
else: self.loginausgabe.config(text="Invalid password!")
else: self.loginausgabe.config(text="Unknown User!")
self.loginusernameentry.config(text="")
self.loginusernameentry.config(text="")
def encryption(self):
self.loginwindow.destroy()
self.encryptionwindow = Tk()
self.encryptionwindow.geometry("1000x600")
self.encryptionwindow.resizable(width= False, height= False)
self.encryptiontextlabel = Label(self.encryptionwindow,text="encryption text",font= ("arial",12))
self.encryptiontextentry = ScrolledText(self.encryptionwindow)
self.decryptiontextlabel = Label(self.encryptionwindow,text="dencryption text",font= ("arial",12))
self.decryptiontextentry = ScrolledText(self.encryptionwindow)
self.encryptionbtn = Button(self.encryptionwindow,text="encrypt",command=self.caesar)
self.caesarkeyencryption = Entry(self.encryptionwindow,width="2")
self.decryptionbtn = Button(self.encryptionwindow,text="decrypt",command=self.caesar)
self.caesarkeydecryption = Entry(self.encryptionwindow,width="2")
self.decryptiontextlabel.place(x="120", y="310")
self.decryptiontextentry.place(x="120", y="330", width="800",height="200")
self.encryptiontextlabel.place(x="120", y="40")
self.encryptiontextentry.place(x="120", y="60", width="800",height="200")
self.encryptionbtn.place(x="120",y="260")
self.caesarkeyencryption.place(x="170",y="264")
self.decryptionbtn.place(x="120",y="530")
self.caesarkeydecryption.place(x="170",y="534")
self.encryptionwindow.mainloop()
** def caesar(self):
caesarkeyencryption = int(self.caesarkeyencryption.get())
encryptiontextentry = self.encryptiontextentry
print(caesarkeyencryption)
encryptiontextresult = ''
for i in encryptiontextentry:
number = ord(i) + caesarkeyencryption
if number > 122:
number -= 26
elif number == 32 + caesarkeyencryption: #whitespace
number = 32
letter = chr(number)
encryptiontextresult += letter
print(encryptiontextresult)
**
l = Login()

Related

Python KeyError(RSA Algorithm)

I am trying to execute this code but I am getting this error:
line 37, in \<module\>
encrypt(encryption_key_pair\[0\],encryption_key_pair\[1\],secret_message
line 22, in encrypt
enc_text = num_trans\[ord_num\]
KeyError: 32
\[Finished in 1.1s\]
Here's the part of the code:
from alphabet import transform, num_trans
from key_generator import generate_keys, encryption_key_pair, decryption_key_pair
#enc_key = [5,14]
#dec_key = [11,14]
secret_message = "abc"
encrypted_message = []
decrypted_message = []
def encrypt(e, modulus, message):
global enc_message
for character in message:
#print(character)
#enc_char = ord(character)
enc_char = transform[f'{character}']
#print(enc_char)
ord_num = (enc_char**e)%modulus
#print(ord_num)
#enc_text = chr(ord_num)
enc_text = num_trans[ord_num]
enc_message = encrypted_message.append(enc_text)
def decrypt(d, modulus, message):
global dec_message
for character in message:
decode_char = transform[f'{character}']
deord_char = (decode_char**d)%modulus
#print(deord_char)
dec_text = num_trans[deord_char]
dec_message = decrypted_message.append(dec_text)
encrypt(encryption_key_pair[0],encryption_key_pair[1],secret_message)
decrypt(decryption_key_pair[0],decryption_key_pair[1],encrypted_message)
print(encrypted_message)
print(decrypted_message)

DES Encryption in python error(TypeError: Object type <class 'str'> cannot be passed to C code)

I build des encryption_gui. I got error:
TypeError: Object type <class 'str'> cannot be passed to C code
from Crypto.Cipher import DES
from tkinter import *
gui = Tk()
def click_btn(event):
print("btn click")
def pad(text):
n = len(text) % 8
return text + (b' ' * n)
t_p = textfield_e.get()
text1 = t_p
t_key = textfield_key.get()
key = t_key
des = DES.new(key, DES.MODE_ECB)
padded_text = pad(text1)
encrypted_text = des.encrypt(padded_text)
textfield_d.insert(0,encrypted_text)
def pad(text):
n = len(text) % 8
return text + (b' ' * n)
gui.geometry('540x600')
gui.title('PyCryptor')
title_h = Label(gui,text='Encryption',font=('kanit',22))
title_h.pack(pady=10)
plant_box = Label(gui,text='Plain Text')
plant_box.pack()
textfield_e = Entry(gui,justify=CENTER,font=('font',15),relief='solid')
textfield_e.pack(side=TOP,fill=X,padx=30,pady=10,ipady=10)
key_box = Label(gui,text='Encryption Key')
key_box.pack()
textfield_key = Entry(gui,justify=CENTER,font=('font',10),relief='solid')
textfield_key.pack(side=TOP,fill=X,padx=50,pady=10,ipady=10)
btn_en = Button(gui,text='Encrypt',width=7,height=1,relief='solid',activebackground='orange',activeforeground='#fff')
btn_en.pack(ipadx=7)
btn_en.bind('<Button-1>',click_btn)
title_h = Label(gui,text='Cipher Text',font=('kanit',22))
title_h.pack(pady=10)
textfield_d = Entry(gui,justify=CENTER,font=('font',15),relief='solid')
textfield_d.pack(side=TOP,fill=X,padx=30,pady=20,ipady=50)
gui.mainloop()
Output :
btn click
Exception in Tkinter callback
Traceback (most recent call last):
File "C:\Users\PAssWORD\AppData\Local\Programs\Python\Python39\lib\tkinter\__init__.py", line 1892, in __call__
return self.func(*args)
File "c:\Users\PAssWORD\Music\encryt.py", line 19, in click_btn
des = DES.new(key, DES.MODE_ECB)
File "C:\Users\PAssWORD\AppData\Local\Programs\Python\Python39\lib\site-packages\Crypto\Cipher\DES.py", line 145, in new
return _create_cipher(sys.modules[__name__], key, mode, *args, **kwargs)
File "C:\Users\PAssWORD\AppData\Local\Programs\Python\Python39\lib\site-packages\Crypto\Cipher\__init__.py", line 79, in _create_cipher
return modes[mode](factory, **kwargs)
File "C:\Users\PAssWORD\AppData\Local\Programs\Python\Python39\lib\site-packages\Crypto\Cipher\_mode_ecb.py", line 216, in _create_ecb_cipher
cipher_state = factory._create_base_cipher(kwargs)
File "C:\Users\PAssWORD\AppData\Local\Programs\Python\Python39\lib\site-packages\Crypto\Cipher\DES.py", line 76, in _create_base_cipher
result = start_operation(c_uint8_ptr(key),
File "C:\Users\PAssWORD\AppData\Local\Programs\Python\Python39\lib\site-packages\Crypto\Util\_raw_api.py", line 232, in c_uint8_ptr
raise TypeError("Object type %s cannot be passed to C code" % type(data))
TypeError: Object type <class 'str'> cannot be passed to C code
You need to pass bytes instead of str to DES.new() and pad(), so change the following lines:
text1 = t_p
...
key = t_key
to
text1 = t_p.encode()
...
key = t_key.encode()
Also the logic of pad() function is incorrect, it should be like below:
def pad(text):
n = len(text) % 8
if n:
n = 8 - n
return text + (b' ' * n)
Also you have defined pad() twice.
Note that AES should be used instead of DES.

Why won't Python script run after computer restart?

After a restart my script won't work anymore.
It worked before. Windows popping up, things needed to typed in and there was a result which I was happy with (like v0.9-alpha-happy). Now it yells at me.
import random
import tkinter as tk
from tkinter import simpledialog
from tkinter import messagebox
from tkinter import *
alleSpieler = []
team_eins = []
first_window = tk.Tk
first_window.withdraw()
def main():
global alleSpieler, i, x
i = 1
x = simpledialog.askinteger("Spieleranzahl", "Anzahl der Spieler: ")
if x % 2 == 0:
while i < x + 1:
spieler = simpledialog.askstring("Spielername", "Gib Spielername {} ein: ".format(i))
alleSpieler.append(spieler)
i = i + 1
else:
messagebox.showinfo("Nope", "Bitte gib eine gerade Anzahl von Spielern ein!")
main()
def sec():
j = 1
while j <= len(alleSpieler):
random_name = random.choice(alleSpieler)
team_eins.append(random_name)
alleSpieler.remove(random_name)
j = j + 1
def teams():
root = Tk()
t = Text(root)
for n in team_eins:
t.insert(END,"Team 1: " + n + "\n")
for n in alleSpieler:
t.insert(END,"Team 2: " + n + "\n")
t.pack()
root.mainloop()
main()
sec()
team1()
And the error(s):
/Users/benediktrautenberg/PycharmProjects/TeamGenerator/venv/bin/python /Users/benediktrautenberg/PycharmProjects/TeamGenerator/Generator.py
Traceback (most recent call last):
File "/Users/benediktrautenberg/PycharmProjects/TeamGenerator/Generator.py", line 48, in <module>
main()
File "/Users/benediktrautenberg/PycharmProjects/TeamGenerator/Generator.py", line 17, in main
x = simpledialog.askinteger("Spieleranzahl", "Anzahl der Spieler: ")
File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/tkinter/simpledialog.py", line 343, in askinteger
d = _QueryInteger(title, prompt, **kw)
File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/tkinter/simpledialog.py", line 271, in __init__
Dialog.__init__(self, parent, title)
File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/tkinter/simpledialog.py", line 137, in __init__
if parent.winfo_viewable():
AttributeError: 'NoneType' object has no attribute 'winfo_viewable'
Process finished with exit code 1
All I did to solve this error was:
first_window = Tk()
first_window.withdraw()
You forgot the () near Tk, so your not actually instantiating it properly.

exception used to pop up alert box from button event in tkinter, cant find out the root for the problem

so my program takes a directory with excel files with one line and combine them all into one.
The gui has two buttons one to choose the path and one to save the wanted path.
I created a gui class and im basically trying to pass the OptionMenu chosen text forward after an event was made, but an exception is raised and Im struggling with,
long story short:
import os
from tkinter import *
from tkinter import filedialog
from CombineExcelFiles import *
class GUI:
def __init__(self, master):
self.master = master
master.title('מיזוג קבצי אקסל')
master.geometry('220x100')
self.credit = Label(master, text='')
self.credit.pack()
self.variable = StringVar(master)
self.variable.set('חלבי')
self.opt = OptionMenu(master, self.variable, 'חלבי', 'פרווה')
self.opt.pack()
Button(window, text='בחר תיקייה למיזוג', command=upload).pack(side=RIGHT)
Button(window, text='בחר תייקת הורדה', command=save).pack(side=LEFT)
def upload():
global basepath
basepath = filedialog.askdirectory()
def save():
#print(self.variable.get())
try: #This is line 25
basepath
file_list = []
download_path = filedialog.askdirectory()
for entry in os.listdir(basepath):
if os.path.isfile(os.path.join(basepath, entry)):
if entry[len(entry)-5:] == '.xlsx' and len(entry) == 17:
file_list.append(entry)
data = getData(basepath, file_list)
writeToFile(data, file_list, download_path, master.variable.get())
except NameError:
tkinter.messagebox.showerror('ERROR', 'בחר תיקיית מקור')
This is the writeToFile from CombineExcelFiles:
def writeToFile(data, files,download_path,variable):
file = Workbook()
ws = file.active
center = Alignment(horizontal='center', vertical='center')
br = Border(left=Side(style='thin'),
right=Side(style='thin'),
top=Side(style='thin'),
bottom=Side(style='thin'))
.
.
.
col = 'C'
row = 3
count = 0
for i in data:
temp = files[count]
for j in i[::-1]:
if type(j) == int or type(j) == float:
ws[col + str(row)].value = ('%.2f' %j)
ws[col + str(row)].alignment = center
ws[col + str(row)].border = br
col = chr(ord(col)+1)
ws['J' + str(row)].value = temp[6:8] + '/' + temp[4:6] + '/' + temp[:4]
ws['K' + str(row)].value = temp[8:10] + ':' + temp[10:12]
row +=1
col = 'C'
ws = fitToCell(ws)
temp_date = datetime.now()
file.save(download_path + '/' + 'מעקב ' + variable + str(temp_date.month) + '-' +
str(temp_date.year) + '.xlsx' )
The error that was given is:
Exception in Tkinter callback
Traceback (most recent call last):
File "C:\Users\******\Anaconda3\lib\tkinter\__init__.py", line 1699, in __call__
return self.func(*args)
File "C:/Users/******/CombineExcels/mainProject.py", line 25, in save
print(self.variable.get())
TypeError: writeToFile() missing 1 required positional argument: 'variable'
Thank you in advance
Edit, Ive put the code n one file so it will be runnable:
import os
from tkinter import *
from tkinter import filedialog
from openpyxl import Workbook
from openpyxl import load_workbook
from openpyxl.styles import Alignment
from openpyxl.styles.borders import Border, Side
from datetime import datetime
class GUI:
def __init__(self, master):
self.master = master
master.title('מיזוג קבצי אקסל')
master.geometry('220x100')
self.credit = Label(master, text='')
self.credit.pack()
self.variable = StringVar(master)
self.variable.set('בחר מרשימה')
self.opt = OptionMenu(master, self.variable, 'חלבי', 'פרווה')
self.opt.pack()
Button(window, text='בחר תיקייה למיזוג', command=upload).pack(side=RIGHT)
Button(window, text='בחר תייקת הורדה', command=save).pack(side=LEFT)
#START GUI PROPERTIES
def upload(self):
global basepath
basepath = filedialog.askdirectory()
print(master)
def save(self):
file_list = []
download_path = filedialog.askdirectory()
for entry in os.listdir(basepath):
if os.path.isfile(os.path.join(basepath, entry)):
if entry[len(entry)-5:] == '.xlsx' and len(entry) == 17:
file_list.append(entry)
data = getData(basepath, file_list)
print(self.variable.get())
writeToFile(data, file_list, download_path)
#STOP GUI PROPERTIES
def getData(self, basepath, file_list):
a = []
for file in file_list:
load_workbook(basepath + '/' + file)
tempData = []
for cell in temp['Sheet1']:
for value in cell:
if value.value == None:
continue
else:
tempData.append(value.value)
data.append(tempData)
return data
def fitToCell(self, ws): #get used columns and than fit cell's width into length of letters
dict = {}
for cell in ws:
for value in cell:
temp = str(value.value)
if temp:
if value.coordinate[0] not in dict:
dict[value.coordinate[0]] = len(temp)
elif len(temp) > dict[value.coordinate[0]]:
dict[value.coordinate[0]] = len(temp)
for col in dict:
ws.column_dimensions[col].width = dict[col]
return ws
def writeToFile(self, data, files,download_path):
file = Workbook()
ws = file.active
center = Alignment(horizontal='center', vertical='center')
br = Border(left=Side(style='thin'),
right=Side(style='thin'),
top=Side(style='thin'),
bottom=Side(style='thin'))
print(ws.evenHeader.right.text)
if self.variable.get() == 'חלבי':
ws['C2'].value = 'חלב רצוי'
ws['C2'].alignment = center
ws['C2'].border = br
ws['D2'].value = 'חלב מצוי'
ws['D2'].alignment = center
ws['D2'].border = br
ws['E2'].value = 'קקאו רצוי'
ws['E2'].alignment = center
ws['E2'].border = br
ws['F2'].value = 'קקאו מצוי'
ws['F2'].alignment = center
ws['F2'].border = br
ws['G2'].value = 'שמן רצוי'
ws['G2'].alignment = center
ws['G2'].border = br
ws['H2'].value = 'שמן מצוי'
ws['H2'].alignment = center
ws['H2'].border = br
ws['I2'].value = 'סוכר רצוי'
ws['I2'].alignment = center
ws['I2'].border = br
ws['J2'].value = 'סוכר מצוי'
ws['J2'].alignment = center
ws['J2'].border = br
ws['I2'].value = 'מספר מתכון'
ws['I2'].alignment = center
ws['I2'].border = br
ws['J2'].value = 'זמן ייצור'
ws['J2'].alignment = center
ws['J2'].border = br
ws['K2'].value = 'תאריך ייצור'
ws['K2'].alignment = center
ws['K2'].border = br
col = 'C'
row = 3
count = 0
for i in data:
temp = files[count]
for j in i[::-1]:
if type(j) == int or type(j) == float:
ws[col + str(row)].value = ('%.2f' %j)
ws[col + str(row)].alignment = center
ws[col + str(row)].border = br
col = chr(ord(col)+1)
ws['J' + str(row)].value = temp[6:8] + '/' + temp[4:6] + '/' + temp[:4]
ws['J' + str(row)].alignment = center
ws['J' + str(row)].border = br
ws['K' + str(row)].value = temp[8:10] + ':' + temp[10:12]
ws['K' + str(row)].border = br
ws['K' + str(row)].alignment = center
row +=1
col = 'C'
ws = fitToCell(ws)
temp_date = datetime.now()
file.save(download_path + '/' + 'מעקב ' + self.variable.get() +' ' + str(temp_date.month) + '-' + str(temp_date.year) + '.xlsx' )
window = Tk()
my_gui = GUI(window)
#print(my_gui.variable.get())
window.mainloop()
This is the error:
runfile('C:/Users/*****/Desktop/תכנות/untitled2.py',
wdir='C:/Users/*****/Desktop/תכנות')
Exception in Tkinter callback
Traceback (most recent call last):
File "C:\Users\*****\Anaconda3\lib\tkinter\__init__.py", line 1699, in __call__
return self.func(*args)
File "C:/Users/*****/CombineExcels/mainProject.py", line 25, in save
TypeError: writeToFile() missing 1 required positional argument: 'var'
For some reason it keeps returning from another path
solved it, had put all the methods inside the object, while the events func inside the init.
also i ran too many times the program so the errors were not related to my code...

Why is my Caesar Cipher program not displaying my encrypted message? Resolution is off too?

I am creating a Caesar Cipher program for class in Python and I was am getting errors when hitting the encrypt button. Also the sizes of the buttons are all out of whack and I can't figure out how to change that. I am very new to Python so please in simplest terms.
This is one of the errors I am getting
Traceback (most recent call last):
File "/Users/Chandler/Desktop/caesar/CSCI220-Assign2-CaesarEncode-CTL.py", line 67, in <module>
main()
File "/Users/Chandler/Desktop/caesar/CSCI220-Assign2-CaesarEncode-CTL.py", line 44, in main
while not contains(buttonPoint1, win.getMouse()):
TypeError: contains() missing 1 required positional argument: 'ptIn'
but any other additional errors noticed will be helpful as well.
Thanks!
from graphics import *
def main():
width = 300
height = 150
win = GraphWin("Caesar Cipher, Chandler Long")
buttonPoint1 = Point(width/2-80, 9*height/10-15)
buttonPoint2 = Point(width/2+80, 9*height/10+15)
button1 = Rectangle(buttonPoint1, buttonPoint2)
labelB = Text(Point(width/2, 9*height/10), "Cipher")
label1 = Text(Point(width/6, height/5), "Enter Message:")
label2 = Text(Point(width/6, 2*height/5), "Key:")
label3 = Text(Point(width/6, 3*height/5), "Your Message:")
labelV = Text(Point(2*width/3, 3*height/5), "")
input1 = Entry(Point(2*width/3, height/5), width//20)
input2 = Entry(Point(2*width/3, 2*height/5), 3)
graphOb = [button1, labelB, label1, label2, input1, input2]
for graphicsObject in graphOb:
graphicsObject.draw(win)
while not contains(buttonPoint1, buttonPoint2, win.getMouse()):
None
labelB.setText("Quit")
try:
labelV.setText(cipher(textBox1.getText(), int(textBox2.getText())))
except:
label3.setText('Error:')
labelV.setText('Invalid key.')
label3.draw(win)
labelV.draw(win)
while not contains(buttonPoint1, win.getMouse()):
None
win.close()
def contains(pt1, pt2, ptIn):
return pt1.getX() < ptIn.getX() and ptIn.getX() < pt2.getX()
pt1.getY() < ptIn.getY() and ptIn.getY() < pt2.getY()
def encrypt(message, key):
cleartext = ""
letterLow = "abcdefghijklmnopqrstuvwxyz"
letterCap = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
for char in text:
if char in lettersLow:
cleartext = cleartext + chr((ord(char) + key - ord("a")) % 26 + ord("a"))
elif char in letterCap:
cleartext = cleartext + chr((ord(char) + key - ord("A")) % 26 + ord("A"))
else:
cleartext = cleartext + char
return cleartext
#end main
main()
You are calling contains with 2 arguments even though it is defined with three arguments.
while not contains(buttonPoint1, win.getMouse()):
None
win.close()
def contains(pt1, pt2, ptIn):
return pt1.getX() < ptIn.getX() and ptIn.getX() < pt2.getX()
pt1.getY() < ptIn.getY() and ptIn.getY() < pt2.getY()
File "/Users/Chandler/Desktop/caesar/CSCI220-Assign2-CaesarEncode-CTL.py", line 44, in main
while not contains(buttonPoint1, win.getMouse()):
You are missing an and in the definition of contains(). If you want to have the definition of contains() return the full true false value, it should be
def contains(pt1, pt2, ptIn):
return pt1.getX() < ptIn.getX() and ptIn.getX() < pt2.getX() and
pt1.getY() < ptIn.getY() and ptIn.getY() < pt2.getY()
As you have it, it will return the value of the first line and ignore the second line.
Another possible error may be
for char in text:
I do not see where text has been initialized and passed into encrypt(message, key) You do not use the input argument message. It may be that you meant to use one where you used the other.

Categories

Resources