def connect(self): if self.connected: self.log('Warning (connect): already connected') return True # set lower connection if not self.s.connect(): return False try: # set encryption setup self.rsa = RSAPublic() self.aes = AESCipher() self.aes.gen_key() # set secure conn (raise an error if fails) self.set_connection('client') except Exception as e: self.log("Error (connect): can't connect - " + repr(e)) self.disconnect() return False self.connected = True self.log('Success (connect)') return True
def resetPassword(self): conn = connectToDB() cur = conn.cursor() user = self.parent.getPilot() print(user) if (self.txtNewPass.text() == self.txtConfirmPass.text()): if (self.validatePassword()): password = AESCipher('aids').encrypt(self.txtNewPass.text()) encpass = password.decode("utf-8") try: query = "UPDATE users SET password = %s WHERE user_id = %s" value = (encpass, user[0][0]) cur.execute(query, value) conn.commit() self.changeSuccess = changeSuccessClass(parent=self) self.changeSuccess.show() except Exception as e: print(e) self.parent.audit("Pilot " + str(user[0][0]) + " changed his password.") self.close()
def aes_encrypt(pwd): """ 加密当前文件夹下所有 txt 文件 """ aes = AESCipher(pwd) for txt_file in get_files_list('txt'): with open(txt_file, 'r', encoding='utf8') as f: contents = [ b64encode(aes.encrypt_line(line)) + LINE_BREAK for line in f ] with open(txt_file, 'w', encoding='utf8') as f: f.writelines(contents) print('{} 加密完成'.format(txt_file))
def aes_decrypt(pwd): """ 解密当前文件夹下所有 txt 文件 """ aes = AESCipher(pwd) for txt_file in get_files_list('txt'): with open(txt_file, 'r', encoding='utf8') as f: contents = [ aes.decrypt_line(b64decode(line)).decode() for line in f ] with open(txt_file, 'w', encoding='utf8') as f: f.writelines(contents) print('{} 解密完成'.format(txt_file))
def sendEmail(self): port = 465 mypass = (AESCipher('my password').decrypt( 'oNp8RcyRuLep8XYQ1JOJl57azvNzmeIrQ9pEKp0cIHs=')).decode() context = ssl.create_default_context() Recipient = self.txt_email.text() try: with smtplib.SMTP_SSL('smtp.gmail.com', port, context=context) as server: server.login('*****@*****.**', mypass) msg = MIMEMultipart('alternative') msg['Subject'] = 'Test Message' msg['To'] = self.txt_email.text() message = """ Code: %s """ % (self.code) msg.attach(MIMEText(message)) server.sendmail('*****@*****.**', Recipient, msg.as_string()) server.quit() print('Email Sent!') except Exception as e: print(e)
def connect(self): if self.connected: self.log('Warning (connect): already connected') return True # check lower connection if not self.s.connected: self.log('Error (connect): lower is not connected') return False try: # set encryption setup self.rsa = RSAPrivate() self.aes = AESCipher() # set secure conn (raise an error if fails) self.set_connection('server') except Exception as e: self.log("Error (connect): can't connect - " + repr(e)) self.disconnect() return False self.connected = True self.log('Success (connect)') return True
def receive(): """Handles receiving of messages.""" while True: try: msg = client.recv(BUFSIZ).decode("utf-8") if (msg[0] == "@"): priv_key = msg[1:] elif (':' in msg): print(msg) parsed_msg = msg.split(':') private_key = RSA.importKey(priv_key) decryptor = PKCS1_OAEP.new(private_key) decrypted_key = decryptor.decrypt(binascii.unhexlify(bytes(parsed_msg[2], "utf-8"))) print("Randomly generated key from the sender : ", decrypted_key.decode("utf-8")) new_aes = AESCipher(decrypted_key.decode("utf-8")) decrypted = new_aes.decrypt(bytes(parsed_msg[1], "utf-8")) print(parsed_msg[0] + ":" + decrypted.decode()) else: print(msg) except OSError: # Possibly client has left the chat. break
def updatePassword(self): conn = connectToDB() cur = conn.cursor() self.newPass = self.txtNewPass.text() if (self.validatePassword()): encpass = AESCipher('aids').encrypt(self.newPass) query = "UPDATE users SET password = %s WHERE email = %s" values = (encpass, self.email) cur.execute(query, values) conn.commit() self.parent.returnToHome()
def incremental_aes_decrypt(pwd, mark='*'): """ 针对增量加密的全文解密。 通常情况下没必要频繁解密之前已加密的内容,否则该使用场景并不适宜用增量加密。 """ aes = AESCipher(pwd) for txt_file in get_files_list('txt'): with open(txt_file, 'r', encoding='utf8') as f: contents = f.readlines() for i, line in enumerate(contents): if line.startswith(mark): decrypt_contents = [ aes.decrypt_line(b64decode(line)).decode() for line in contents[:i] ] decrypt_contents.extend(contents[i + 1:]) break else: continue with open(txt_file, 'w', encoding='utf8') as f: f.writelines('*' + LINE_BREAK) f.writelines(decrypt_contents) print('{} 解密完成'.format(txt_file))
def login(self): conn = connectToDB() cur = conn.cursor() user = self.txt_username.text() password = self.txt_password.text() # print(user + " " + password) cur.execute('SELECT user_id, username,password,user_type FROM users WHERE username = "******"' % (user)) self.result = cur.fetchall() # print(result) if (not self.result): print('NOT TODAY BOIII') self.lbl_response.setStyleSheet("QLabel {\ncolor: red; padding-left: 4px}") self.lbl_response.setText('Invalid username/password') self.txt_username.setStyleSheet("QLineEdit {\nborder: 1.2px solid red; padding-left: 4px}") self.txt_password.setStyleSheet("QLineEdit {\nborder: 1.2px solid red; padding-left: 4px;}") else: dbuser = self.result[0][1] dbuserType = self.result[0][3] dbpass = self.result[0][2] strpass = (AESCipher('aids').decrypt(dbpass)).decode() if (password == strpass): if (dbuserType == 0): self.clearText() print('YEHEEEEEY') self.homepage = adminhomepageClass(parent=self) self.audit("Admin logged in successfully") self.close() self.homepage.show() elif (dbuserType == 1): self.clearText() print('Pilot logging in') self.homepage = pilothomepageClass(parent=self) self.audit(self.currentUser[0][1] + " logged in successfully") self.close() self.homepage.show() else: print('NOT TODAY BOIII') self.lbl_response.setStyleSheet("QLabel {\ncolor: red; padding-left: 4px}") self.lbl_response.setText('Invalid username/password') self.txt_username.setStyleSheet("QLineEdit {\nborder: 1.2px solid red; padding-left: 4px}") self.txt_password.setStyleSheet("QLineEdit {\nborder: 1.2px solid red; padding-left: 4px;}")
def incremental_aes_encrypt(pwd, mark='*'): """ 增量加密。 :param pwd: 密码 :param mark: 区分加密与否的标识 该标识应在文件中独占一行,表示在其上的文本行均已加密,其下的文本行均未加密 注意标识不应有与 base64 编码后的密文相同的可能性 """ aes = AESCipher(pwd) for txt_file in get_files_list('txt'): with open(txt_file, 'r', encoding='utf8') as f: contents = f.readlines() encrypt_contents = encrypt_new_contents(aes, contents, mark) if encrypt_contents is False: # 跳过无标识的文件 print('{} 未找到标识'.format(txt_file)) continue with open(txt_file, 'w', encoding='utf8') as f: f.writelines(encrypt_contents) # 追加加密标识行 f.writelines(mark) print('{} 加密完成'.format(txt_file))
def insertToDB(self): try: monthList = { '' : '00', 'January': '01', 'February': '02', 'March': '03', 'April': '04', 'May': '05', 'June': '06', 'July': '07', 'August': '08', 'September': '09', 'October': '10', 'November': '11', 'December': '12' } fname = self.txt_fname.text() lname = self.txt_lname.text() if (self.rbtn_female.isChecked()): gender = 0 elif (self.rbtn_male.isChecked()): gender = 1 else: gender = '' month = self.cmb_month.currentText() day = self.cmb_day.currentText() year = self.cmb_year.currentText() birthday = datetime.datetime.strptime(monthList[month] + day + year, '%m%d%Y').date() address = self.txt_address.text() city = self.txt_city.text() province = self.txt_province.text() zipCode = self.txt_zip.text() email = self.txt_email.text() mobile = self.txt_mobile.text() emContact = self.txt_emContact.text() emNumber = self.txt_emNumber.text() certNo = self.txt_certificate.text() operator = self.txt_operator.text() issueDate = datetime.datetime.strptime(monthList[self.cmb_issue_month.currentText()] + self.cmb_issue_day.currentText() + self.cmb_issue_year.currentText(), '%m%d%Y').date() expire = datetime.datetime.strptime(monthList[self.cmb_expiry_month.currentText()] + self.cmb_expiry_day.currentText() + self.cmb_expiry_year.currentText(), '%m%d%Y').date() conn = connectToDB() cur = conn.cursor() cur.execute('INSERT INTO address(permanent_address, city, province, zipcode) VALUES' '("%s","%s","%s",%s)' % (address, city, province, zipCode)) conn.commit() cur.execute('SELECT address_id FROM address WHERE permanent_address = "%s" AND zipcode = %s' % (address,zipCode)) result = cur.fetchall() address_id = 0 for row in result: for i in row: address_id = i self.username = fname[0:1] + lname[0:] self.password = lname[0:1] + fname[0:] # password = lname encpass = AESCipher('aids').encrypt(self.password) query = """INSERT INTO users(address_id, user_img, last_name, first_name, username, password, user_type, license_date, license_expiry, certif_no, emergency_contact, emergency_number, operator, gender, date_of_birth, email, phone_number) VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s)""" # values = (address_id, lname, fname, self.username, encpass, 1, issueDate, expire, certNo, emContact, emNumber, # operator, gender, birthday, email, mobile) values = (str(address_id), self.dbimage, str(lname), str(fname), str(self.username), encpass, 1, issueDate, expire, str(certNo), str(emContact), str(emNumber), str(operator), gender, birthday, str(email), str(mobile)) cur.execute(query, values) conn.commit() self.addSuccess = addSuccessClass(parent=self) self.addSuccess.setWindowFlags(self.addSuccess.windowFlags() | QtCore.Qt.WindowStaysOnTopHint) self.addSuccess.show() except Exception as e: self.addError = addErrorClass(parent=self) self.addError.setWindowFlags(self.addError.windowFlags() | QtCore.Qt.WindowStaysOnTopHint) self.addError.show() self.audit("Admin added pilot " + fname + " " + lname)
import socket from threading import Thread from Encryption import AESCipher from Crypto.PublicKey import RSA from Crypto.Cipher import PKCS1_OAEP import binascii import string import random # Create random symmetric key key = ''.join(random.choices(string.ascii_uppercase + string.digits, k=10)) print("Random generated key of user : "******"""Handles receiving of messages.""" while True: try: msg = client.recv(BUFSIZ).decode("utf-8") if (msg[0] == "@"): priv_key = msg[1:] elif (':' in msg): print(msg) parsed_msg = msg.split(':') private_key = RSA.importKey(priv_key) decryptor = PKCS1_OAEP.new(private_key) decrypted_key = decryptor.decrypt(binascii.unhexlify(bytes(parsed_msg[2], "utf-8"))) print("Randomly generated key from the sender : ", decrypted_key.decode("utf-8")) new_aes = AESCipher(decrypted_key.decode("utf-8"))