# 資安code update 12/29 15:12 ```python= # AES_RSA.py # AES..done # RSA..done # GUI..done # 12/29 15:12 from Crypto.Cipher import AES import os import hashlib from Crypto.Util import Counter import base64 from Crypto import Random from Crypto.Hash import SHA #RSA NEED from Crypto.Cipher import PKCS1_v1_5 as Cipher_pkcs1_v1_5 from Crypto.Signature import PKCS1_v1_5 as Signature_pkcs1_v1_5 from Crypto.PublicKey import RSA import tkinter as tk #from tkinter import * from tkinter.filedialog import askdirectory,askopenfilename class AES_Cipher: @staticmethod def md5sum( raw ): m = hashlib.md5() m.update(raw.encode("utf-8")) return m.hexdigest() BS = AES.block_size @staticmethod def pad( s ): """note that the padding is no necessary""" """return s + (Cipher.BS - len(s) % Cipher.BS) * chr(Cipher.BS - len(s) % Cipher.BS)""" return s @staticmethod def unpad( s ): """return s[0:-ord(s[-1])]""" return s def __init__(self, key): self.key = AES_Cipher.md5sum(key) #the state of the counter callback self.cnter_cb_called = 0 self.secret = None def _reset_counter_callback_state( self, secret ): self.cnter_cb_called = 0 self.secret = secret def _counter_callback( self ): """ this function should be stateful """ self.cnter_cb_called += 1 return (self.secret[self.cnter_cb_called % AES_Cipher.BS] * AES_Cipher.BS).to_bytes(16, byteorder="little") def encrypt(self, raw): secret = os.urandom( AES_Cipher.BS ) self._reset_counter_callback_state( secret ) cipher = AES.new( self.key, AES.MODE_CTR, counter = self._counter_callback ) raw_padded = AES_Cipher.pad( raw ) enc_padded = cipher.encrypt( raw_padded ) return secret+enc_padded def decrypt(self, enc): secret = enc[:AES_Cipher.BS] self._reset_counter_callback_state( secret ) cipher = AES.new( self.key, AES.MODE_CTR, counter = self._counter_callback ) enc_padded = enc[AES_Cipher.BS:] raw_padded = cipher.decrypt( enc_padded ) return AES_Cipher.unpad( raw_padded ) ################################################# class RSA_Cipher: def _encrypt(self): with open('public.pem',"r") as f: key = f.read() AES_KEY = self.AES_KEY rsakey = RSA.importKey(key) cipher = Cipher_pkcs1_v1_5.new(rsakey) cipher_key = base64.b64encode(cipher.encrypt(AES_KEY.encode(encoding="utf-8"))) with open('AES_KEY_encrypted','wb') as f: f.write(cipher_key) def _dencrypt(self): _path = K_path_entry.get() with open(_path,'rb') as f: AES_KEY_encrypted = f.read() with open('private.pem') as f: key = f.read() rsakey = RSA.importKey(key) cipher = Cipher_pkcs1_v1_5.new(rsakey) the_key = cipher.decrypt(base64.b64decode(AES_KEY_encrypted), "ERROR") return the_key def __init__ (self, AES_KEY): self.AES_KEY = AES_KEY ############################################## def selectF_Path(): path_ = askopenfilename() f_path.set(path_) def selectK_Path(): path_ = askopenfilename() key_path.set(path_) def selectEF_Path(): path_ = askopenfilename() Ef_path.set(path_) def _encrypt_the_file(): key = key_show_entry.get() cipher = AES_Cipher(key) file_path = f_path_entry.get() with open(file_path,'r') as f: test = f.read() encrypted = cipher.encrypt(test.encode("utf-8")) encrypted = base64.b64encode(encrypted) #str_encrypt = (str(encrypted,encoding="utf-8")) with open(file_path+"_encrypted", 'w') as f: f.write(str(encrypted,encoding="utf-8")) generate_the_RSA_key_pair() _encrypt_the_key() #_dencrypt_the_file() #------------------------test def _dencrypt_the_file(): thekey = _dencrypt_the_key() thekey = str(thekey,encoding="utf-8") cipher = AES_Cipher(thekey) __path = EF_path_entry.get() with open(__path, 'r') as f: encrypted = f.read() plain_text = cipher.decrypt(base64.b64decode(encrypted)) with open(__path+"_OUTPUT.txt", 'wb') as f: f.write(plain_text) def generate_the_RSA_key_pair(): random_generator = Random.new().read rsa = RSA.generate(1024, random_generator) private_pem = rsa.exportKey() with open('private.pem', 'wb') as f: f.write(private_pem) public_pem = rsa.publickey().exportKey() with open('public.pem', 'wb') as f: f.write(public_pem) def _encrypt_the_key(): cipher = RSA_Cipher(AES_key.get()) cipher._encrypt() def _dencrypt_the_key(): cipher = RSA_Cipher(AES_key.get()) return cipher._dencrypt() ################################################## #tk.Entry(window, textvariable = path).grid(row = 0, column = 1) #tk.Button(window, text = "path", command = selectPath).grid(row = 0, column = 2) #################################################### if __name__ == '__main__': window = tk.Tk() f_path = tk.StringVar() AES_key = tk.StringVar() key_path = tk.StringVar() Ef_path = tk.StringVar() window.title('RSA+AES Hybrid Encryption') window.geometry('400x400') window.configure(background='white') #------------------------------------------------- encrypt_Label = tk.Label(text = '加密') encrypt_Label.grid(row = 0,column = 1,pady = 10) f_path_entry = tk.Entry(textvariable = f_path,highlightcolor='blue', highlightthickness=1) f_path_entry.grid(row = 1,column = 1,padx = 20,pady = 10) encrypt_Label2 = tk.Label(text = '加密檔案') encrypt_Label2.grid(row = 1,column = 0) path_Button = tk.Button(text='選擇檔案路徑' ,command = selectF_Path) path_Button.grid(row = 1,column = 2) key_show_entry = tk.Entry(textvariable = AES_key, highlightthickness=1) key_show_entry.grid(row = 2,column = 1,padx = 10,pady = 10) key_ge_Label = tk.Label(text='輸入密鑰' ) key_ge_Label.grid(row = 2,column = 0,padx = 5) encrypt_Button = tk.Button(text='加密' ,command = _encrypt_the_file) encrypt_Button.grid(row = 3,column = 1,pady = 5) #------------------------------------------------ dencrypt_Label = tk.Label(text = '解密') dencrypt_Label.grid(row = 4,column = 1,pady = 10) K_path_entry = tk.Entry(textvariable = key_path,highlightcolor='blue', highlightthickness=1) K_path_entry.grid(row = 5,column = 1,padx = 20,pady = 10) dencrypt_Label2 = tk.Label(text = 'RSA加密後鑰匙') dencrypt_Label2.grid(row = 5,column = 0) K_path_Button = tk.Button(text='選擇檔案路徑' ,command = selectK_Path) K_path_Button.grid(row = 5,column = 2) EF_path_entry = tk.Entry(textvariable = Ef_path,highlightcolor='blue', highlightthickness=1) EF_path_entry.grid(row = 6,column = 1,padx = 20,pady = 10) dencrypt_Label3 = tk.Label(text = '要解密的檔案') dencrypt_Label3.grid(row = 6,column = 0) EF_path_Button = tk.Button(text='選擇檔案路徑' ,command = selectEF_Path) EF_path_Button.grid(row = 6,column = 2) dencrypt_Button = tk.Button(text='解密' ,command = _dencrypt_the_file) dencrypt_Button.grid(row = 7,column = 1,pady = 5) #------------------------------------------------------- window.mainloop() ##################################################### #key = "A1B2C3D4E5F6G7H8" ## key """ Bsize = AES.block_size mode = AES.MODE_CTR cipher = AES_Cipher(key) with open("test",'r') as f: test = f.read() #print('originalText(add space" "to blocksize):'+test) encrypted = cipher.encrypt(test.encode("utf-8")) encrypted = base64.b64encode(encrypted) str_encrypt = (str(encrypted,encoding="utf-8")) with open('testout' , 'w') as f: f.write(str(encrypted,encoding="utf-8")) #print('ciperText(base64):'+str_encrypt) """ """ plain_text = cipher.decrypt(base64.b64decode(encrypted)) str_plain = (str(plain_text,encoding="utf-8")) print('plainText :'+str_plain) if((test) == str_plain): print("\nThe plainText is the originaltext") """ ``` 12/28 ```python= # AES_RSA.py # AES..done # RSA..50% # GUI..80% # 12/28 08:22 from Crypto.Cipher import AES import os import hashlib from Crypto.Util import Counter import base64 from Crypto import Random from Crypto.Hash import SHA #RSA NEED from Crypto.Cipher import PKCS1_v1_5 as Cipher_pkcs1_v1_5 from Crypto.Signature import PKCS1_v1_5 as Signature_pkcs1_v1_5 from Crypto.PublicKey import RSA import tkinter as tk #from tkinter import * from tkinter.filedialog import askdirectory,askopenfilename class AES_Cipher: @staticmethod def md5sum( raw ): m = hashlib.md5() m.update(raw.encode("utf-8")) return m.hexdigest() BS = AES.block_size @staticmethod def pad( s ): """note that the padding is no necessary""" """return s + (Cipher.BS - len(s) % Cipher.BS) * chr(Cipher.BS - len(s) % Cipher.BS)""" return s @staticmethod def unpad( s ): """return s[0:-ord(s[-1])]""" return s def __init__(self, key): self.key = AES_Cipher.md5sum(key) #the state of the counter callback self.cnter_cb_called = 0 self.secret = None def _reset_counter_callback_state( self, secret ): self.cnter_cb_called = 0 self.secret = secret def _counter_callback( self ): """ this function should be stateful """ self.cnter_cb_called += 1 return (self.secret[self.cnter_cb_called % AES_Cipher.BS] * AES_Cipher.BS).to_bytes(16, byteorder="little") def encrypt(self, raw): secret = os.urandom( AES_Cipher.BS ) self._reset_counter_callback_state( secret ) cipher = AES.new( self.key, AES.MODE_CTR, counter = self._counter_callback ) raw_padded = AES_Cipher.pad( raw ) enc_padded = cipher.encrypt( raw_padded ) return secret+enc_padded def decrypt(self, enc): secret = enc[:AES_Cipher.BS] self._reset_counter_callback_state( secret ) cipher = AES.new( self.key, AES.MODE_CTR, counter = self._counter_callback ) enc_padded = enc[AES_Cipher.BS:] raw_padded = cipher.decrypt( enc_padded ) return AES_Cipher.unpad( raw_padded ) ################################################# def selectPath(): path_ = askopenfilename() path.set(path_) def _encrypt_the_file(): key = key_show_entry.get() cipher = AES_Cipher(key) file_path = path_entry.get() with open(file_path,'r') as f: test = f.read() encrypted = cipher.encrypt(test.encode("utf-8")) encrypted = base64.b64encode(encrypted) #str_encrypt = (str(encrypted,encoding="utf-8")) with open(file_path+"_encrypted", 'w') as f: f.write(str(encrypted,encoding="utf-8")) def _encrypt_the_AESKEY(): ################################################## #tk.Entry(window, textvariable = path).grid(row = 0, column = 1) #tk.Button(window, text = "path", command = selectPath).grid(row = 0, column = 2) ##################################################### if __name__ == '__main__': random_generator = Random.new().read rsa = RSA.generate(1024, random_generator) private_pem = rsa.exportKey() with open('private.pem', 'wb') as f: f.write(private_pem) public_pem = rsa.publickey().exportKey() with open('public.pem', 'wb') as f: f.write(public_pem) message = 'hello ghost, this is a plian text' with open('public.pem',"r") as f: key = f.read() rsakey = RSA.importKey(key) cipher = Cipher_pkcs1_v1_5.new(rsakey) cipher_text = base64.b64encode(cipher.encrypt(message.encode(encoding="utf-8"))) print(cipher_text) with open('private.pem') as f: key = f.read() rsakey = RSA.importKey(key) cipher = Cipher_pkcs1_v1_5.new(rsakey) text = cipher.decrypt(base64.b64decode(cipher_text), "ERROR") print(text) ###################### window = tk.Tk() path = tk.StringVar() AES_key = tk.StringVar() window.title('RSA+AES Hybrid Encryption') window.geometry('800x600') window.configure(background='white') path_entry = tk.Entry(textvariable = path,highlightcolor='blue', highlightthickness=1) path_entry.grid(row = 0,column = 1,padx = 20,pady = 10) path_Button = tk.Button(text='選擇路徑' ,command = selectPath) path_Button.grid(row = 0,column = 2) key_show_entry = tk.Entry(textvariable = AES_key, highlightthickness=1) key_show_entry.grid(row = 1,column = 1,padx = 10,pady = 10) key_ge_Button = tk.Label(text='輸入密鑰' ) key_ge_Button.grid(row = 1,column = 0,padx = 5) encrypt_Button = tk.Button(text='加密' ,command = _encrypt_the_file) encrypt_Button.grid(row = 2,column = 1) window.mainloop() ##################################################### #key = "A1B2C3D4E5F6G7H8" ## key """ Bsize = AES.block_size mode = AES.MODE_CTR cipher = AES_Cipher(key) with open("test",'r') as f: test = f.read() #print('originalText(add space" "to blocksize):'+test) encrypted = cipher.encrypt(test.encode("utf-8")) encrypted = base64.b64encode(encrypted) str_encrypt = (str(encrypted,encoding="utf-8")) with open('testout' , 'w') as f: f.write(str(encrypted,encoding="utf-8")) #print('ciperText(base64):'+str_encrypt) """ """ plain_text = cipher.decrypt(base64.b64decode(encrypted)) str_plain = (str(plain_text,encoding="utf-8")) print('plainText :'+str_plain) if((test) == str_plain): print("\nThe plainText is the originaltext") """""" ``` --- 12/27 ```python= # AES..done # RSA # GUI from Crypto.Cipher import AES import os import hashlib from Crypto.Util import Counter import base64 import tkinter as tk #from tkinter import * from tkinter.filedialog import askdirectory,askopenfilename class Cipher: @staticmethod def md5sum( raw ): m = hashlib.md5() m.update(raw.encode("utf-8")) return m.hexdigest() BS = AES.block_size @staticmethod def pad( s ): """note that the padding is no necessary""" """return s + (Cipher.BS - len(s) % Cipher.BS) * chr(Cipher.BS - len(s) % Cipher.BS)""" return s @staticmethod def unpad( s ): """return s[0:-ord(s[-1])]""" return s def __init__(self, key): self.key = Cipher.md5sum(key) #the state of the counter callback self.cnter_cb_called = 0 self.secret = None def _reset_counter_callback_state( self, secret ): self.cnter_cb_called = 0 self.secret = secret def _counter_callback( self ): """ this function should be stateful """ self.cnter_cb_called += 1 return (self.secret[self.cnter_cb_called % Cipher.BS] * Cipher.BS).to_bytes(16, byteorder="little") def encrypt(self, raw): secret = os.urandom( Cipher.BS ) #random choose a "secret" which is not secret self._reset_counter_callback_state( secret ) cipher = AES.new( self.key, AES.MODE_CTR, counter = self._counter_callback ) raw_padded = Cipher.pad( raw ) enc_padded = cipher.encrypt( raw_padded ) return secret+enc_padded #yes, it is not secret def decrypt(self, enc): secret = enc[:Cipher.BS] self._reset_counter_callback_state( secret ) cipher = AES.new( self.key, AES.MODE_CTR, counter = self._counter_callback ) enc_padded = enc[Cipher.BS:] #we didn't encrypt the secret, so don't decrypt it raw_padded = cipher.decrypt( enc_padded ) return Cipher.unpad( raw_padded ) ################################################# def selectPath(): path_ = askopenfilename() path.set(path_) ################################################## window = tk.Tk() path = tk.StringVar() window.title('RSA+AES Hybrid Encryption') window.geometry('800x600') window.configure(background='white') path_Button = tk.Button(text='選擇路徑' ,command = selectPath) path_Button.grid(row = 0,column = 2) path_entry = tk.Entry(textvariable = path) path_entry.grid(row = 0,column = 1) #tk.Entry(window, textvariable = path).grid(row = 0, column = 1) #tk.Button(window, text = "path", command = selectPath).grid(row = 0, column = 2) ##################################################### window.mainloop() ##################################################### Bsize = AES.block_size mode = AES.MODE_CTR key = "A1B2C3D4E5F6G7H8" ## key cipher = Cipher(key) with open("test",'r') as f: test = f.read() print('originalText(add space" "to blocksize):'+test) encrypted = cipher.encrypt(test.encode("utf-8")) encrypted = base64.b64encode(encrypted) str_encrypt = (str(encrypted,encoding="utf-8")) with open('testout' , 'w') as f: f.write(str(encrypted,encoding="utf-8")) print('ciperText(base64):'+str_encrypt) plain_text = cipher.decrypt(base64.b64decode(encrypted)) str_plain = (str(plain_text,encoding="utf-8")) print('plainText :'+str_plain) if((test) == str_plain): print("\nThe plainText is the originaltext") ```