Let's Try Base64 Encode and Decode with Pyscript


輸入要加密文字:

def on_click(evt): click_event()

加密文字為:

原始文字為:

input = Element("input_text") out = Element("enc") def click_event(*ags, **kwgs): data = str(input.value) out.write(data) #data = 'signatute' #print(data) import micropip micropip.install('base64') import base64 data = data.encode('utf-8') result = base64.encodebytes(data).decode('utf-8') pyscript.write('enc', result) new_result = base64.decodebytes(result.encode('utf-8')).decode('utf-8') pyscript.write('dec', new_result)

輸入要解密的字串

def on_click(evt): click_event2()

解密後的文字為:

input2 = Element("input_text2") out2 = Element("dec2") def click_event2(*ags, **kwgs): data2 = str(input2.value) out2.write(data2) try: dec_result = base64.decodebytes(data2.encode('utf-8')).decode('utf-8') pyscript.write('dec2', dec_result) except(ValueError, ArithmeticError): pyscript.write('dec2', "輸入錯誤")

接下來嘗試將base64編碼的圖片轉回來

輸入Base64編碼的圖片

def on_click(evt): click_event3()

解密後的圖片為:

input3 = Element("input_text3") out3 = Element("dec3") def click_event3(*ags, **kwgs): data3 = str(input3.value) #out3.write(data3) try: imgdata = base64.b64decode(data3) pyscript.write('dec3', imgdata) with open('file.bin', 'wb') as f: imgdata2 = base64.b64decode(data3) f.write(imgdata2) #newimg = document.createElement("img") #newimg.setAttribute("src", imgdata) #element = document.getElementById("tem") #element.appendChild(newimg) except(ValueError, ArithmeticError): pyscript.write('dec3', "輸入錯誤")

有點問題,解碼後的圖片無法輸出,只能先用連覽器內建的解碼器顯示圖片