尝试将base64与Tkinter文本一起使用时出现奇怪错误

时间:2014-12-07 00:23:29

标签: python encryption tkinter base64

我目前正在制作一个简单的工具,使用以下代码中的一些代码加密/删除文本:https://stackoverflow.com/a/16321853/4285156

当我在CMD中运行它时,它工作得非常好。当我尝试将代码与Tkinter Text()小部件一起使用时,问题出现了。

以下是我的计划的屏幕截图:http://i.imgur.com/8sTkAUN.png

正如您所看到的,它会加密文本“Hello,world”。正好。问题在于,每当我尝试解密某些内容时,控制台都会给我一条错误消息,但它无法正常工作。

我认为这与我正在使用Text()小部件的事实有关,但是为什么它在我加密东西时起作用,但在尝试解密时却不行?正如我之前所说,当我不使用Tkinter时,它可以正常工作。

以下是代码:

from Tkinter import *
import base64

password = "aS4KmfkKr5662LfLKjrI6Kan4fK"

def encode(key, clear):
    enc = []
    for i in range(len(clear)):
        key_c = key[i % len(key)]
        enc_c = chr((ord(clear[i]) + ord(key_c)) % 256)
        enc.append(enc_c)
    return base64.urlsafe_b64encode("".join(enc))

def decode(key, enc):
    dec = []
    enc = base64.urlsafe_b64decode(enc)
    for i in range(len(enc)):
        key_c = key[i % len(key)]
        dec_c = chr((256 + ord(enc[i]) - ord(key_c)) % 256)
        dec.append(dec_c)
    return "".join(dec)


GUI = Tk()
GUI.title('Cryppy')
GUI.minsize(width=300, height=300)

txt1 = Label(GUI, text="Decrypted Text")
txt1.grid(row=0, column=0, sticky=W, padx=(10,10))

tBox1 = Text(GUI, bd=2, width=60, height=5)
tBox1.grid(row=1, column=0, sticky=W, padx=(10,10))

txt2 = Label(GUI, text="Encrypted Text:")
txt2.grid(row=2, column=0, sticky=W, padx=(10,10))

tBox2 = Text(GUI, bd=2, width=60, height=5)
tBox2.grid(row=3, column=0, sticky=W, padx=(10,10))

def cryptIt():
    codeIt = encode(password, tBox1.get("1.0", "end-1c"))
    print codeIt
    tBox2.delete("1.0", END)
    tBox2.insert(END, codeIt)

def decryptIt():
    decodeIt = decode(password, tBox2.get("1.0", "end-1c"))
    print decodeIt
    tBox1.delete("1.0", END)
    tBox1.insert(END, decodeIt)

bCrypt = Button(GUI, text="Encrypt", command=cryptIt)
bCrypt.grid(row=4, sticky=W, padx=(10,10))

bCrypt2 = Button(GUI, text="Decrypt", command=decryptIt)
bCrypt2.grid(row=4, sticky=W, padx=(65,10))

GUI.mainloop()

这是错误消息

Exception in Tkinter callback
Traceback (most recent call last):
  File "E:\Python27\lib\lib-tk\Tkinter.py", line 1486, in __call__
    return self.func(*args)
  File "C:\Users\Runar\Google Drive\Prosjekter\SyncNote\Source Code\mainEx.py", line 47, in decryptIt
    decodeIt = decode(password, tBox2.get("1.0", "end-1c"))
  File "C:\Users\Runar\Google Drive\Prosjekter\SyncNote\Source Code\mainEx.py", line 16, in decode
    enc = base64.urlsafe_b64decode(enc)
  File "E:\Python27\lib\base64.py", line 112, in urlsafe_b64decode
    return b64decode(s, '-_')
  File "E:\Python27\lib\base64.py", line 71, in b64decode
    s = _translate(s, {altchars[0]: '+', altchars[1]: '/'})
  File "E:\Python27\lib\base64.py", line 36, in _translate
    return s.translate(''.join(translation))
TypeError: character mapping must return integer, None or unicode

1 个答案:

答案 0 :(得分:0)

我认为urlsafe_b64decode不适用于unicode。只需输入字符串ascii,例如

  enc = base64.urlsafe_b64decode(enc.encode('ascii','ignore'))

希望这有帮助。