def NewUTXOTransaction(self, source, dest, amount, fso): #新建一个交易 inputs = list() outputs = list() acc, validOutPuts = fso dest = Crypt.AtoPHK(dest) if acc < amount: Log.Panic("ERROR: Not enough funds!") return None else: #创建一个输入列表 for txid in validOutPuts.keys(): outs = validOutPuts[txid] for out in outs: input = TranInput(txid, out, None, source) inputs.append(input) #创建一个输出列表 #只能有两个输出 outputs.append(TranOutput(amount, dest)) #转给对方 if acc > amount: outputs.append( TranOutput(acc - amount, Crypt.getHashPubKey(source))) #找零 tx = Transaction(None, inputs, outputs) tx.SetID() return tx
def __init__(self): try: self.pubkey = open('.pubkey', 'r').read().encode() self.hashed_pubkey = Crypt.sha256(self.pubkey) self.privkey = open('.privkey', 'r').read().encode() except IOError: self.pubkey, self.privkey = Crypt.generate_RSA() Crypt.write_RSA(self.pubkey, self.privkey) self.hashed_pubkey = Crypt.sha256(self.pubkey)
def send(self, msg, is_file=False): data, newpubkey, newprivkey = Crypt.encrypt(self.pubkey, self.privkey, self.get_receiver(), msg, is_file) r = requests.post(AnonDoge.server + '/api/msgs', data=data, verify=False) Crypt.write_RSA(newpubkey, newprivkey) self.pubkey = newpubkey self.hashed_pubkey = Crypt.sha256(newpubkey) self.privkey = newprivkey return r.json()
def recieveAll(self, buffsize): retdata = "" cry = Crypt() data = bytearray() packetsize = self.getSocket().recv(4) while sys.getsizeof(data) < int.from_bytes(packetsize, 'little'): read_sockets, write_sockets, error_sockets = select.select( [self.getSocket()], [], [], 4) if self.getSocket() in read_sockets: data.extend(self.getSocket().recv(self.getBUFFER_SIZE())) else: return "timeout" retdata = cry.decryptit(bytes(data)).decode() return retdata
def transfer(conn): hostcon.settimeout(.1) extconn.settimeout(.1) while True: try: pack = hostconn.recv(65356) decpack = Crypt.decrypt(pack, "server") except socket.timeout: pass try: pack = hostconn.recv(65356) decpack = Crypt.decrypt(pack, "client") except socket.timeout: pass
def register(usr, passwd, mail): """ Cette fonction permet de créer un compte sur le serveur de messagerie. La fonction prend 3 paramètres : - usr : le nom d'utilisateur souhaité - passwd : le mot de passe du compte - mail : l'adresse mail de l'utilisateur """ sha = hashlib.sha512((usr + " : " + passwd).encode()).hexdigest() key = RSA.generate(2048) public_key = key.publickey() key_to_send = crpt.crypt_message(key.exportKey(format='PEM'), passwd) acces = connection_server.ask_for_ticket() connection_server.requests[acces] = "REGISTER\\" + "\\".join([ usr, sha, mail, key_to_send, "\\".join( public_key.exportKey().split("\n")) ]) connection_server.ask_for_send(acces) msg_from_server = attendre_reponse(acces) if msg_from_server == "REGISTER\\OK": # --- Avertir l'utilisateur et lui proposer de se connecter --- pass elif msg_from_server == "REGISTER\\ERROR": # --- Avertir l'utilisateur et quitter l'application --- pass elif msg_from_server == "REGISTER\\USERNAME_ALREADY_EXISTS": # --- Avertir l'utilisateur que ce nom d'utilisateur est deja pris et lui proposer de recommencer avec les autres cases préremplies --- pass elif msg_from_server == "REGISTER\\EMAIL_ALREADY_USED": # --- Avertir l'utilisateur que ce mail est deja utilise et lui proposer de recommencer avec les autres cases préremplies --- pass
def handleClient(self, client): try: # Send Server Message client.send((self.serverMessage[:1024])) E = Crypt.Crypt() while True: data = client.recv(1024) if (data == "Online?"): response = "[*] Users Online\n" for clients in self.connections: response += "\t" + clients.getpeername()[0] + "\n" message = E.Encrypt(response, self.key) client.send(message) elif data: threading.Thread(target=self.dispense, args=(data, )).start() else: pass except socket.error: # Remove Clients From List If An Error Occurs self.connections.remove(client) client.close() except Exception, e: #print e pass
def FindSpendableOutputs(self,public_key,amount): """ unspentOutputs:没有花费的输出 unspentTXs:没有花费的交易 accumulated:累计个数 """ unspentOutputs = dict() u = UTXOSet.UTXOSet() unspentTXs = u.getUXTOs() accumulated = 0 amount = int(amount) pubKeyHash = Crypt.getHashPubKey(public_key) for key,tx in unspentTXs.items(): tx = PickleStr.toObj(tx.decode("utf-8")) txid = tx.ID unspentOutputs[txid] = [] for outIdx in range(len(tx.Vout)): out = tx.Vout[outIdx] if out.IsLockedWithKey(pubKeyHash) and accumulated < amount: accumulated += out.Value unspentOutputs[txid].append(outIdx) tx.Vout.pop(outIdx) self.Keys.put(key) if accumulated >= amount: return accumulated, unspentOutputs
def __init__(self): ''' @summary: Constructor ''' self.__config = self.__load_config() self.encrypted_file_list = os.path.join(os.environ['APPDATA'], "encrypted_files.txt") # Init Crypt Lib self.Crypt = Crypt.SymmetricCrypto() # FIRST RUN # Encrypt! if not os.path.isfile(self.encrypted_file_list): self.Crypt.init_keys() file_list = self.find_files() # Start encryption self.encrypt_files(file_list) # If no files were encrypted. do nothing if not os.path.isfile(self.encrypted_file_list): return # Present GUI self.start_gui() # ALREADY ENCRYPTED # Present menu elif os.path.isfile(self.encrypted_file_list): self.start_gui()
def backup(): """ Cette fonction crée une archive chiffrée du dossier personnel de l'utilisateur et l'envoie au serveur. Elle est utile pour permettre au client de se déconnecter de l'application sans pour autant perdre ses données. On pourrait également appeler cette fonction à intervalle de temps régulier afin d'assurer les donées du client. """ global username global mdp zipdirectory("backup.zip", username) backup_crpt = crpt.crypt("backup.zip", mdp) bkp_file = open(backup_crpt, 'rb') msg_to_send = "BACKUP\\" + binascii.hexlify(bkp_file.read()) bkp_file.close() # --- AFFICHER UNE ANIMATION D'ATTENTE ET INFORMER : SAUVEGARDE DES DONNEES EN COURS --- ticket = connection_server.ask_for_ticket() connection_server.requests[ticket] = msg_to_send connection_server.ask_for_send(ticket) msg_from_server = attendre_reponse(ticket) if msg_from_server == "BACKUP\\OK": # --- AFFICHER A L'ECRAN : ENVOI DE LA SAUVEGARDE REUSSI --- os.remove(backup_crpt) with open("bkp_sended.txt", "a") as f: f.write(msg_to_send) return backup_crpt else: # --- AVERTIR L'UTILISATEUR AVEC UNE POPUP ET FERMER L'APPLICATION --- return "ERROR"
def get_password(self, is_force_input): password = '' # パスワード入力を強制しない場合は記憶済パスワードを探す if is_force_input == False: # 記憶した暗号化済みパスワードと秘密鍵を読み出し、複合して返す try: with open('password.dat', 'rb') as f: crypted_str = pickle.load(f) with open('key.dat', 'rb') as f: key = pickle.load(f) decrypt_result = Crypt.Decrypt(crypted_str, key) return decrypt_result # そもそもファイルがなければユーザ入力 except FileNotFoundError: pass # ウィジェット作成 self.__create_widgets() #GUIを表示 self.mainloop() #入力されたパスワードを変数に保存 password = self.Password # 記憶するにチェックしていれば記憶 if self.IsRememberPassword.get(): self.save(password) return password
def __init__(self): PrivateKey, PrintPubey, PublicKey, PublicHashKey, Address = Crypt.getKeypair( ) self.PrivateKey = PrivateKey self.PrintPubkey = PrintPubey self.PublicKey = PublicKey self.PublicHashKey = PublicHashKey self.Address = Address
def Sign(self, privkey, prevTXs): """ :param privkey:私钥信息 :param prevTXs:交易字典 描述信息:对部分信息进行签名 """ if self.iscoinbase: return txCopy = self.TrimmedCopy() for inID in range(len(txCopy.Vin)): vin = txCopy.Vin[inID] prevTX = prevTXs[vin.Txid] txCopy.Vin[inID].Signature = None txCopy.Vin[inID].PubKey = prevTX.Vout[vin.Vout].PubKeyHash txCopy.SetID() txCopy.Vin[inID].PubKey = None signature = Crypt.getSignInfo(Crypt.getSignKey(privkey), txCopy.ID.encode("utf-8")) self.Vin[inID].Signature = signature
def add(self, entry): """ Add an ENTRY to the CArchive. ENTRY must have: entry[0] is name (under which it will be saved). entry[1] is fullpathname of the file. entry[2] is a flag for it's storage format (0==uncompressed, 1==compressed) entry[3] is the entry's type code. Version 5: If the type code is 'o': entry[0] is the runtime option eg: v (meaning verbose imports) u (menaing unbuffered) W arg (warning option arg) s (meaning do site.py processing. """ (nm, pathnm, flag, typcd) = entry[:4] # FIXME Could we make the version 5 the default one? # Version 5 - allow type 'o' = runtime option. try: if typcd in ('o', 'd'): s = '' flag = 0 elif typcd == 's': # If it's a source code file, add \0 terminator as it will be # executed as-is by the bootloader. s = open(pathnm, 'rU').read() s = s + '\n\0' else: s = open(pathnm, 'rb').read() except IOError: print "Cannot find ('%s', '%s', %s, '%s')" % (nm, pathnm, flag, typcd) raise ulen = len(s) assert flag in range(3) if flag == 1 or flag == 2: s = zlib.compress(s, self.LEVEL) if flag == 2: global AES import AES import Crypt key = Crypt.gen_random_key(32) # Note: keep this in sync with bootloader's code s = key + AES.new(key, AES.MODE_CFB, "\0" * AES.block_size).encrypt(s) dlen = len(s) where = self.lib.tell() if typcd == 'm': if pathnm.find('.__init__.py') > -1: typcd = 'M' self.toc.add(where, dlen, ulen, flag, typcd, nm) self.lib.write(s)
def SendLoginPacket(self, rndK): c = Crypt.Crypt() recv = self.Sock.Send("<msg t='sys'><body action='login' r='0'><login z='w1'><nick><![CDATA[" + self.user.Username + "]]></nick><pword><![CDATA[" + c.GetLoginHash(self.user.Password, rndK) + "]]></pword></login></body></msg>") packetElements = recv.split('%') userData = packetElements[4].split('|') self.user.ID = userData[0] self.user.Userstring = packetElements[4] self.user.ConfirmationHash = packetElements[5] self.user.FriendsKey = packetElements[6] self.user.SWID = userData[1] self.user.LoginKey = userData[3]
def register(): username = raw_input("Nom d'utilisateur : ") while not username: print "Le nom d'utilisateur ne doit pas etre vide... Veuillez réessayer !" username = raw_input("Nom d'utilisateur : ") passwd = "" passwd_conf = "a" while not passwd == passwd_conf: passwd = getpass.getpass("Mot de passe : ") while not passwd: print "Le mot de passe ne doit pas etre vide... Veuillez réessayer !" passwd = getpass.getpass("Mot de passe : ") passwd_conf = getpass.getpass("Confirmation du mot de passe : ") while not passwd_conf: print "Le mot de passe ne doit pas etre vide... Veuillez réessayer !" passwd_conf = getpass.getpass("Confirmation du mot de passe : ") if not passwd == passwd_conf: print "Les mots de passe ne correspondent pas... Veuillez réessayer !" email = raw_input("Email : ") while not email: print "L'email ne doit pas etre vide... Veuillez réessayer !" email = raw_input("Email : ") sha = hashlib.sha512((username + " : " + passwd).encode()).hexdigest() print "Creation de vos cles privees/publiques en cours (peut prendre quelques instants)" key = RSA.generate(4096) public_key = key.publickey() key_to_send = crpt.crypt_message(key.exportKey(format='PEM'), passwd) """print "len(public_key) = "+str(len(public_key.exportKey())) print "len(private) = "+str(len(key.exportKey())) print "len crypted = "+str(len(key_to_send)) print 'len both = '+str(len(public_key.exportKey())+len(key_to_send)) print 'len esle = '+str(len("REGISTER\\"+"\\".join([username, sha, email]))) print "len soustract = "+str(len("REGISTER\\"+"\\".join([username, sha, email, key_to_send, "\\".join(public_key.exportKey().split("\n"))])) - len("REGISTER\\"+"\\".join([username, sha, email])) - 2*len("\\")) msg_to_send = "REGISTER\\"+"\\".join([username, sha, email, key_to_send, "\\".join(public_key.exportKey().split("\n"))]) print "Envoye : "+msg_to_send print "len envoye : "+str(len(msg_to_send.split("\\")))""" connection_server.send(("REGISTER\\" + "\\".join([ username, sha, email, key_to_send, "\\".join( public_key.exportKey().split("\n")) ]) + chr(23))) msg_recu = attendre_reponse() if msg_recu == "REGISTER\\OK": print "Enregistement reussi !" elif msg_recu == "REGISTER\\ERROR": print "Something went wrong... Please try again !" sys.exit() elif msg_recu == "REGISTER\\USERNAME_ALREADY_EXISTS": print "Ce nom d'utilisateur est déja pris... Veuillez réessayer !" register() elif msg_recu == "REGISTER\\EMAIL_ALREADY_USED": print "Cette adresse mail à deja été utilisée... Veuillez réessayer !" register()
def creatblock(self): """ 创建创世区块 :param dest:自己的地址 :return: """ dest = Crypt.AtoPHK(Wallet().Address) tx = self.NewCoinbaseTX(dest) # 创世区块 block = Block(tx.getresult()) self.db.put(block.Headers.gethash(), str(block)) self.db.put("l", block.Headers.gethash()) block.getstring()
def save(self, password): # 平文のパスワードを暗号化 encrypt_result = Crypt.Encrypt(password) # 暗号化したパスワード crypted_str = encrypt_result[0] # 秘密鍵 key = encrypt_result[1] with open('password.dat', 'wb') as f: pickle.dump(crypted_str, f) with open('key.dat', 'wb') as f: pickle.dump(key, f)
def __init__(self): ''' @summary: Constructor ''' self.__config = self.__load_config() self.encrypted_file_list = os.path.join(os.environ['APPDATA'], "encrypted_files.txt") # Init Crypt Lib self.Crypt = Crypt.SymmetricCrypto() # FIRST RUN # Encrypt! if not os.path.isfile(self.encrypted_file_list): # Disable Task Manager if self.__config["disable_task_manager"]: self.task_manager = TaskManager() try: self.task_manager.disable() except WindowsError: pass # Add to startup programs # TODO Test if self.__config["open_gui_on_login"]: self.__add_to_startup_programs() # Find files and initialise keys self.Crypt.init_keys() file_list = self.find_files() # Start encryption self.encrypt_files(file_list) # If no files were encrypted. cleanup and return if self.__no_files_were_encrypted(): # TODO Test self.cleanup() return # Delete Shadow Copies if "delete_shadow_copies" in self.__config: self.__delete_shadow_files() # Open GUI self.start_gui() # ALREADY ENCRYPTED - Open GUI elif os.path.isfile(self.encrypted_file_list): self.start_gui()
def init(): global DEPLOY_PRIVATEKEY, DEPLOYER # The private key for signing is expected to be found in user settings settings = ZeroFrame.userGetSettings(wait=True) if "deploy_privatekey" in settings: DEPLOY_PRIVATEKEY = settings["deploy_privatekey"] DEPLOYER = Crypt.privatekeyToAddress(DEPLOY_PRIVATEKEY) signers = ZeroFrame.fileRules("data/bots/content.json", wait=True)["signers"] if DEPLOYER not in signers: print(f"[zIRC] Invalid private key. Expected to match any public key of: {signers}") return start()
def broadcastToAll(self): try: E = Crypt.Crypt() print "\nType messages below to be broadcasted as the server.\n----------------------------------------------------\n" while True: message = raw_input("") message = "<SERVER> " + message # Encrypt Message message = E.Encrypt(message, self.key) # Send To All Connected Clients self.dispense(message) except Exception, e: print e pass
def get_password(self, is_force_input): password = '' # パスワード入力を強制しない場合は記憶済パスワードを探す if is_force_input == False: ret, user_path = OsDepend.get_user_path() if ret != STANDARD_RETURN.OK: return STANDARD_RETURN.NOT_OK, '' # 記憶した暗号化済みパスワードと秘密鍵を読み出し、複合して返す self.external_file = ExternalFile.ExternalFile(user_path + EXTERNAL_FILE.PATH) result_pass = self.external_file.get('password') result_key = self.external_file.get('secret_key') if result_pass[0] == 0 and result_key[0] == 0: crypted_str = result_pass[1] key = result_key[1] # 16進文字列に変換して保存しているので元のバイナリに戻す crypted_str = bytes.fromhex(crypted_str) key = bytes.fromhex(key) decrypt_result = Crypt.Decrypt(crypted_str, key) return STANDARD_RETURN.OK, decrypt_result # 読み出しできなければパスワード入力させる else: pass #tkinterのインスタンスでありメインウィンドウ self.master = Tk.Tk() #BookeanVar()はTrueかFalseの2択の特殊な変数の型 #パスワードを記憶するかどうかのチェックボックス用 self.IsRememberPassword = Tk.BooleanVar() #Python3ではJavaと違って継承元のコンストラクタを暗黙的に呼び出さないので、明示的に呼び出す必要がある super().__init__(self.master) # ウィジェット作成 self.__create_widgets() #閉じるボタンが押されたときの処理 self.master.protocol("WM_DELETE_WINDOW", self.__on_closing) #GUIを表示 self.mainloop() #入力されたパスワードを変数に保存 if self.result == STANDARD_RETURN.OK: password = self.Password # 記憶するにチェックしてOKが押されていれば記憶 if self.IsRememberPassword.get(): self.save(password) return self.result, password
def fetch(self): r = requests.get(AnonDoge.server + '/api/msgs', params = { 'hashed_pubkey': self.hashed_pubkey }, verify=False) msgs = r.json()['msgs'] arr = list() for msg in msgs: try: msg, newpubkey = Crypt.decrypt(self.privkey, msg) arr.append(msg) self.set_receiver(newpubkey) except: return 'Incorrect decryption' return arr
def save(self, password): # 平文のパスワードを暗号化 encrypt_result = Crypt.Encrypt(password) # 暗号化したパスワード crypted_str = encrypt_result[0] # 秘密鍵 key = encrypt_result[1] # それぞれテキストで保存できるように16進文字列に変換しておく crypted_str = crypted_str.hex() key = key.hex() ret, user_path = OsDepend.get_user_path() if ret == STANDARD_RETURN.OK: self.external_file = ExternalFile.ExternalFile(user_path + EXTERNAL_FILE.PATH) self.external_file.save('password', crypted_str) self.external_file.save('secret_key', key)
def RecieveData( self, s, ): try: D = Crypt.Crypt() key = self.key # Get Server Message (Unencrypted) print s.recv(self.bufferLength) while True: recieved = s.recv(self.bufferLength) print D.Decrypt(recieved, key) except Exception, e: #print e pass
def Verify(self, prevTXs): """ :param prevTXs:交易信息 :return: 验证结果 """ txCopy = self.TrimmedCopy() for inID in range(len(self.Vin)): vin = self.Vin[inID] prevTX = prevTXs[vin.Txid] txCopy.Vin[inID].Signature = None txCopy.Vin[inID].PubKey = prevTX.Vout[vin.Vout].PubKeyHash txCopy.SetID() txCopy.Vin[inID].PubKey = None result = Crypt.getVerifyInfo(vin.PubKey, vin.Signature, txCopy.ID.encode("utf-8")) if not result: return False return True
def init(): global DEPLOY_PRIVATEKEY, DEPLOYER # The private key for signing is expected to be found in user settings settings = ZeroFrame.userGetSettings(wait=True) if "deploy_privatekey" in settings: DEPLOY_PRIVATEKEY = settings["deploy_privatekey"] DEPLOYER = Crypt.privatekeyToAddress(DEPLOY_PRIVATEKEY) signers = ZeroFrame.fileRules("data/bots/content.json", wait=True)["signers"] if DEPLOYER not in signers: print( f"[zIRC] Invalid private key. Expected to match any public key of: {signers}" ) return start()
def backup(): global username global mdp zipdirectory("backup.zip", username) backup_crpt = crpt.crypt("backup.zip", mdp) bkp_file = open(backup_crpt, 'rb') msg_to_send = "BACKUP\\" + binascii.hexlify(bkp_file.read()) bkp_file.close() print "Envoi de la sauvegarde..." connection_server.send(msg_to_send + chr(23)) msg_from_server = attendre_reponse() if msg_from_server == "BACKUP\\OK": print "Envoye ! " os.remove(backup_crpt) with open("bkp_sended.txt", "a") as f: f.write(msg_to_send) return backup_crpt else: print "Une erreur est survenue lors de l'envoi de la sauvegarde. Vous n'allez pas être deconnecte." return "ERROR"
def SendData( self, s, ): try: E = Crypt.Crypt() key = self.key nick = "<Default> " while True: message = raw_input("") if (message.find("/nick") >= 0): # Change nickname new_nick = message.replace("/nick ", "") if (new_nick.lower == "server"): print "[--] Cannot Change Nick To Nick Of Server" else: nick = "<" + new_nick + "> " print "[+] Nickname Changed To: %s" % nick elif (message.find("/clear") >= 0): # Clears The Screen print '\n' * 100 elif (message.find("/help") >= 0): # Display Help Message print("\n\t\t<--- HELP --->\n" + "/nick [new nickname]\tChange Nick Name\n" + "/clear\t\t\tClear The Screen\n" + "/help\t\t\tShow This Message\n" + "/online\t\t\tShow Who Is Online At The Moment\n") elif (message.find("/online") >= 0): # Ask server who is online # (Not Encrypted, but Recieved Encrypted) s.send("Online?") else: # Encrypt And Send Data data = E.Encrypt((nick + message), key) s.send(data) except Exception, e: #print e pass
def __init__(self): ''' @summary: Constructor ''' self.encrypted_file_list = os.path.join(os.environ['APPDATA'], "encrypted_files.txt") # Init Crypt Lib self.Crypt = Crypt.SymmetricCrypto() # FIRST RUN # Encrypt! if not os.path.isfile(self.encrypted_file_list): self.Crypt.init_keys() file_list = self.find_files() # Start encryption # TODO Restore this self.encrypt_files(file_list) # Present GUI self.start_gui() # ALREADY ENCRYPTED # Present menu elif os.path.isfile(self.encrypted_file_list): self.start_gui()
except ValueError: print("Please enter only Numbers between 0 and 4") continue if userIn == 1: keys = Keygen.keygen() print("*** Keypairs ***") print("- Private Key: (N={},e={})".format(keys.private.RSA, keys.private.exponent)) print("- Public Key: (N={},d={})".format(keys.public.RSA, keys.public.exponent)) elif userIn == 2 or userIn == 3: Key = RSAInputParser.InputParser(input("Please enter RSA-Key: ")) if userIn == 2: message = input("Please enter the plaintext message: ") encrypted = Crypt.encrypt(Key.N, Key.exp, message) print("Encrypted: {}".format(encrypted)) else: message = input("Please enter the encrypted message: ") decrypted = Crypt.decrypt(Key.N, Key.exp, message) print("Dcrypted: {}".format(decrypted)) elif userIn == 0: break print("Bye Bye")
def UseKey(self, pubKeyHash): lockingHash = Crypt.getHashPubKey(self.PubKey) return lockingHash == pubKeyHash
def envoyer_message(dest=None, conv_type=None): if not dest: connection_server.send(("GET\\friends" + chr(23))) msg_from_server = attendre_reponse() if msg_from_server == "GET\\friends\\REFUSED": print "Erreur lors de la récuperation de vos amis. Cela est probablement dut à une erreur dans votre connection. Solution proposee : rédemarer l'application et se reconnecter." else: msg_from_server = msg_from_server.split(", ") for x in msg_from_server: if x == " " or x == "": msg_from_server.remove(x) menu_text = "" menu_text += "\nVoici la liste de vos amis. Tapez leur numéro pour leur envoyer un message.\n" + colours[ "yellow"] + colours[ "reverse"] + "[ 0 ] Retour au menu principal\n" + colours[ "default"] rep_available = ["0", "G"] for x in range(len(msg_from_server)): menu_text += "[ " + str(x + 1) + " ] " + msg_from_server[x] + "\n" rep_available.append(str(x + 1)) if len(rep_available) == 2: menu_text += "Si tu n'as pas d'amis, prend un curly ;)\n" menu_text += colours[ "green"] + "[ + ]" + " Ajouter un ami.\n" + colours["default"] rep_available.append("+") if len(rep_available) > 3: menu_text += colours[ "red"] + "[ - ]" + " Supprimer un ami.\n" + colours[ "default"] rep_available.append("-") menu_text += colours[ "blue"] + "[ G ] Créer un nouveau groupe.\n" + colours[ "default"] menu_text += "\n" rep = verif_answer(menu_text, rep_available, "Non pris en charge... Réessayer.") if rep == "+": friend_to_add = raw_input( "Quel est le nom d'utilisateur de votre nouvel ami ? \nLaisser vide pour retourner au menu précédent. \n>>" ) if not len(friend_to_add) == 0: connection_server.send( ("ADD\\friend\\" + friend_to_add + chr(23))) msg_from_server = attendre_reponse() if msg_from_server == "ADD\\friend\\OK": print "Ami ajoute avec succes !" elif msg_from_server == "ADD\\friend\\404": print "Cet ami n'existe pas !" elif msg_from_server == "ADD\\friend\\REFUSED": print "Acces refuse !" elif msg_from_server == "ADD\\FRIEND\\REFUSED\\ADDING_OWN_USERNAME": print "Il est interdit de s'ajouter soi-meme en ami ;)" elif len(friend_to_add) == 0: envoyer_message() return 0 elif rep == "-": rep_available = [] menu_text = "" menu_text += "Tapez le numéro de l'ami qui n'en est plus un : \n" + colours[ "yellow"] + colours[ "reverse"] + "[ 0 ] Retour en arriere\n" + colours[ "default"] for x in range(len(msg_from_server)): menu_text += "[ " + str( x + 1) + " ] " + msg_from_server[x] + "\n" rep_available.append(str(x + 1)) rep_available.append("0") rep = verif_answer( menu_text, rep_available, "Valeur non prise en charge... Réessayez !") if rep == "0": envoyer_message() return 0 connection_server.send( ("REMOVE\\friend\\" + msg_from_server[int(rep) - 1] + chr(23))) msg_from_server = attendre_reponse() if msg_from_server == "REMOVE\\friend\\OK": print "Ami supprimé avec succès" elif msg_from_server == "REMOVE\\friend\\404": print "Cet ami ne fait pas parti des votres !" elif msg_from_server == "REMOVE\\friend\\REFUSED": print "Acces refuse !" elif rep == "0": afficher_menu() return 0 elif rep == "G": nom = raw_input( "Donnez un nom à ce nouveau groupe.\nLaissez vide pour annuler et revenir en arriere.\n>>" ) if len(nom) == 0: envoyer_message() return 0 else: friends_to_add = [] while True: menu_text = "Entrez le numéro de l'ami à ajouter au groupe.\n" + colours[ "yellow"] + colours[ "reverse"] + "[ 0 ] Annuler la création du groupe et retourner au menu précédent.\n" + colours[ "default"] rep_available = ["0"] if not len(friends_to_add) == 0: menu_text += colours[ "red"] + "[ - ] Retirer des amis déjà ajouté.\n" + colours[ "default"] rep_available.append("-") for x in range(len(msg_from_server)): if not msg_from_server[x] in friends_to_add: menu_text += "[ " + str( x + 1) + " ] " + msg_from_server[x] + "\n" rep_available.append(str(x + 1)) else: menu_text += colours[ "green"] + "[ + ] " + msg_from_server[ x] + "\n" + colours["default"] if len(friends_to_add) > 1: menu_text += "[ " + str( len(msg_from_server) + 1) + " ] Valider et créer le groupe.\n" rep_available.append(str(len(msg_from_server) + 1)) rep = verif_answer( menu_text, rep_available, "Valeur non pris en charge... Réessayer.") if rep == "0": envoyer_message() return 0 elif rep == "-": menu_text = "Entrez le numéro de l'ami qui ne doit pas être ajouté au groupe.\n" + colours[ "yellow"] + colours[ "reverse"] + "[ 0 ] Annuler et retourner au menu précédent.\n" + colours[ "default"] rep_available = ["0"] for x in range(len(friends_to_add)): menu_text += "[ " + str( x + 1) + " ] " + friends_to_add[x] + "\n" rep_available.append(str(x + 1)) rep = verif_answer( menu_text, rep_available, "Non pris en charge... Réessayer.") friends_to_add.pop(int(rep) - 1) elif rep == str(len(msg_from_server) + 1): key = r_pass.generate(256) friends_to_add.append(username) connection_server.send("START\\group\\" + nom + "\\" + key + "\\" + str(len(friends_to_add)) + "\\" + "\\".join(friends_to_add) + chr(23)) msg_from_server = attendre_reponse() if msg_from_server.split("\\")[:2] == [ "GROUP", "CREATED" ]: print "Groupe créé avec succès." try: os.mkdir(username + os.sep + "groups") except: pass try: os.mkdir(username + os.sep + "groups" + os.sep + "infos") except: pass f = open( username + os.sep + "groups" + os.sep + "infos" + os.sep + nom + ".info", "w") f.write("Key=" + key + "\nMembers=" + ", ".join(friends_to_add) + "\nGroup id=" + msg_from_server.split("\\")[2]) f.close() break else: friends_to_add.append(msg_from_server[int(rep) - 1]) else: print msg_from_server[int(rep) - 1], "selectionne." if not os.path.exists(username + os.sep + "messages" + os.sep + msg_from_server[int(rep) - 1]): key = r_pass.generate(256) destinataire = msg_from_server[int(rep) - 1] try: os.mkdir(username + os.sep + "keys") except: pass f = open( username + os.sep + "keys" + os.sep + destinataire + "key", "w") f.write(key) f.close() connection_server.send("START\\s_conv\\" + msg_from_server[int(rep) - 1] + "\\" + key + chr(23)) msg_from_server = attendre_reponse() if msg_from_server == "S_CONV\\CREATED": print "Les messages de cette conversation seront chiffrés avec une clé unique." elif msg_from_server == "S_CONV\\REFUSED": print "ACCES REFUSE. Vous allez etre déconnecte." return 1 else: destinataire = msg_from_server[int(rep) - 1] f = open( username + os.sep + "keys" + os.sep + destinataire + "key", "r") key = f.read() f.close() print "Tapez votre message ci dessous et appuyez sur entrée pour l'envoyer.\nLaissez le champ vide pour retrourner en arriere." message = raw_input(">>") if not len(message) == 0: msg_crypted = crpt.crypt_message(message, key) print "Envoye : {}".format( "SEND\\" + destinataire + "\\" + "[" + datetime.datetime.isoformat(datetime.datetime.now()) + "\\" + username + "]" + msg_crypted) connection_server.send( ("SEND\\" + destinataire + "\\" + "[" + datetime.datetime.isoformat(datetime.datetime.now()) + "\\" + username + "]" + msg_crypted + chr(23))) msg_from_server = attendre_reponse() if msg_from_server == "SEND\\OK": prev_conv = "" print "Message envoyé !\n\n" try: f = open( username + os.sep + "messages" + os.sep + destinataire, "r") prev_conv = f.read() f.close() except: pass finally: verif_path(os.path.join(username, "messages"), folder=True) f = open( username + os.sep + "messages" + os.sep + destinataire, "w") f.write(prev_conv) f.write("[" + datetime.datetime.isoformat( datetime.datetime.now()) + "\\" + username + "]" + message + "\n") f.close() trier_conv(username + os.sep + "messages" + os.sep + destinataire) elif len(message) == 0: envoyer_message() return 0 else: print "Le message n'a pas été remis.\n\n" afficher_menu() else: if conv_type == "single": f = open(username + os.sep + "keys" + os.sep + dest + "key", "r") key = f.read() else: f = open(username + os.sep + "groups" + os.sep + "infos" + os.sep + dest + ".info") datas = f.read().split("\n") key = "=".join(datas[0].split("=")[1:]) members = datas[1].split("=")[1].split(", ") id = datas[2].split("=")[1] f.close() print "Tapez votre message ci dessous et appuyez sur entré pour l'envoyer. Laissez le champ vide pour annuler et retourner à la conversation." message = raw_input(">>") if not len(message) == 0: msg_crypted = "[" + datetime.datetime.isoformat( datetime.datetime.now( )) + "\\" + username + "]" + crpt.crypt_message(message, key) if conv_type == "single": print "Message envoye : {}".format("SEND\\" + dest + "\\" + msg_crypted) connection_server.send( ("SEND\\" + dest + "\\" + msg_crypted + chr(23))) else: connection_server.send( ("SEND_GROUP\\" + ", ".join(members) + "\\" + id + "\\" + msg_crypted + chr(23))) msg_from_server = attendre_reponse() if msg_from_server == "SEND\\OK": prev_conv = "" print "Message envoyé !\n\n" try: if conv_type == "single": f = open( username + os.sep + "messages" + os.sep + dest, "r") prev_conv = f.read() f.close() except: pass finally: if conv_type == "single": f = open( username + os.sep + "messages" + os.sep + dest, "w") f.write(prev_conv) f.write("[" + datetime.datetime.isoformat( datetime.datetime.now()) + "\\" + username + "]" + message + "\n") f.close() if conv_type == "single": trier_conv(username + os.sep + "messages" + os.sep + dest) else: print "Le message n'a pas été remis.\n\n" else: return 0
def envoyer_message(type=str(), dest=str(), message=str()): """ Cette fonction permet d'envoyer un message. Elle doit terminer d'être codée. Elle prend 3 paramètres : - type : Deux valeurs possibles, à savoir 'single' ou 'group', correspondant respectivement à une conversation avec une seule personne et à une conversation de groupe. - dest : le destinataire dans le cas d'une conversation avec une seule personne, le nom du groupe dans le cas d'un groupe. - message : le message à envoyer. """ if type == "single": key_file = open(os.path.join(username, "keys", dest + "key"), "r") key = key_file.read() key_file.close() msg = "[" + datetime.datetime.isoformat(datetime.datetime.now( )) + "\\" + username + "]" + crpt.crypt_message(message, key) acces = connection_server.ask_for_ticket() connection_server.requests[acces] = "SEND\\" + dest + "\\" + msg connection_server.ask_for_send(acces) msg_from_server = attendre_reponse(acces) if msg_from_server == "SEND\\OK": # --- LE MESSAGE À ÉTÉ ENVOYÉ, INFORMER L'UTILISATEUR (VIA UN PETIT SIGNE SUR LE MESSAGE, CF WHATSAPP PAR EXEMPLE) conv_file = open(os.path.join(username, "messages", dest), "a") conv_file.write( "[" + datetime.datetime.isoformat(datetime.datetime.now()) + "\\" + username + "]" + message + "\n") conv_file.close() trier_conv(os.path.join(username, "messages", dest)) else: # --- LE MESSAGE N'A PAS ETE REMIS. AVERTIR L'UTILISATEUR --- pass elif type == "group": config_file = open( os.path.join(username, "groups", "infos", dest + ".info"), "r") config = config_file.read() config_file.close() group_key = config.split("\n")[0].split("=")[1] group_members = config.split("\n")[1].split("=")[1].split(", ") group_id = config.split('\n')[2].split('=')[1] msg = "[" + datetime.datetime.isoformat(datetime.datetime.now( )) + "\\" + username + "]" + crpt.crypt_message(message, group_key) acces = connection_server.ask_for_ticket() connection_server.requests[acces] = "SEND_GROUP\\" + ", ".join( group_members) + "\\" + group_id + "\\" + msg connection_server.ask_for_send(acces) msg_from_server = attendre_reponse(acces) if msg_from_server == "SEND\\OK": # --- LE MESSAGE À ÉTÉ ENVOYÉ, INFORMER L'UTILISATEUR (VIA UN PETIT SIGNE SUR LE MESSAGE, CF WHATSAPP PAR EXEMPLE) pass else: # --- LE MESSAGE N'A PAS ETE REMIS. AVERTIR L'UTILISATEUR --- pass pass else: raise ValueError("Expected 'single' or 'group', {} found".format(type))
import os import sys sys.path.append( os.path.join(os.path.dirname(os.path.abspath(__file__)), '..\src')) import Logger import Crypt try: str = 'hogefuga' print('暗号化対象文字列:' + str) encrypt_result = Crypt.Encrypt(str) #encrypt_result[0]:暗号化した文字列 #encrypt_result[1]:秘密鍵 crypted_str = encrypt_result[0] key = encrypt_result[1] print('暗号化した文字列:', end='') print(crypted_str) decrypt_result = Crypt.Decrypt(crypted_str, key) print('復号した文字列:' + decrypt_result) except Exception as e: tb = sys.exc_info()[2] Logger.Logging("message:{0}".format(e.with_traceback(tb)))