def __init__(self): self.DEFAULTNAME = "SCC.key" self.InitKey = "\x00" * 32 self.IV = "\x00" * 16 self.Encryptor = pyaes.AESModeOfOperationOFB(self.InitKey, iv=self.IV) self.Decryptor = pyaes.AESModeOfOperationOFB(self.InitKey, iv=self.IV) self.IK()
def foo(): #for i in range(1000000): #print(i) global mode global operation_mode global file_path global folder_path global key_path file_text = view.findChild(QObject, "textField") file_path = file_text.property("text") folder_text = view.findChild(QObject, "savePathField") folder_path = folder_text.property("text") key_text = view.findChild(QObject, "keyField") key_path = key_text.property("text") key_value = None with open(file_path[8:], mode='rb') as file: # b is important -> binary file_to_operate = file.read() with open(key_path[8:], mode='rb') as file: # b is important -> binary key_value = file.read() #key_value = os.urandom(32) if mode == "CTR" and operation_mode == "Encrypt": aes = pyaes.AESModeOfOperationCTR(key_value) ciphertext = aes.encrypt(file_to_operate) with open(folder_path[8:] + "/Encrypted_" + os.path.basename(file_path), mode='wb') as file: # b is important -> binary file.write(ciphertext) if mode == "CTR" and operation_mode == "Decrypt": aes = pyaes.AESModeOfOperationCTR(key_value) decrypted = aes.decrypt(file_to_operate) with open(folder_path[8:] + "/Decrypted_" + os.path.basename(file_path)[1:], mode='wb') as file: # b is important -> binary file.write(decrypted) if mode == "OFB" and operation_mode == "Encrypt": aes = pyaes.AESModeOfOperationOFB(key_value) ciphertext = aes.encrypt(file_to_operate) with open(folder_path[8:] + "/Encrypted_" + os.path.basename(file_path), mode='wb') as file: # b is important -> binary file.write(ciphertext) if mode == "OFB" and operation_mode == "Decrypt": aes = pyaes.AESModeOfOperationOFB(key_value) decrypted = aes.decrypt(file_to_operate) with open(folder_path[8:] + "/Decrypted_" + os.path.basename(file_path)[1:], mode='wb') as file: # b is important -> binary file.write(decrypted) print(file_path, folder_path, key_path)
def DecryptFile(self, Path): dc = pyaes.AESModeOfOperationOFB(self.Key, iv=self.iv) processed_size = 0 osz = os.path.getsize(Path) - 64 sh5 = hashlib.sha512() with open(Path, "rb") as fp: sha512digest = fp.read(64) with open("%s" % Path[:1 + (-len(".eca"))], "wb") as fpb: while True: tmp = fp.read(self.BUFFER) if (not tmp): break processed_size += len(tmp) print "Decrypting%s\t%s [%s%s] %s%.3f\t\r" % ( "." * (3 - (processed_size % 3)), os.path.basename(Path), "#" * int(20 * processed_size / osz), " " * (20 - int(20 * processed_size / osz)), "%", 100.0 * processed_size / osz), d_data = dc.decrypt(tmp) sh5.update(d_data) fpb.write(d_data) fpb.close() print "Checking... %s%s\r\n" % ("%s" % Path[:1 + (-len(".eca"))], " " * 100), if (sh5.digest() != sha512digest): os.remove("%s" % Path[:1 + (-len(".eca"))]) print "Failed Decrypting on %s probably key error%s\r\n" % ( "%s" % Path[:1 + (-len(".eca"))], " " * 100), else: print "Decrypted %s to %s%s\r\n" % ( Path, "%s" % Path[:1 + (-len(".eca"))], " " * 100),
def decrypt(self, ciphertext, iv, key, algo="aes-256-cbc"): cipher_type = self._get_algo_cipher_type(algo) if cipher_type == "cbc": cipher = pyaes.AESModeOfOperationCBC(key, iv=iv) elif cipher_type == "ctr": # The IV is actually a counter, not an IV but it does almost the # same. Notice: pyaes always uses 1 as initial counter! Make sure # not to call pyaes directly. # We kinda do two conversions here: from byte array to int here, and # from int to byte array in pyaes internals. It's possible to fix that # but I didn't notice any performance changes so I'm keeping clean code. iv_int = 0 for byte in iv: iv_int = (iv_int * 256) + byte counter = pyaes.Counter(iv_int) cipher = pyaes.AESModeOfOperationCTR(key, counter=counter) elif cipher_type == "cfb": # Change segment size from default 8 bytes to 16 bytes for OpenSSL # compatibility cipher = pyaes.AESModeOfOperationCFB(key, iv, segment_size=16) elif cipher_type == "ofb": cipher = pyaes.AESModeOfOperationOFB(key, iv) decrypter = pyaes.Decrypter(cipher) data = decrypter.feed(ciphertext) data += decrypter.feed() return data
def EncryptFile(self, Path): global arp ec = pyaes.AESModeOfOperationOFB(self.Key, iv=self.iv) processed_size = 0 dgs = SHA512fd(Path) with open(Path, "rb") as fp: with open("%s.eca" % (Path), "wb") as fpb: fpb.write(dgs) osz = os.path.getsize(Path) while True: tmp = fp.read(self.BUFFER) if (not tmp): break processed_size += len(tmp) print "Encrypting%s\t%s [%s%s] %s%.3f\t\r" % ( "." * (3 - (processed_size % 3)), os.path.basename(Path), "#" * int(20 * processed_size / osz), " " * (20 - int(20 * processed_size / osz)), "%", 100.0 * processed_size / osz), e_data = ec.encrypt(tmp) fpb.write(e_data) print "Encrypted %s to %s%s\r\n" % (Path, "%s%s" % (Path, ".eca"), " " * 100), if (self.urandom): if (arp.output): filename = self.SaveKey(arp.output) else: filename = self.SaveKey("key") print "Key saved as %s" % (filename)
def chooseMode(mode, key): if (mode == "CBC"): _mode = pyaes.AESModeOfOperationCBC(key) elif (mode == "OFB"): _mode = pyaes.AESModeOfOperationOFB(key) elif (mode == "CTR"): _mode = pyaes.AESModeOfOperationCTR(key) return _mode
def AES_new(key, iv=None): """ Returns an AES cipher object and random IV if None specified """ if iv is None: iv = fast_urandom16() # return AES.new(key, AES.MODE_CBC, IV), IV # Util.aes = pyaes.AESModeOfOperationCBC(key, iv = iv) # plaintext = "TextMustBe16Byte" # ciphertext = aes.encrypt(plaintext) return AES.AESModeOfOperationOFB(key, iv=iv), iv
def decrypt(data) -> bytes: if not is_wc24_keys_available(): raise Exception("RSA-AES keys not initialized. Can't decrypt data.") if get_uint32(data, 0x00) != WC24_MAGIC: raise Exception("Error: No WC24 data given. Can't extract U8 data.") iv = get_bytes(data, INIT_VECTOR_OFFSET, INIT_VECTOR_SIZE) aes = pyaes.AESModeOfOperationOFB(AES_KEY, iv=iv) return aes.decrypt(data[DATA_OFFSET:])
def encode(self): details = raw_input("Please enter account info: ").lower() username = raw_input("Enter username that will be encoded: ") message = raw_input("Enter password that will be encoded: ") key = raw_input("Enter a 16 characters encryption key: ") try: aes = pyaes.AESModeOfOperationOFB(key) encoded_password = aes.encrypt(message) data = details + ":" + username + ":" + encoded_password self.write_report(data, self.filename) except ValueError: print "ERROR: Key must have 16 characters"
def conn(): s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) ip = socket.gethostbyname(socket.gethostname()) print(ip) port = 56568 address = (ip, port) s.bind(address) s.listen(1) print("Started Listening on ", ip, ':', port) client, addr = s.accept() print("Got a connection from", addr[0], ':', addr[1]) client.send(key_192) key_192r = client.recv(1024) enaes = pyaes.AESModeOfOperationOFB(key_192) deaes = pyaes.AESModeOfOperationOFB(key_192r) while True: msg = input("Text :") enmsg = enaes.encrypt(msg) print('encrypted :', enmsg) if "bye" in msg: print("Connection ended") client.send(enmsg) client.close() break else: client.send(enmsg) enrec = client.recv(1024) print('encrypted :', enrec) derec = deaes.decrypt(enrec).decode('utf-8') print("Alice :", derec) if "bye" in derec: print("Connection ended") client.close() break
def decode(self): details = raw_input("Please enter account info: ").lower() key = raw_input("Enter 16 bit encryption key: ") try: password = self.return_data(details)[1] username = self.return_data(details)[0] except IOError: print "ERROR: File does not exist or you don't have read permission" else: try: aes = pyaes.AESModeOfOperationOFB(key) decoded = aes.decrypt(password) print "Username for the %s account is %s with password: "******"ERROR: Key must have 16 characters"
def encrypt(data) -> bytes: if not is_wc24_keys_available(): raise Exception("RSA-AES keys not initialized. Can't encrypt data.") privkey = rsa.PrivateKey.load_pkcs1(RSA_KEY, "PEM") signature = rsa.sign(data, privkey, "SHA-1") iv = os.urandom(INIT_VECTOR_SIZE) aes = pyaes.AESModeOfOperationOFB(AES_KEY, iv=iv) encrypted = aes.encrypt(data) outdata = bytearray(WC24_HEADER_SIZE + INIT_VECTOR_SIZE + SIGNATURE_SIZE + len(encrypted)) put_uint32(outdata, 0x00, WC24_MAGIC) put_uint32(outdata, 0x04, 1) put_uint8(outdata, 0x0C, 1) put_bytes(outdata, INIT_VECTOR_OFFSET, iv) put_bytes(outdata, SIGNATURE_OFFSET, signature) put_bytes(outdata, DATA_OFFSET, encrypted) return bytes(outdata)
def beautify_message(self, msg): text = msg if len(msg) > 3: if self.isBytes(msg): msg = msg.decode(ENCODING).split(';') text = msg[1] + ' >> [' + msg[2] + '] ' # If message encrypted if RSA_KEY: aes = pyaes.AESModeOfOperationOFB(RSA_KEY) #base64 decode decoded_msg = base64.b64decode(msg[3]) # Decrypt! decryptedMsg = aes.decrypt(decoded_msg).decode(ENCODING) text += decryptedMsg else: text += msg[3] # If message received # if (msg[1] != self.login): text += '\r\n' return text
def send_entry_event(self, event): """Send message from entry field to target""" global message text = self.entry.get(1.0, tk.END) if text != '\n': if RSA_KEY: # Encrypt! aes = pyaes.AESModeOfOperationOFB(RSA_KEY) # Message encrypt in bytes msg = aes.encrypt(text[:-1]) # Base64 encode message to send to server my_msg = base64.b64encode(msg) message = bytes('msg;' + self.login + ';' + self.target + ';', ENCODING) + my_msg else: message = 'msg;' + self.login + ';' + self.target + ';' + text message = message.encode(ENCODING) self.gui.send_message(message) self.entry.mark_set(tk.INSERT, 1.0) self.entry.delete(1.0, tk.END) self.entry.focus_set() else: messagebox.showinfo('Warning', 'You must enter non-empty message') with self.lock: self.messages_list.configure(state='normal') if text != '\n': if self.isBytes(message): text = self.beautify_message(message) else: text = self.beautify_message(message.split(';')) self.messages_list.insert(tk.END, text) self.messages_list.configure(state='disabled') self.messages_list.see(tk.END) return 'break'
def rebuildDecryptor(self): self.Decryptor = pyaes.AESModeOfOperationOFB(self.InitKey, iv=self.IV)
import pyaes key = 'ds,dfh/khsiaj94i*&%vfker/{27&^$#@Xx#b0)' message = 'hello there,how you doing?' cipher = pyaes.AESModeOfOperationOFB(key) key = key.encode('utf-8') def pad(s): return s + ((16 - len(s) % 16) * '{') def encrypt(plaintext): global cipher return cipher.encrypt(pad(plaintext)) def decrypt(ciphertext): global cipher dec = cipher.decrypt(ciphertext).decode('utf-8') l = dec.count('{') return dec[:len(dec) - 1] print('Message :', message) encrypted = encrypt(message) decrypted = decrypt(encrypted) print("Encryted :", encrypted) print("decrpted :", decrypted)
def execution(keySelect): password = str(input("Ingrese la clave: ")).encode('utf-8') # Unicode-objects must be encoded before hashing hashed = hashlib.sha256(password).digest() # Se utiliza un algoritmo hash para manejar la clave el cual retorna una cadena de caracteres de 32-bytes iv = "InitializationVe" # Para el modo de operacion OFB, se necesita un vector aleatoreo de inicializacion de 16-bytes if keySelect == 1: # Segun la preferencia del usuario, se modifica el tamaƱo de la llave a utilizar key = hashed[:16] # Del hash, se seleccionan 128 bits elif keySelect == 2: key = hashed[:24] # Del hash, se seleccionan 192 bits else: key = hashed # Del hash, se seleccionan 256 bits aes = pyaes.AESModeOfOperationOFB(key, iv = iv) # Se inicializa el cifrado mediante el modo de operacion "Output Feedback"(OFB), puesto que este permite ingresar un texto plano de cualquier longitud, sin requerir de padding ruta = input("Ingrese la ruta, nombre y extension de la imagen: ") image = open(ruta, 'rb') # Se crea un archivo de modo lectura que contiene la imagen image_read = image.read() # Se lee la imagen convirtiendola en su representacion en bytes print("Cifrando imagen, espere por favor") image_encrypt = aes.encrypt(image_read) if image_read != image_encrypt: print("Imagen cifrada!!!") else: print("Error cifrando") sys.exit() input("Codificando en Base64, presione Enter para continuar") image_base64en = base64.b64encode(image_encrypt) if image_encrypt != image_base64en: print("Imagen codificada en Base64: \n\n", image_base64en, "\n") else: print("Error codificando en base64 la imagen cifrada") sys.exit() input("Decodificando Imagen en Base64, presione Enter para continuar") image_base64dec = base64.b64decode(image_base64en) if image_base64en != image_base64dec: print("Imagen decodificada desde Base64") else: print("Error decodificando la imagen cifrada") sys.exit() #aes = pyaes.AESModeOfOperationCBC(key, iv = iv) # El modo de operacion CBC mantiene el estado, por lo cual se requiere crear una nueva instacion para descifrar aes = pyaes.AESModeOfOperationOFB(key, iv = iv) print("Descifrando imagen, espere por favor") image_decrypt = aes.decrypt(image_base64dec) if image_decrypt == image_read: print("Imagen descifrada!!!") else: print("Error descifradando") sys.exit() ruta = input("Ingrese la ruta, nombre y extension donde desea que se guarde la imagen: ") image_result = open(ruta, 'wb') # Se crea archivo de modo escritura que contendra la imagen resultante image_result.write(image_decrypt) # Se guarda la informacion de la imagen desencriptada print("Imagen generada en la ruta especificada, ya puede terminar el programa.\n")
def rDecrypt(self, data): Decryptor = pyaes.AESModeOfOperationOFB(self.InitKey, iv=self.IV) return Decryptor.decrypt(data)
print(result) print(keys_list) #get_key('2') # A 256 bit (32 byte) key key = "This_key_for_demo_purposes_only!" # Convert str to byte object key = key.encode('utf-8') # For some modes of operation we need a random initialization vector # of 16 bytes iv = "InitializationVe" iv = iv.encode('utf-8') aes = pyaes.AESModeOfOperationOFB(key, iv=iv) plaintext = "Text may be any length you wish, no padding is required" ciphertext = aes.encrypt(plaintext) #repr(ciphertext) logging.info(ciphertext) print(ciphertext) # The counter mode of operation maintains state, so decryption requires # a new instance be created #aes = pyaes.AESModeOfOperationCTR(key) #aes = pyaes.AESModeOfOperationCFB(key, iv = iv, segment_size = 8) aes = pyaes.AESModeOfOperationOFB(key, iv=iv) decrypted = aes.decrypt(ciphertext) logging.info("Dedecrypted Message: %s", decrypted) # True
def rEncrypt(self, data): Encryptor = pyaes.AESModeOfOperationOFB(self.InitKey, iv=self.IV) return Encryptor.encrypt(data)