def cetakAbsensi(self): if len(self.absensi) > 0: absensi = self.absensi tmp = np.copy(self.absensi) for i in range(len(absensi)): for j in range(2, len(absensi[i]) - 1): if absensi[i, j] == "": tmp[i, j] = "belum absen" elif int( aes.AESCipher(absensi[i, -1]).decrypt( absensi[i, j])) < 0: tmp[i, j] = "tidak hadir" elif int( aes.AESCipher(absensi[i, -1]).decrypt( absensi[i, j])) > 0: tmp[i, j] = "hadir" tmp = tmp[:, :-1] colhead = [ 'NIM', 'Nama', 'p1', 'p2', 'p3', 'p4', 'p5', 'p6', 'p7', 'p8', 'p9', 'p10', 'p11', 'p12' ] df = pd.DataFrame(tmp) df.to_excel('Absensi %s.xlsx' % self.matkulSelected.get(), index=False, header=colhead) messagebox.showinfo( "Message", "Absensi tersimpan sebagai Absensi %s.xlsx" % self.matkulSelected.get())
def saveChangePreview(self, data): tempidx = self.pertemuan.get().split(' ')[-1] if self.selected.get() == 'Hadir': bil_random = str(np.random.randint(1, high=100)) enkripsi = aes.AESCipher( data[-1]).encrypt(bil_random).decode('utf-8') sql = "UPDATE absensi a INNER JOIN mahasiswa m ON m.id = a.mhs_id INNER JOIN mata_kuliah k ON k.id = a.matkul_id SET p" + tempidx + " = %s WHERE m.nim = %s AND k.nama = %s" csr.execute(sql, (enkripsi, str(data[0]), self.matkul.get())) db.commit() else: bil_random = str(np.random.randint(-100, high=-1)) enkripsi = aes.AESCipher( data[-1]).encrypt(bil_random).decode('utf-8') sql = "UPDATE absensi a INNER JOIN mahasiswa m ON m.id = a.mhs_id INNER JOIN mata_kuliah k ON k.id = a.matkul_id SET p" + tempidx + " = %s WHERE m.nim = %s AND k.nama = %s" csr.execute(sql, (enkripsi, str(data[0]), self.matkul.get())) db.commit() self.clearPreview() sql = "SELECT a.mhs_id, a.p1, a.p2, a.p3, a.p4, a.p5, a.p6, a.p7, a.p8, a.p9, a.p10, a.p11, a.p12 FROM absensi a INNER JOIN mahasiswa m ON a.mhs_id = m.id INNER JOIN mata_kuliah k ON a.matkul_id = k.id INNER JOIN user u ON u.mhs_dos_id = m.id WHERE k.nama = %s AND role='mahasiswa'" csr.execute(sql, (self.matkul.get(), )) temp = np.array(csr.fetchall(), dtype=str) self.kehadiran = temp[:, int(tempidx)] self.writeToTable( self.tempData[(self.mainPageNumber - 1) * 10:self.mainPageNumber * 10], self.kehadiran[(self.mainPageNumber - 1) * 10:self.mainPageNumber * 10])
def __init__(self, mode: AuthMode, **kwargs): self.token = None print(mode) if mode == AsciiBot.AuthMode.TOKEN: self.token = kwargs['token'] elif mode == AsciiBot.AuthMode.CRYPTO_TOKEN: cipher = aes.AESCipher(key=kwargs['key']) self.token = cipher.decrypt(kwargs['token']) elif mode == AsciiBot.AuthMode.INTERACTIVE: token = input('EncryptedToken: ') key = getpass.getpass(prompt='Password: '******'Filename: ') \ if 'filename' not in kwargs else kwargs['filename'] key = getpass.getpass(prompt='Password: '******'key' not in kwargs else kwargs['key'] cipher = aes.AESCipher(key=key) self.token = cipher.decrypt(open(filename, 'r').read()) else: raise Exception('Mode', 'UnknownMode') self.updater = telegram.ext.Updater(token=self.token) self.dispatcher = self.updater.dispatcher font_size = int(input("Font size: ")) \ if 'font_size' not in kwargs else kwargs['font_size'] default_width = int(input("Default width: ")) \ if 'default_width' not in kwargs else kwargs['default_width'] # The main picture converter self.converter = image_processing.AsciiImageProcessing( font_size, default_size=(default_width, default_width)) # Handlers registration start_command_handler = telegram.ext.CommandHandler( 'start', self.start_command) self.dispatcher.add_handler(start_command_handler) text_message_handler = telegram.ext.MessageHandler( telegram.ext.Filters.text, self.text_message_echo) self.dispatcher.add_handler(text_message_handler) photo_handler = telegram.ext.MessageHandler(telegram.ext.Filters.photo, self.photo_message, pass_chat_data=True, pass_user_data=True) self.dispatcher.add_handler(photo_handler)
def aesTest(): mykey = "iliketrains" myMessage = "Voici mon message AES" cipher = aes.AESCipher(key=mykey) encrypted = cipher.encrypt(myMessage) print('##### AES encrypted , ', myMessage) print(encrypted) new_cipher = aes.AESCipher(key=mykey) decrypted = new_cipher.decrypt(encrypted) print('##### AES de crypted') print(decrypted)
def __init__(self): try: with open('keys.json') as file: documents = json.load(file) print("keys.json found. Proceeding ...") encrypted_api_key = documents["exchanges"][0]['keys'][0][ 'api-key'] encrypted_api_secret = documents["exchanges"][0]['keys'][1][ 'api-secret'] self.base_url = documents["exchanges"][0]["api-url"] key = input("Enter your password :"******"keys.json doesn't exist. Creating the file ...") with open('keys.json', "w") as file: self.api_key = input("Enter your API-key :") self.api_secret = input("Enter your API-secret :") self.base_url = 'https://api.binance.com/' key = input("Enter your password :"******"api-key": str(cipher.encrypt(api_key).decode()) }, { "api-secret": str(cipher.encrypt(api_secret).decode()) }] }) data = json.dump(data, file) except KeyError: print( "There seems to be an error within the \"keys.json\" file. Terminating the program ..." ) exit()
def load_enckeypair(file_name, passwd): try: keypair = load_keypair(file_name, passwd) return (keypair.publickey(), aes.AESCipher(passwd).encrypt(keypair.exportKey())) except Exception as err: raise Exception("Error while loading keypair: " + err.message)
def decrypt(self, encryptedText, seed): secretKey = self.hmac_sha3_512(seed) cipher = aes.AESCipher(secretKey) decryptedText = cipher.decrypt(encryptedText) try: decryptedText = decryptedText.decode('utf-8') return decryptedText except UnicodeDecodeError: return ""
def encrypt(self, inputSecretText, seed): secretKey = self.hmac_sha3_512(seed) cipher = aes.AESCipher(secretKey) encryptedText = cipher.encrypt(inputSecretText) try: encryptedText = encryptedText.decode('utf-8') return encryptedText except UnicodeDecodeError: return ""
def onClipChange(self, *args): # não fazer nada se nenhum utilizador estiver ligado if self.userCombo.get_active() == -1: return if not self.ignore_clip: # send clip data to list view # self.view.appendData(clip_data) # do msg encryption scheme msg = self.clipboard.wait_for_text() randomBytes = urandom( min(self.keyPair.publicKey.size() / 8, len(msg))).encode("hex") criptogram = aes.AESCipher(randomBytes).encrypt(msg) encRandomBytes = self.keyPair.encrypt(randomBytes) encMsg = criptogram + ":" + encRandomBytes entryTime = times.epochtime() print("entry time", entryTime) msgEntry = str(entryTime) + ":" + encMsg # save to end of file if not self.checkUserIntegrity(self.userCombo.get_active_text()): self.logoutCurrentUser() self.promptError( "User inválido.", "Os ficheiros do utilizador foram corrompidos.") return # clip history with open( files_location + file_prefix + self.userCombo.get_active_text() + clip_sufix, "a") as f: try: fcntl.flock(f, fcntl.LOCK_EX | fcntl.LOCK_NB) f.write(msgEntry + "\n") except Exception as err: fcntl.flock(f, fcntl.LOCK_UN) raise err # hash log with open( files_location + file_prefix + self.userCombo.get_active_text() + hash_sufix, "a") as f: try: fcntl.flock(f, fcntl.LOCK_EX | fcntl.LOCK_NB) f.write(hashez.salted(msg) + "\n") except Exception as err: fcntl.flock(f, fcntl.LOCK_UN) raise err # add entry to view self.view.appendData(times.strftime(entryTime)) else: self.ignore_clip = False
def saveToFile(self, key, vaultData): raw_text = "" for x in range(len(vaultData)-1): raw_text += str(vaultData[x]) + "\n" raw_text += str(vaultData[len(vaultData)-1]) cipher = aes.AESCipher(key) dataToWrite = cipher.encrypt(raw_text) myFile = open("pw-" + self.vaultName + ".dspm", "wb") myFile.write(dataToWrite) myFile.close()
def showAbsensi(self, absensi): self.clearTable() for i in range(len(absensi)): self.MidContain1.append( Label(self.frameMid, font="12", width="4", text=str(i + 1))) self.MidContain2.append( Label(self.frameMid, font="12", width="10", text=absensi[i, 0])) self.MidContain3.append( Label(self.frameMid, font="12", width="45", text=absensi[i, 1])) self.MidContain1[-1].grid(row=i + 1, column=0) self.MidContain2[-1].grid(row=i + 1, column=1) self.MidContain3[-1].grid(row=i + 1, column=2) for j in range(3, 15): if absensi[i, j - 1] == "": self.MidContain4.append( Label(self.frameMid, width="2", bg="#ffffff", borderwidth="1", relief="groove")) elif int( aes.AESCipher(absensi[i, -1]).decrypt( absensi[i, j - 1])) < 0: self.MidContain4.append( Label(self.frameMid, width="2", bg="#ff0000", borderwidth="1", relief="groove")) elif int( aes.AESCipher(absensi[i, -1]).decrypt( absensi[i, j - 1])) > 0: self.MidContain4.append( Label(self.frameMid, width="2", bg="#00ff00", borderwidth="1", relief="groove")) self.MidContain4[-1].grid(row=i + 1, column=j)
def readPasswordFile(self, key): pwFile = open("pw-" + self.vaultName + ".dspm", "r") fileData = pwFile.read() if len(fileData) < 16: #this is a dodgy hack, fix the aes decrypt function to use a better IV noData = [] return noData cipher = aes.AESCipher(key) decryptedText = cipher.decrypt(fileData) decryptedData = decryptedText.split("\n") pwFile.close() return decryptedData
def openVault(self): myFile = open("secret-" + self.vaultName + ".dspm", "rb") fileData = myFile.read() myFile.close() data = fileData.split("\n".encode('utf-8')) mySalt = (data[0]).decode('utf-8') encryptedKey = data[1] password = getpass.getpass() hashedPassword = pbkdf2_sha256.hash(password, salt=str.encode(mySalt)) cipher = aes.AESCipher(hashedPassword) key = cipher.decrypt(encryptedKey) print("Vault opened.") self.auth = True return key
def startAbsen(self): tempidx = self.pertemuan.get().split(' ')[-1] self.scanBluetooth() data = self.tempData for i in range(len(self.btAddrAbsen)): for addr, name in self.nearby_devices: if addr == self.btAddrAbsen[i].upper(): bil_random = str(np.random.randint(1, high=100)) enkripsi = aes.AESCipher( data[i][-1]).encrypt(bil_random).decode('utf-8') sql = "UPDATE absensi a INNER JOIN mahasiswa m ON m.id = a.mhs_id INNER JOIN mata_kuliah k ON k.id = a.matkul_id SET p" + tempidx + " = %s WHERE m.nim = %s AND k.nama = %s" csr.execute(sql, (enkripsi, str(data[i][0]), self.matkul.get())) db.commit() sql = "SELECT a.mhs_id, a.p1, a.p2, a.p3, a.p4, a.p5, a.p6, a.p7, a.p8, a.p9, a.p10, a.p11, a.p12 FROM absensi a INNER JOIN mahasiswa m ON a.mhs_id = m.id INNER JOIN mata_kuliah k ON a.matkul_id = k.id INNER JOIN user u ON u.mhs_dos_id = m.id WHERE k.nama = %s AND role='mahasiswa'" csr.execute(sql, (self.matkul.get(), )) temp = np.array(csr.fetchall(), dtype=str) self.kehadiran = temp[:, int(tempidx)] self.writeToTable( self.tempData[(self.mainPageNumber - 1) * 10:self.mainPageNumber * 10], self.kehadiran[(self.mainPageNumber - 1) * 10:self.mainPageNumber * 10])
else: key_times = [] aes_enc_times = [] rsa_enc_times = [] rsa_crt_dec_times = [] rsa_dec_times = [] aes_dec_times = [] for i in range(ITERATIONS): print "Execution %d..." % i rsa_bob = rsa.RSACipher() with measure_time(key_times): rsa_bob.gen_key_pair(1024) public_key_bob = rsa_bob.get_public_key() key = "HardcodedKey?lol" # 128-bits key aes128 = aes.AESCipher(key) input = sys.argv[1] # reading and printing the message with measure_time(aes_enc_times): ciphertext = aes128.encrypt(input) rsa_alice = rsa.RSACipher() rsa_alice.set_public_key(public_key_bob) with measure_time(rsa_enc_times): e_key = rsa_alice.encrypt_string(key) with measure_time(rsa_dec_times): key = rsa_bob.decrypt_string(e_key) with measure_time(rsa_crt_dec_times): key = rsa_bob.decrypt_string(e_key, True)
def copyEntryToClipboard(self, widget): if self.userCombo.get_active() == -1: return loginOk = False response = Gtk.ResponseType.OK dialog = None passwd = None while not loginOk and response == Gtk.ResponseType.OK: if not self.checkUserIntegrity(self.userCombo.get_active_text()): self.logoutCurrentUser() self.promptError( "User inválido.", "Os ficheiros do utilizador foram corrompidos.") break dialog = LoginDialog(self, self.userCombo.get_active_text()) response = dialog.run() loginOk = False if (response == Gtk.ResponseType.OK): # fez login print(dialog.passEntry.get_text()) # pass passwd = dialog.passEntry.get_text() # ver se tem todos os ficheiros if (not self.checkUserIntegrity( self.userCombo.get_active_text())): self.logoutCurrentUser() response == Gtk.ResponseType.OK self.promptError( "User inválido.", "Os ficheiros do utilizador foram corrompidos.") dialog.destroy() break clip_file = files_location + file_prefix + self.userCombo.get_active_text( ) + clip_sufix # ver se a pass corresponde ao ficheiro with open(clip_file, "r") as f: if not hashez.verify(passwd, f.readline().replace("\n", "")): self.promptError( "Password incorreta.", "A password introduzida está incorreta.") else: loginOk = True dialog.destroy() if loginOk: (model, path) = self.view.get_selection().get_selected_rows() entry = times.strf2epoch(model[path[0]][0]) clip_file = files_location + file_prefix + self.userCombo.get_active_text( ) + clip_sufix encMessage = '' encRandomBytes = '' with open(clip_file, "rw+") as f: lines = f.readlines() for line in range(len(lines)): if lines[line].split(":")[0] == str(entry): encMessage = lines[line].split(":")[1] encRandomBytes = lines[line].split(":")[2].replace( "\n", "") randomBytes = self.keyPair.decrypt(encRandomBytes, passwd) originalMessage = aes.AESCipher(randomBytes).decrypt(encMessage) self.ignore_clip = True self.clipboard.set_text(originalMessage, -1) self.promptInfo("Copy", 'Copiado com sucesso!')
def encrypt(self, password, message): crypt = aes.AESCipher(password).encrypt(message) return crypt
line1 = "Initiating protocol: AES(SHA256(ECDH), CBC, IV)" line2 = "Message format: IV + AES(message)" line3 = "420173635064, 4558608748405, 15517495227187" line4 = "13847371191292, 7178231866375" line5 = "12740127109992, 2657998351758" line6 = "12108314104269, 7751833675327" line7 = "Send me flag plz" line8 = "Here you go: TG17{large_primes_are_nice}" line9 = "Thanks!" line10 = "End connection" line11 = "Connection closed" secret = "27356762530" key = SHA256.new() key.update(secret) cipher = aes.AESCipher(key.digest()) print("B: " + base64.b64encode(line0)) print("A: " + base64.b64encode(line1)) print("A: " + base64.b64encode(line2)) print("A: " + base64.b64encode(line3)) print("A: " + base64.b64encode(line4)) print("B: " + base64.b64encode(line5)) print("A: " + base64.b64encode(line6)) print("B: " + cipher.encrypt(line7)) print("A: " + cipher.encrypt(line8)) print("B: " + cipher.encrypt(line9)) print("B: " + cipher.encrypt(line10)) print("A: " + cipher.encrypt(line11))
import aes from base64 import b64decode from base64 import b64encode KEY = "evlzctfverymahan" cipher = aes.AESCipher(KEY) def encrypt(plaintext): return cipher.encrypt(plaintext) def decrypt(ciphertext): return cipher.decrypt(ciphertext) # Generate AES Encrypted Cookie based on format: # encrypt( "username:<0/1>"(=>admin_flag) ) # ex. "batterycharger:1", cookie: b64encode(927e323b9ea14b1d8f1459d106b6074a6db48f0b24f00137859d3d4cb08284b0) # OWUwMTk0M2E0YjY4MGJhZGIzZGZkZGEwN2Q1MmM4YjE= def generateCookie(username, admin): cookie_string = username + ":1" if admin else username + ":0" encrypted_cookie = encrypt(cookie_string) # encode encrypted_cookie string to bytes and convert to b64 encoded_cookie = b64encode(encrypted_cookie.encode()) return encoded_cookie.decode() def decryptCookie(encoded_cookie): try: encrypted_cookie = b64decode(encoded_cookie)
def __init__(self): self.config = buu_config.config self.redis_ins = redis.Redis(host = self.config.redis_addr, port = self.config.redir_port, \ db = self.config.redis_db, password = self.config.redis_password) self.encryptor = aes.AESCipher(self.config.aes_key)
def decrypt_string(x): salt = get_salt() cipher = aes.AESCipher(salt[:32].encode(), salt[32:48].encode()) return cipher.decrypt(x.encode()).decode()
def to_encrypt(s): return aes.AESCipher(aes_key).encrypt(s)
def to_decrypt(s): return aes.AESCipher(aes_key).decrypt(s)
def encrypt_and_save(token, key, filename): cipher = aes.AESCipher(key=key) encrypted_token = cipher.encrypt(token) f = open(filename, 'w') f.write(encrypted_token) f.close()
def writeToTable(self, data, hadir): self.clearMainTable() kehadiran = [] if len(data) % 10 != 0: for i in range(len(data) % 10): self.mainTblContain1[i].config( text=str((self.mainPageNumber - 1) * 10 + i + 1)) self.mainTblContain2[i].config(text=data[i][0]) self.mainTblContain3[i].config(text=data[i][1]) if hadir[i] == '': self.mainTblContain4[i].config(text="Belum Absen") kehadiran.append(False) elif int(aes.AESCipher(data[i, -1]).decrypt(hadir[i])) < 0: self.mainTblContain4[i].config(text="Tidak Hadir") kehadiran.append(False) elif int(aes.AESCipher(data[i, -1]).decrypt(hadir[i])) > 0: self.mainTblContain4[i].config(text="Hadir") kehadiran.append(True) j = 0 if j <= i: self.mainTbl1Contain5.config( text="Preview", command=lambda: self.previewData(data[0], kehadiran[0]), bg="#049723") j += 1 if j <= i: self.mainTbl2Contain5.config( text="Preview", command=lambda: self.previewData(data[1], kehadiran[1]), bg="#049723") j += 1 if j <= i: self.mainTbl3Contain5.config( text="Preview", command=lambda: self.previewData(data[2], kehadiran[2]), bg="#049723") j += 1 if j <= i: self.mainTbl4Contain5.config( text="Preview", command=lambda: self.previewData(data[3], kehadiran[3]), bg="#049723") j += 1 if j <= i: self.mainTbl5Contain5.config( text="Preview", command=lambda: self.previewData(data[4], kehadiran[4]), bg="#049723") j += 1 if j <= i: self.mainTbl6Contain5.config( text="Preview", command=lambda: self.previewData(data[5], kehadiran[5]), bg="#049723") j += 1 if j <= i: self.mainTbl7Contain5.config( text="Preview", command=lambda: self.previewData(data[6], kehadiran[6]), bg="#049723") j += 1 if j <= i: self.mainTbl8Contain5.config( text="Preview", command=lambda: self.previewData(data[7], kehadiran[7]), bg="#049723") j += 1 if j <= i: self.mainTbl9Contain5.config( text="Preview", command=lambda: self.previewData(data[8], kehadiran[8]), bg="#049723") else: for i in range(10): self.mainTblContain1[i].config( text=str((self.mainPageNumber - 1) * 10 + i + 1)) self.mainTblContain2[i].config(text=data[i][0]) self.mainTblContain3[i].config(text=data[i][1]) if hadir[i] == '': self.mainTblContain4[i].config(text="Belum Absen") kehadiran.append(False) elif int(aes.AESCipher(data[i, -1]).decrypt(hadir[i])) < 0: self.mainTblContain4[i].config(text="Tidak Hadir") kehadiran.append(False) elif int(aes.AESCipher(data[i, -1]).decrypt(hadir[i])) > 0: self.mainTblContain4[i].config(text="Hadir") kehadiran.append(True) j = 0 self.mainTbl1Contain5.config( text="Preview", command=lambda: self.previewData(data[0], kehadiran[0]), bg="#049723") j += 1 self.mainTbl2Contain5.config( text="Preview", command=lambda: self.previewData(data[1], kehadiran[1]), bg="#049723") j += 1 self.mainTbl3Contain5.config( text="Preview", command=lambda: self.previewData(data[2], kehadiran[2]), bg="#049723") j += 1 self.mainTbl4Contain5.config( text="Preview", command=lambda: self.previewData(data[3], kehadiran[3]), bg="#049723") j += 1 self.mainTbl5Contain5.config( text="Preview", command=lambda: self.previewData(data[4], kehadiran[4]), bg="#049723") j += 1 self.mainTbl6Contain5.config( text="Preview", command=lambda: self.previewData(data[5], kehadiran[5]), bg="#049723") j += 1 self.mainTbl7Contain5.config( text="Preview", command=lambda: self.previewData(data[6], kehadiran[6]), bg="#049723") j += 1 self.mainTbl8Contain5.config( text="Preview", command=lambda: self.previewData(data[7], kehadiran[7]), bg="#049723") j += 1 self.mainTbl9Contain5.config( text="Preview", command=lambda: self.previewData(data[8], kehadiran[8]), bg="#049723") j += 1 self.mainTbl10Contain5.config( text="Preview", command=lambda: self.previewData(data[9], kehadiran[9]), bg="#049723")
# coding: utf8 import os import logging import hashlib from datetime import datetime import argparse from flask import Flask, request import aes import mail import conf app = Flask(__name__) aes_cipher = aes.AESCipher(conf.mail_relay_key) @app.route('/mail_login', methods=['POST']) def mail_login(): enc_email, enc_password, sign = request.form['email'], request.form[ 'password'], request.form['sign'] email, password = aes_cipher.decrypt(enc_email), aes_cipher.decrypt( enc_password) logging.debug('email:%s, password:%s, sign:%s', email, password, sign) sign_computed = hashlib.sha1( '%s:%s:%s' % (email, password, conf.mail_relay_key)).hexdigest() if sign != sign_computed: return '', 401
def decrypt(self, password, message): decrypt = aes.AESCipher(password).decrypt(message) return decrypt
def dec_privkey(privkey, passwd): return RSA.importKey(aes.AESCipher(passwd).decrypt(privkey))
def encryptKey(self, key, userHashedPass): cipher = aes.AESCipher(userHashedPass) cipherText = cipher.encrypt(key) return cipherText
def decrypt_and_return(key, filename): cipher = aes.AESCipher(key=key) encrypted_token = open(filename, 'r').read() token = cipher.decrypt(encrypted_token) return token