def on_write(self, sock): if sock == self.local_sock: data = ''.join(self.data_to_local) self.data_to_local = [] self.send(data, sock) elif sock == self.remote_sock: if self.state == STATE_CONNECTING: self.send(encrypt(self.cmd), sock) rs.add(sock) elif self.state == STATE_RELAYING: data = ''.join(self.data_to_remote) self.data_to_remote = [] self.send(encrypt(data), sock) else: raise Exception('oops')
def auth(self): while True: msg = '请输入用户密码: ' self.request.send(msg.encode()) logininfo = self.request.recv(1024) logininfo = json.loads(logininfo.decode()) userinfo = self.configinfo['userinfo'] if not userinfo: break if logininfo[0] in userinfo: #如果用户存在 if common.encrypt(logininfo[1]) == userinfo[ logininfo[0]]['password']: #比较用户的密码和配置中用户的密码 msg = "400" #验证通过 log_msg = self.log_template % (logininfo[0], 'login', ' ', "success", "登录成功") self.__write_log(log_msg, 'info') else: msg = "401" #密码错误 log_msg = self.log_template % (logininfo[0], 'login', '', "faild", "登录失败,密码错误") self.__write_log(log_msg, 'warning') else: msg = "402" #用户不存在 log_msg = self.log_template % (logininfo[0], 'login', '', "faild", "登录失败,未知用户") self.__write_log(log_msg, 'error') self.request.send(msg.encode()) client_ack = self.request.recv(1024).decode() if client_ack == "300": break else: continue
def setup(): filename = os.path.dirname(os.path.abspath(inspect.stack()[0][1])) config.read(filename + '/data.ini') if int(config['SETUP']['first_time']) == 1: print('Running the manager for first time') print('Please enter your password for encrypting and verification ( you will prompted for the password ' 'every time you run the main script)') # 256 bit key hashed_pw = hashlib.sha256(getpass.getpass(prompt='Password for script: ').encode('ascii').strip()).digest() check_pwd = hashlib.sha256(getpass.getpass(prompt='ReType the password: '******'ascii').strip()).digest() if check_pwd == hashed_pw: config['SETUP']['first_time'] = '0' config['SETUP']['check'] = str(encrypt(config['SETUP']['check'], hashed_pw), 'utf-8') # writing the changes back into the file filename = os.path.dirname(os.path.abspath(inspect.stack()[0][1])) with open(filename + '/data.ini', 'w') as configfile: # save config.write(configfile) # succesful status print("Setup complete! Now you can use the script normally") else: print("Passwords do not match!") print("Aborting...") else: print("Setup already done") print("exiting...")
def check_verification_code(): """ :tips: uin = 40805092 --> 17688834313的手机号码 :return: """ # 先调用发验证码接口 params = {'serverId': 3711, 'uin': 40805092, 'account_id': 22650705, 'user_id': 15001242, 'ip': 123456} params = encrypt(**params) Access('SendVerificationCode', **params).get() # 获取数据库最新的验证码 verify_code = int(DB().get_verification_code()) # 调用校验验证码接口 payload = {'serverId': 3711, 'uin': 40805092, 'account_id': 22650705, 'user_id': 15001242, 'ip': 123456, 'verify_code': verify_code} payload = encrypt(**payload) response = Access('CheckVerificationCode', **payload).get() return response
def on_read(self, sock): try: data = sock.recv(BUF_SIZE) except Exception as e: print e self.destroy() return if not data: self.destroy() return if sock == self.local_sock: if self.state == STATE_WAIT_GREETING: print 'got greeting from {}: {}'.format( sock.getpeername(), len(data)) self.send('\x05\x00', self.local_sock) self.state = STATE_WAIT_COMMAND elif self.state == STATE_WAIT_COMMAND: self.on_command(data) elif self.state == STATE_CONNECTING: self.data_to_remote.append(data) print 'data from app while connecting:', len(data) elif self.state == STATE_RELAYING: print '->', len(data) self.send(encrypt(data), self.remote_sock) else: raise NotImplementedError('other state') elif sock == self.remote_sock: if self.state == STATE_CONNECTING: self.state = STATE_RELAYING if self.data_to_remote: data = ''.join(self.data_to_remote) self.data_to_remote = [] data = encrypt(data) self.send(data, sock) elif self.state == STATE_RELAYING: data = decrypt(data) self.send(data, self.local_sock) else: raise NotImplementedError('oops') else: raise Exception('oops')
def add_user(): configinfo = base.init() userdb = os.path.join(BASE_PATH, configinfo['userdb']) data_path = os.path.join(BASE_PATH, configinfo['data']) username = input('请输入用户名: ') passwd = input('请输入密码: ') fp = open(userdb, 'a+') fp.write("%s:%s" % (username, common.encrypt(passwd)) + '\n') #写入密码文件 fp.close() user_file = os.path.join(data_path, username) #用户数据目录 os.mkdir(user_file) #创建目录 print('用户%s添加成功' % username)
def setUp(self): # 先调用发验证码接口 params = { 'serverId': 3711, 'uin': 40805092, 'account_id': 22650705, 'user_id': 15001242, 'ip': 123456 } params = encrypt(**params) Access('SendVerificationCode', **params).get() # 获取数据库最新的验证码 self.verify_code = int(DB().get_verification_code())
def add_user(username, hashed_pwd): # adding a new user config['DATA'][username] = str( encrypt(getpass.getpass(prompt='Password for ' + username + ':'), hashed_pwd), 'utf-8') # writing the changes back into the file filename = os.path.dirname(os.path.abspath(inspect.stack()[0][1])) with open(filename + '/data.ini', 'w') as configfile: # save config.write(configfile) # Success message print("Account of " + username + " successfully added")
def on_read(self, sock): try: data = sock.recv(BUF_SIZE) except Exception as e: print e self.destroy() return if not data: self.destroy() return if self.stage == STAGE_RELAYING: if sock == self.local_sock: data = decrypt(data) print '->', len(data) self.send(data, self.remote_sock) elif sock == self.remote_sock: print '<-', len(data) data = encrypt(data) self.send(data, self.local_sock) elif self.stage == STAGE_WAIT_COMMAND: cmd = decrypt(data) try: request_addr = parse_request_addr(cmd) self.send(encrypt('\x05\x00'), self.local_sock) sock = socket.socket() self.remote_sock = sock sock.setblocking(0) ws.add(sock) sock2handler[sock] = self sock.connect_ex(request_addr) self.stage = STAGE_CONNECTING print 'connecting to remote', request_addr except Exception as e: print e self.destroy() elif self.stage == STAGE_CONNECTING: data = decrypt(data) self.data_to_remote.append(data)
def test_check_verification_code_fail(self): """校验验证码失败""" payload = { 'serverId': 3711, 'uin': 40805092, 'account_id': 22650705, 'user_id': 15001242, 'ip': 123456, 'verify_code': 12345 } payload = encrypt(**payload) response = Access('CheckVerificationCode', **payload).get() message = response['Message'] self.assertEqual('Verification Code is not correct!', message)
def set_main_password(self): if not self.main_password_is_correct(): return self.inputs = self.get_inputs() main_password = self.ids.main_password_inp.text if not self.validate_password(main_password): self.message = 'Password too weak' elif not self.password: self.message = 'Type password to server first' else: self.message = '' self.encrypted_password = encrypt(self.password, main_password).decode() self.save_config() self.ids.manager.current = 'credentials'
def get_excel_test_data(self): """ 请求方式等于get时使用 :return type: list --> [{...},{...},{...}...] """ for i in range(2, self.rows): value = self.sheet.row_values(i)[1:self.cols - 1] # 获取预期结果 check_point = self.sheet.row_values(i)[-1] for k, v in enumerate(value): """将float数据转成int型""" if isinstance(v, float): value[k] = int(v) payload = encrypt(**dict(zip(self.key, value))) payload['check_point'] = check_point self.data.append(payload) return self.data
def encrypt(plaintext: str, key: bytes) -> bytes: return common.encrypt(plaintext, key, ecb_encryption)
def encryptMessage(self, message): return common.encrypt(self.sessionkey, message)
def getEncryptedNonce(self): self.DHKey = common.generateKey(self.sharedKey) self.myNonce = common.getNonce() return common.encrypt(self.DHKey, self.myNonce)
if int(sys.argv[2]) < 65535 and int(sys.argv[2]) > 0: PORT = int(sys.argv[2]) else: print "The port provided is invalid, ports must be 0-65535. The program will now exit." sys.exit(1) HOST = sys.argv[1] else: print "Invalid parameters, default HOST ({0}) and PORT ({1}) will be used".format(HOST, PORT) client = socket.socket(socket.AF_INET, socket.SOCK_STREAM) try: client.connect((HOST, PORT)) except socket.gaierror, errorMessage: print "The client could not connect due to an Address-related error: {0}".format(errorMessage) sys.exit(1) except socket.error, errorMessage: print "The client could not connect: {0}".format(errorMessage) sys.exit(1) # prompt for and encrypt message message = raw_input("Enter message: ") print 'plaintext', message ciphertext = encrypt(message) print 'ciphertext', ciphertext # send message and terminate print 'sending message' client.send(ciphertext) print 'terminating' client.close()