def test_web(self): phone = self.get_random_phone_number() # check timestamp = str(time.time()) action = random.choice(list(constants.ActionEnum)).value user = self.user ip = '::1' url = urlparse.urljoin(self.server, '/phone/check') params = dict(token=user.token, timestamp=timestamp, phone=phone, action=action, ip=ip) params['sign'] = utils.md5(user.key+timestamp+phone) response = requests.get(url, params=params) logging.info('response: %s', response.text) r = response.json() self.assertTrue(r['code'] == 0, 'access url failure: url: %s, response: %s' % (url, response.text)) # add white list url = urlparse.urljoin(self.server, '/phone/commit/white_list') params = dict(token=user.token, timestamp=timestamp, phone=phone) params['sign'] = utils.md5(user.key+timestamp+phone) response = requests.get(url, params=params) logging.info('response.text: %s', response.text) r = response.json() self.assertTrue(r['code'] == 0, 'access url failure: url: %s, response: %s' % (url, response.text)) return
def post(self): params = {} for key in ['phone', 'icon']: params[key] = self.arguments.get(key, "") #fh = open("/static/gofree.png", "wb") #fh.write(params['icon'].decode('base64')) #fh.close() width = 100 uid_hash = utils.md5(self.current_user['uid']) img_dir = 'static/headimg/%s/%s' % (uid_hash[:2], uid_hash[2:4]) filename = utils.md5(str(time.time()+random.randint(10000, 99999))) img_file = '%s/%s.png' % (img_dir, filename) # 创建文件夹 img_path = os.path.join(constants.BASE_DIR, img_dir) if not os.path.exists(img_path): os.makedirs(img_path) f = open(os.path.join(constants.BASE_DIR, img_file), 'wb+') f.write(params['icon'].decode('base64')) f.close() im = Image.open(os.path.join(constants.BASE_DIR, img_file)) ratio = float(width)/im.size[0] height = int(im.size[1]*ratio) nim = im.resize((width, height), Image.BILINEAR) nim.save(os.path.join(constants.BASE_DIR, img_file)) users.update_avatar(self.current_user['uid'], '/'+img_file) base_url = self.config['url']['base'] url = base_url + '/' + img_file # print `url` + 'url' return self.return_result({"url": url})
def autenticate_user(self, cryptor, server): status = "unauthorized" # Mientras estado sea desautorizado. while status == "unauthorized": print "Autenticación:" usr = raw_input(">>> Usuario: ") pwd = getpass.getpass(">>> Password: "******"|" + pwd_md5)) crypto = server.recv(self.__buffer_size) status = decrypt(cryptor, crypto) if (status == "unauthorized"): print "Usuario o contraseña incorrectos.\n" # Si el servidor no envía datos, significa que la autenticación ha # sido fallida. if (crypto == ""): print "Se ha superado el número máximo de intentos..." return False return True
def reset_password(handler, old, new): db = handler.db user = db.query(User).filter_by(name=handler.username).first() if user.pwd != utils.md5(old): return False user.pwd = utils.md5(new) return True
def from_url(self, url): if md5(url) in self.cache: self.data = self.cache[md5(url)] return data = json.dumps({'url': url}) headers = {'Content-Type': 'application/json'} self.data = self._get_faces(headers, data) self.cache[md5(url)] = self.data
def modify_password(old_password, new_password): oldpasswd = utils.md5(old_password) newpasswd = utils.md5(new_password) username = current_user.get('username') sql = "update users set user_password= ?, update_time = ? where user_name = ? and user_password = ? " params = (newpasswd, utils.now(), username, oldpasswd) num = db.update(sql, params) return True if num > 0 else False
def post(self): args = login_parser.parse_args() # get args if succeeded user, passwd = args['username'], args['password'] # Login r = requests.Session() print('[*] debug - try to login') fail, _ = try_to_login(r, user, passwd) if fail: return {'message': 'Failed to login'}, 400 print('[*] debug - login success') # Generate the token dic = {'username': user, 'password': passwd} dic['secret'] = md5(config.SECRET_KEY) token = md5(dic) # TODO: add salt or use passlib? # print(token) # Check if a user is in the db res = db.session.execute( text('SELECT * FROM `user` WHERE username=:user'), {'user': user}) if res.returns_rows: # If not existing, add a new user if res.rowcount == 0: sql = text(''' INSERT INTO `Course`.`user` (`username`, `password`, `perm`, `firstlogin`, `lastlogin`, `token`, `sid`) VALUES (:username, :passwd, 0, :time, :time, :token, 68); ''') db.session.execute( sql, { 'username': user, 'passwd': passwd, 'time': time.time(), 'token': token }) db.session.commit() # If it exists, updates the token elif res.rowcount == 1: sql = text(''' UPDATE `Course`.`user` SET `token`=:token, `lastlogin`=:time WHERE username=:username ''') db.session.execute(sql, { 'token': token, 'username': user, 'time': time.time() }) db.session.commit() # Update user information # TODO: make this async info = get_person_identity(r, user, passwd) update_user_info(user, info) return {'token': token}, 200
def from_file(self, path): if os.path.getsize(path) > 2*1024*1024: raise FileTooBigException('File must be under 2MB') if md5(path) in self.cache: self.data = self.cache[md5(path)] return data = open(path, 'rb').read() headers = {'Content-Type': 'application/octet-stream'} self.data = self._get_faces(headers, data) self.cache[md5(path)] = self.data
def wakaestado(chat, lang): """ Piece of the standard flow to calculate and send the wakaestado """ completed = db.check_completed(md5(chat)) # put phase to 0 db.change_phase(newphase=0, id_user=md5(chat)) # final risk and "explanation" risk, partial_scores = obesity_risk(md5(chat), completed) risk = round(risk) # imagen wakaestado send_image(images[lang]['wakaestado.jpg'], chat) # wakaestado detailed if completed[0] and completed[1] and completed[2]: # nutrition, activity, bmi, risk, network # normal weight, overweight... weight_cat = weight_category(round(partial_scores['bmi']), lang) difference = partial_scores['mean_contacts'] - partial_scores[ 'wakascore'] # load "debajo/arriba" string index = 0 if difference > 0 else 1 position = languages[lang]['posicion_media'].split('\n')[index] details = languages[lang]['wakaestado_detail'] details = details.format( str(risk) + n_avocados(risk), str(abs(round(difference))), position, str(partial_scores['n_contacts']), str(round(partial_scores['nutrition'])) + n_avocados(partial_scores['nutrition']), str(round(partial_scores['activity'])) + n_avocados(partial_scores['activity']), str(round(partial_scores['bmi_score'])) + n_avocados(partial_scores['bmi_score']), str(round(partial_scores['bmi'])), weight_cat, str(round(partial_scores['network'])) + n_avocados(partial_scores['network'])) send_message(emoji.emojize(details), chat) # WakaEstado partial else: # give a general advice send_message( emoji.emojize(languages[lang]['wakaestado_parcial'].format( str(risk) + avocados(risk))), chat)
def create(): response={} try: reader = codecs.getreader("utf-8") data = json.load(reader(request.body)) #data=json.load(request.body.read().decode('utf8')) firstName='\''+data['firstName']+'\'' lastName='\''+data['lastName']+'\'' nickName='\''+data['nickName']+'\'' telephone='\''+data['telephone']+'\'' email='\''+data['email']+'\'' userPass='******''+utils.md5(data['userPass'])+'\'' sql="insert into User (firstName, lastName, nickName, telephone,email,us erPass) values(%s, %s,%s, %s,%s, %s)" %(firstName,lastName,nickName,telephone,em ail, userPass) userID=mysql.query(sql,0)[0] #print (userID) token=uuid.uuid4().hex response['userID']=userID response['token']=token userIDstr='\''+str(userID)+'\'' token='\''+token+'\'' sql="insert into Token (created_at, userID, generatedToken) values (TIME STAMPADD(MONTH,1,CURRENT_TIMESTAMP), %s, %s)" % (userIDstr, token) mysql.query(sql,1)
def auth_register_controller(): # Get post parameters try: temp_data = request.json username = temp_data['username'] password = temp_data['password'] except: # Parameter error current_app.logger.error("Error in parsing requests:", exc_info=True) return jsonify({'status': 1, 'error': HTTP_BADREQ_TEXT}), HTTP_BADREQ # Check whether this username is already registered temp = find_user_by_username(username) if temp == 1: return jsonify({'status': 1, 'error': '用户名已被注册'}), HTTP_OK elif temp == 2: return jsonify({'status': 1, 'error': '数据库未知错误'}), HTTP_UNKNOWN # Store user try: new_user = User(username=username, password=md5(password)) current_app.db.session.add(new_user) current_app.db.session.commit() except: current_app.logger.error("Error in inserting a new user:", exc_info=True) current_app.db.session.rollback() return jsonify({'status': 1, 'error': '数据库未知错误'}), HTTP_UNKNOWN return jsonify({'status': 0}), HTTP_OK
def send_sms_ytx(phone, ytx): """ 容联云通讯短信验证码 """ # FIXME 修改为异步 or 消息队列 ts = datetime.now().strftime("%Y%m%d%H%M%S") sig = utils.md5(ytx['acid'] + ytx['actoken'] + ts).upper() url = '%s/2013-12-26/Accounts/%s/SMS/TemplateSMS?sig=%s' % \ (ytx['url'], ytx['acid'], sig) headers = { "Accept": "application/json", "Content-Type": "application/json;charset=utf-8", "Authorization": base64.b64encode(ytx['acid'] + ':' + ts), } code = str(random.randint(100000, 999999)) payload = { "to": phone, "appId": ytx['appid'], "templateId": "18791", "datas": [code, '10'], } r = requests.post(url, headers=headers, data=json.dumps(payload)) result = r.json() if result['statusCode'] == '000000': return True, code elif result['statusCode'] == '112314': return False, result['statusCode'] else: return False, result['statusMsg'].encode('utf-8')
def buy_trial_cloud(self, cpu, memory, datahd, os, bw, zone_id): data = { 'accessKey': self.accesskey, 'vKey': md5(self.accesskey, self.screctkey, cpu, memory, datahd, os, bw, zone_id), 'cpu': cpu, 'memory': memory, 'datahd': datahd, 'os': os, 'bw': bw, 'zoneId': zone_id } data = urlencode(data) headers = {'Content-Type': 'application/x-www-form-urlencoded'} result = self.connection.request('/api/buyTrialCloud', headers=headers, data=data, method='POST') return json.loads(result.body)
def __init__(self, use_cache=True): super().__init__() dataset_file = DATASET_CUSTOM_FILE if os.path.exists(DATASET_CUSTOM_FILE) else DATASET_FILE print("Use dataset %s" % dataset_file) with bz2.open(dataset_file, "rb") as fp: raw = fp.read() hs = md5(raw) cache_file = os.path.join(CACHE_DIR, "%s.captcha.gz" % hs) if os.path.exists(cache_file) and use_cache: print("Use dataset cache %s" % cache_file) X, y, labels = joblib.load(cache_file) self.labels = labels self.X = X self.y = y return Xlist = [] ylist = [] N = SEG_SIDE_LENGTH BS = 8 PAD = BS - (N * N % BS) CS = math.ceil(N * N / BS) with BytesIO(raw) as fp: t = tqdm(desc="decode dataset", total=fp.getbuffer().nbytes) while True: X = fp.read(CS) y = fp.read(1) if X == b'' or y == b'': break t.update(CS + 1) X = np.array([ (ck >> ofs) & 0b1 for ck in X for ofs in range(BS-1, -1, -1) ][:-PAD]) X = 1 - X y = u(y) Xlist.append(X) ylist.append(y) t.close() labels = list(sorted(set(ylist))) assert len(labels) == LABELS_NUM ixs = np.empty(128, dtype=np.uint8) for ix, c in enumerate(labels): ixs[ord(c)] = ix X = np.array(Xlist, dtype=np.float32).reshape(-1, 1, N, N) y = np.array([ ixs[ord(c)] for c in ylist ], dtype=np.long) self.labels = labels self.X = X self.y = y joblib.dump((X, y, labels), cache_file, compress=9)
def save_models(self): obj = self.new_obj request = self.request year = request.POST.get('birth_of_year') month = request.POST.get('birth_of_month') day = request.POST.get('birth_of_day') obj.admin_no = request.user.username if not year: year = u'*' if not month: month = u'*' if not day: day = u'*' if year != u'*' or month != u'*' or day != u'*': obj.birth = year + '-' + month + '-' + day md5_string = year + month + day + request.POST.get( 'name') + request.POST.get('gender') + request.POST.get('source') obj.no = md5(md5_string) try: obj.save() except: pass
def pass_reset_post(): req_data = request.get_json(force=True) # exc = '' # for x in req_data: # exc = exc + str(x) + ':' + str(req_data[x]) + '||' # raise Exception(exc) reset_token = req_data['resetToken'] new_password = req_data['password'] try: tmp_token = jwt.decode(reset_token, SECRET_KEY, algorithms='HS256', verfify_exp=True) email = tmp_token['email'] iat = tmp_token['iat'] user_exists = app.cassandra.execute(app.cassandra.pr_user_lookup, [email]) if user_exists[0].last_modified > datetime.datetime.utcfromtimestamp( iat): raise Exception except: return make_response(jsonify("Bad token"), 403) # pass_hash = pbkdf2_sha256.hash(new_password) pass_hash = md5(new_password) new_modified_time = datetime.datetime.utcnow() app.cassandra.execute(app.cassandra.pr_upd_pass, [pass_hash, new_modified_time, email]) return make_response(jsonify("Success"), 200)
def sign_in(self) -> None: captcha = self.captcha.get() if not captcha or captcha.strip() != self.captcha_answer: self.update_captcha() messagebox.showerror("Регистрация", "Ошибка в капче!", icon="warning") return login, password = self.username.get(), self.password.get() is_sign_in = self.database_manager.sign_in(login, md5(password)) if is_sign_in: # * Очистка фрейма, мусорных атрибутов self.Frame.destroy() del self.Frame del self.username del self.password del self.captcha # * Инициализация основной страницы self.MainPage() return True self.update_captcha() messagebox.showerror("Авторизация", "Логин и/или пароль неверны!", icon="warning") return False
def start(): cookies = cks() if cookies: q.update({'cookies': cookies}) unfinished = [1] while unfinished: for x in req_info: try: key = x['url'] + '|' + str(x.get('libid', '')) category_id = md5(key) t = db2.find_one({'category_id': category_id}) if t: page = t.get('page', []) pages = range(1, t.get('pages', 1) + 1) # unfinished.remove(1) unfinished = list(set(pages) - set(page)) if unfinished: for y in unfinished: try: get_list(x, q['cookies'], y) except: sys.exit() # cookies = cks() # get_list(x, y) else: print('%s no item' % category_id) except Exception as e: print(e) sys.exit()
def savestudent(request): conn = DBSession() params_tuple=['student.id','student.name','student.identity','student.clazzid'] student_id,name,identity,clazzid=[request.params.get(x) for x in params_tuple] student = conn.query(Student).filter(Student.id == student_id).first() if student: student.name = name student.identity = identity student.clazzid = clazzid student.updatetime=time.time() else : student = Student() student.name = name student.identity = identity student.clazzid = clazzid student.state=0 student.createtime=time.time() student.updatetime=time.time() user = User() user.name = identity #md5加密 user.password = md5(identity) user.role = 2 user.regtime=time.time() user.logintimes=0 conn.add(user) conn.flush() student.userid = user.id conn.add(student) conn.flush() return HTTPFound(location=request.route_url('student_list'))
def check_sign_duomeng(self): """ duomeng验证签名 """ args = self.request.arguments kv = [] for key in args: if key != 'sign': value = args[key][0].decode('utf-8') kv.append('%s=%s' % (key, value)) raw_str = '' for s in sorted(kv): raw_str += s raw_str += self.config['duomeng_key']['ios'] utils.loggers.use('callback', self.log_path).info('[duomeng_before_md5]'+raw_str) utils.loggers.use('callback', self.log_path).info('[duomeng_md5]'+utils.md5(raw_str)) return utils.md5(raw_str)
def cloud(): while True: time.sleep(3) video = Video.select().where(Video.status == 1).first() if not video: continue Video.update(status = 2).where(Video.id == video.id).execute() root = os.path.dirname(os.getcwd()) envfile = cloudconfig() cmd = [sys.executable, f'{root}/up.py', '-c', envfile, f'{os.getcwd()}/queues/{video.id}'] Video.update({Video.output: f'{" ".join(cmd)}\n'}).where(Video.id == video.id).execute() p = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.STDOUT) while True: line = p.stdout.readline() if not line: break Video.update({Video.output: Video.output + line.decode('utf-8')}).where(Video.id == video.id).execute() p.wait() if p.returncode == 1: Video.update(status = 3).where(Video.id == video.id).execute() if p.returncode == 2: Video.update(status = 1).where(Video.id == video.id).execute() if p.returncode != 0: continue code = open(f'{root}/tmp/out.m3u8', 'r').read() Video.update( status = 0, code = code, slug = md5(code, True), params = open(f'{root}/tmp/params.json', 'r').read(), updated_at = datetime.datetime.now() ).where(Video.id == video.id).execute()
def message_service_callback(self,msg): if msg=="refresh_match_grid": self.data_grid_model = MatchsTreeModel(self.analyze_thread.dataset) self.matchs_grid.setModel(self.data_grid_model) if url_with_params(self.urlComboBox.currentText()): file_path = "data/"+md5(self.urlComboBox.currentText()) if not os.path.exists(file_path): # for row in self.analyze_thread.dataset: # row.pop("formula_total") # row.pop("formula_last10") # row.pop("formula_last4") # write_file(file_path,json.dumps(self.analyze_thread.dataset)) pass self.execute_button.setEnabled(True) self.clear_button.setEnabled(True) self.urlComboBox.setEnabled(True) elif msg == "cache_history_data": #batch_save_history_matchs(self.download_history_thread.dataset) wl_lb_match_history_cache(self.download_history_thread.dataset) pass elif msg == "completed": self.execute_button.setEnabled(True) self.urlComboBox.setEnabled(True) elif msg == "trigger_matchs_analyze": self.trigger_matchs_analyze() else: self.msg_bar.setText(msg)
def log_in(self, username, password): """ Attempt to log in. :param username: User login. :param password: User password. :returns: True :rtype: bool :raises: :class:`.APIException` """ response = self._request( 'GET', '/v2/user-token', args=dict( loginMethod='9gag', loginName=username, password=utils.md5(password), language='en_US', pushToken=utils.random_sha1() ) ) self.token = response['data']['userToken'] self.userData = response['data'] self.generatedAppId = dict(parse_qsl(self.userData['noti']['readStateParams']))['appId'] # self.generatedAppId = dict(parse_qsl(self.userData['noti']['chatBadgeReadStateParams']))['appId'] return True
def get_new_order_price(self, cpu, memory, datahd, os, bw, ordernum, periodtype, periodnum, zoneid): data = { 'accessKey': self.accesskey, 'vKey': md5(self.accesskey, self.screctkey, cpu, memory, datahd, os, bw, ordernum, periodtype, periodnum, zoneid), 'cpu': cpu, 'memory': memory, 'datahd': datahd, 'os': os, 'bw': bw, 'orderNum': ordernum, 'periodType': periodtype, 'periodNum': periodnum, 'zoneId': zoneid } data = urlencode(data) headers = {'Content-Type': 'application/x-www-form-urlencoded'} result = self.connection.request('/api/getNewOrderPrice', headers=headers, data=data, method='POST') return json.loads(result.body)
def _new_plugin(actor_system, plugin_actors,plugin_name): plugin_import = import_plugin(plugin_name) plugin_md5 = md5(os.path.join(plugins_dir(), plugin_name + '.py')) plugin_actor = create_actor(actor_system, plugin_import.Main) plugin_actors[plugin_name] = {"actor": plugin_actor, "md5": plugin_md5} print "new plugin loaded: %s" % plugin_name return plugin_actors
def go_main(chat, lang): """ Macro for setting up one user to the main phase """ db.change_phase(newphase=0, id_user=md5(chat)) send_message(languages[lang]['select'], chat, main_menu_keyboard(chat, lang))
def __init__(self, executable): """ init function Args: executable: target executable file path """ self.logger = LogUtil.get_logger() self.executable = executable self.elf = getELF(executable) self.arch = get_arch(self.elf) self.functions = {} self.addr2func = {} self.get_func() self.signs = {} self.explored_addr = [] self.matched = {} self.sign_cache_file = "/tmp/" + md5(executable) + "_sign.cache" if os.path.exists(self.sign_cache_file): with open(self.sign_cache_file) as f: data = f.read() try: self.signs = json.loads(data) except Exception as e: self.logger.error(str(e))
def get_sign(self, params={}): """ 兑吧md5签名 """ params = self._ksort(params) raw_str = '' for p in params: raw_str += str(p[1]) return utils.md5(raw_str)
def analysis_rss(self, list_obj): logging.info('-- analysis rss --') if self.lclass == "intelligence": for i in self.content: u = { "class": self.lclass, "title": self.get_value(i, list_obj['response']['title']).strip(), "summary": self.get_value(i, list_obj['response']['summary']), "publish_time": time.strftime( "%Y-%m-%d %H:%M", self.get_value(i, list_obj['response']['publish_time'])), "source": self.get_value(i, list_obj['response']['source']), "raw_url": self.get_value(i, list_obj['response']['raw_url']) } url = u['raw_url'] uhash = str(md5(url)) if self.unique_url(url): u["rhash"] = uhash redis_c.lpush('result', json.dumps(u)) logging.info('-- push url %s --' % url) else: logging.info('-- exist url %s --' % url)
def _IsNewPC(self): if sys.platform == 'win32': cur_name = md5(os.environ['COMPUTERNAME']) store_name = get_conf('perm', 'flag') if cur_name != store_name: clear_conf('db') set_conf('perm', 'flag', cur_name)
def main(): # Let's use letter frequencies to detect English english = [ # a - z letter frequencies 0.08167, 0.01492, 0.02782, 0.04253, 0.12702, 0.02228, 0.02015, 0.06094, 0.06966, 0.00153, 0.00772, 0.04025, 0.02406, 0.06749, 0.07507, 0.01929, 0.00095, 0.05987, 0.06327, 0.09056, 0.02758, 0.00978, 0.02360, 0.00150, 0.01974, 0.00074] I_english = sum([p ** 2 for p in english]) freqs = {' ': 0, '.': 0, ',': 0} # I set these frequencies to 0, too lazy to look them up for (i, char) in enumerate(string.ascii_uppercase): freqs[char] = english[i] # Brute force! length = len(ciphertext) I = [] for a in aa: for b in bb: trial_cipher = decrypt(ciphertext, a, b) counts = Counter(trial_cipher) Ij = sum([freqs[char] * n / length for (char, n) in counts.items()]) I.append(((a, b), abs(Ij - I_english))) results = sorted(I, key=lambda x: x[1]) a, b = results[0][0] plaintext = decrypt(ciphertext, a, b) solution = md5(plaintext) print(plaintext) print(solution)
def pack_dataset(): N = SEG_SIDE_LENGTH BS = 8 weight = np.array([1 << ofs for ofs in range(BS - 1, -1, -1)], dtype=np.uint8) pad = np.zeros((BS - (N * N % BS)), dtype=np.uint8) ignored = get_trash_segs_md5() with bz2.open(DATASET_CUSTOM_FILE, "wb") as fp: for label in tqdm(sorted(os.listdir(DECODED_DATASET_DIR)), "pack dataset"): subdir = os.path.join(DECODED_DATASET_DIR, label) y = b(label[0]) for filename in sorted(os.listdir(subdir)): path = os.path.join(subdir, filename) im = cv2.imread(path).astype(np.uint8) hs = md5(im.tobytes()) if hs in ignored: continue X = np.array((im.sum(axis=2) // 3) >> 7, dtype=np.uint8) X = np.hstack([X.flatten(), pad]).reshape(-1, BS) X = (X * weight).sum(axis=1).astype(np.uint8) X = bytes(X) fp.write(X + y)
def get(self): word_list = self.get_argument("word", default="").split("\n") if len(word_list) > 0: for word_item in word_list: word = word_item.strip() word_id = utils.md5(word) record_word = Words.objects(word_id=word_id).first() if record_word is not None: self.write("该词条已经存在!") else: word_type = int(self.get_argument("word_type", default=1)) record_word = Words() record_word.word_id = word_id record_word.word = word record_word.src_type = word_type record_word.word_type = 1 record_word.save() top_flg = int(self.get_argument("word_type", default=1)) if top_flg == 1: top_word = TopWords() top_word.type = record_word.src_type top_word.word_id = record_word.word_id top_word.word = record_word.word top_word.save() self.write("词条添加成功!") self.finish()
def make_meta(self): # TREND_LINEAR_DATA------------------------------------------------------------------------ trend_linear_data = json.loads(self.external_collector.get_trend_linear_data()) for value in trend_linear_data.values(): value['rundb_data'] = json.loads(value['rundb_data']) self.collector.write_pickle(trend_linear_data, 'TREND_LINEAR_DATA') # RUN_FILES-------------------------------------------------------------------------------- run_files = json.loads(self.external_collector.get_run_files()) data_ref = {} for run_number, files in run_files.items(): if files['ref'] is not None: data_ref[int(run_number)] = md5(files['ref']) self.collector.write_pickle(data_ref, 'DATA_REF') # MONET_HISTOS----------------------------------------------------------------------------- monet_histos = json.loads(self.external_collector.get_monet_histos()) self.collector.write_pickle(monet_histos, 'MONET_HISTOS')
def network_message(chat, lang): """ This method is invoked when the user visualize the networks """ # first we regenerate the network and get the graph ids ids_ = create_graph() # transform the id graph_id = ids_[md5(chat)][0] # send messages and stuff send_image(images[lang]['wakanetwork.jpg'], chat) contacts_counter = len(db.get_user_relationships(md5(chat))) msg_share = languages[lang]['share'].format(contacts_counter) send_message(emoji.emojize(msg_share), chat) send_message(emoji.emojize(languages[lang]['see_network']), chat) send_message(network_link + '?id=' + str(graph_id), chat)
def questionnaire(num, chat, lang, msg=None): """ Method to start a questionnatie flow TODO This can be parametrized and be way more general """ db.change_phase(newphase=num, id_user=md5(chat)) if num == 1: send_image(images[lang]['personal.jpg'], chat) elif num == 2: send_image(images[lang]['food.jpg'], chat) elif num == 3: send_image(images[lang]['activity.jpg'], chat) if msg: send_message(msg, chat) # edit instruction send_message(languages[lang]['edit'], chat) # throw first question q1 = db.get_question(phase=num, question=1, lang=lang) # error on the database if q1 is None: return # check for "extra" (out of the normal q-a flow) messages extra_messages(num, 1, chat, lang) send_message(emoji.emojize(q1), chat)
def post(self): username = self.get_argument("username") pattern = re.compile(r'^[A-Za-z0-9]{3,20}$') match = pattern.match(username) if match is False and username is None: self.api_response({'status':'fail','message':'会员名填写错误'}) return usercount = self.db.execute_rowcount("select * from users where username = %s", username) if usercount > 0: self.api_response({'status':'fail','message':'此会员名已被使用'}) return phone = self.session.get("phone") phonepattern = re.compile(r'^1(3[0-9]|4[57]|5[0-35-9]|8[0-9]|70)\d{8}$') phonematch = phonepattern.match(phone) if phonematch is False and phone is None: self.api_response({'status':'fail','message':'手机号填写错误'}) return phonecount = self.db.execute_rowcount("select * from users where phone = %s", phone) if phonecount > 0: self.api_response({'status':'fail','message':'此手机号已被使用'}) return password = self.get_argument("password") pwdRepeat = self.get_argument("pwdRepeat") if password is None and pwdRepeat is None and password != pwdRepeat: self.api_response({'status':'fail','message':'密码和确认密码填写错误'}) return type = self.get_argument("type") if type is None: self.api_response({'status':'fail','message':'经营主体不能为空'}) return name = self.get_argument("company",None) if type == u'7' else self.get_argument("name", None) if name is None: self.api_response({'status':'fail','message':'真实姓名或单位名称不能为空'}) return nickname = self.get_argument("nickname") if nickname is None: self.api_response({'status':'fail','message':'个人称呼不能为空'}) return lastrowid = self.db.execute_lastrowid("insert into users (username, password, phone, type, name, nickname, status, createtime)" "value(%s, %s, %s, %s, %s, %s, %s, %s)", username, utils.md5(str(password + config.salt)), phone , type, name, nickname, 1, int(time.time())) #查看是否为供应商列表里面的供应商,如果是转移积分 supplier=self.db.query("select id,pushscore from supplier where mobile=%s",phone) if supplier: self.db.execute("update users set pushscore=%s where id=%s", supplier[0]["pushscore"],lastrowid) self.db.execute("update supplier set pushstatus=2 where id=%s", supplier[0]["id"]) #因为去掉了user_info表,所以name字段直接放在users表了 # result = self.db.execute("insert into user_info (userid, name)value(%s, %s)", lastrowid, name) self.session["userid"] = lastrowid self.session["user"] = username self.session.save() #发短信通知用户注册成功 utils.regSuccessPc(phone, name, username) self.api_response({'status':'success','message':'注册成功','data':{'username':username}})
def sign(params): ''' https://pay.weixin.qq.com/wiki/doc/api/tools/cash_coupon.php?chapter=4_3 ''' params = [(str(key), str(val)) for key, val in params.iteritems() if val] sorted_params_string = '&'.join('='.join(pair) for pair in sorted(params)) sign = '{}&key={}'.format(sorted_params_string, conf.WEIXIN_PAY_API_KEY) return md5(sign).upper()
def getHash(data): try: bEncodedData = utils.byteFyer(data, **utils.encodingArgs) hashDigest = utils.md5(bEncodedData).hexdigest() except Exception: return None else: return hashDigest
def sign(params={}): """ 生成兑吧签名 """ params = [(k, params[k]) for k in sorted(params.keys())] raw_str = '' for p in params: raw_str += str(p[1]) return utils.md5(raw_str)
def check_sign_aos(self): """ aos验证签名 """ raw_param = [self.config['ymserver_key']['aos']] keys = ['order', 'app', 'user', 'chn', 'ad', 'points'] for key in keys: value = self.get_argument(key, '') raw_param.append(value) raw_str = '||'.join(raw_param) return utils.md5(raw_str)[12:20]
def getchunks(self): while self.index < len(self.chunks): chunk = self.chunks[self.index] start = chunk['start'] length = chunk['length'] chunkdata = self.data[start : start + length] hash = utils.adler32(chunkdata) + utils.md5(chunkdata) yield { 'index': self.index, 'start': start, 'hash': hash, 'data': chunkdata } self.index += 1
def stream_cipher_encrypt(img_matrix, cipher): cipher = utils.md5(cipher) random.seed(cipher) height, width = img_matrix.shape for i in range(height): for j in range(width): tmp = int(random.random() * 1000 % 256) img_matrix[i, j] = img_matrix[i, j] ^ tmp return img_matrix
def publish(): get = request.form.get return Video.createOrUpdate(id=get('id'), code=get('code'), tags=get('tags'), title=get('title'), params=get('params'), slug=get('slug') or md5(get('code'), True))
def check_sign_aos(self): """ aos验证签名 """ raw_param = [constants.AOS_SERVER_KEY] keys = ['order', 'app', 'user', 'chn', 'ad', 'points'] for key in keys: value = self.get_argument(key, '') raw_param.append(value) raw_str = '||'.join(raw_param) return utils.md5(raw_str)[12:20]
def verify_password(username_or_token,password): con = MysqlCon('users') user = con.query('user','*',username = username_or_token) user_password = user[2] if not user or not verify_pass(md5(password),user_password): con.close() return False con.close() return True
def main(): keys = [(a, b) for a in aa for b in bb] results = frequency_analysis(ciphertext, decrypt, keys) key = results[0][0] plaintext = decrypt(ciphertext, key) solution = md5(plaintext) print(plaintext) print(solution)
def install(request): conn = DBSession() admin=conn.query(User).filter(User.name=='admin').first() if not admin: user=User() user.name='admin' user.name="admin" user.role=0 user.password=md5("xiaokang") conn.add(user) conn.flush() return HTTPFound(location=request.route_url('public_lesson_list'))
def check_sign_waps(self): """ 万普验证签名 """ args = self.request.arguments kv = '' adv_id = args['adv_id'][0] app_id = args['app_id'][0] key = args['key'][0] udid = args['udid'][0] bill = args['bill'][0] points = args['points'][0] order_id = args['order_id'][0] time = args['activate_time'][0] ac_time = {'activate_time':time} encode_time = urllib.urlencode(ac_time)[14:] kv = adv_id + app_id + key + udid + bill + points + encode_time + order_id + self.config['wanpu_key']['ios'] utils.loggers.use('callback', self.log_path).info('[wanpu_before_md5]'+kv) utils.loggers.use('callback', self.log_path).info('[wanpu_md5]'+utils.md5(kv)) return utils.md5(kv)
def main(): """Brute-forcing while using letter frequencies to detect English.""" keys = [(a, b) for a in aa for b in bb] results = frequency_analysis(ciphertext, decrypt, keys) key = results[3][0] # found it was this one by looking at the results plaintext = decrypt(ciphertext, key) solution = md5(plaintext) print(plaintext) print(solution) return results
def sign_encode(data): try: options = get_options() key = options['SIGN_KEY'] # enter_sign = data.split('&sign=')[1] _values = data.split('&sign=')[0] values = utils.urldecode(_values) _values_sort = sorted(values.iteritems(),key=lambda a:a[0],reverse=False) values_sort = urlencode(_values_sort) sign = utils.md5(values_sort+'&key='+key).upper() except: return 0 return sign
def check_sign_ios(self): """ ios验证签名 """ args = self.request.arguments kv = [] for key in args: if key != 'sign': value = args[key][0].decode('utf-8') kv.append('%s=%s' % (key, value)) raw_str = '' for s in sorted(kv): raw_str += s raw_str += constants.IOS_SERVER_KEY return utils.md5(raw_str)
def _hash_function_kwargs(self): ret = [] for k, v in self.dataset.kwargs.iteritems(): if type(v) == FunctionType: ret.append(str(k) + '_' + v.__name__) elif hasattr(v, '__name__'): ret.append(str(k) + '_' + v.__name__ + '_' + str(v)) elif hasattr(v.__class__, '__name__'): ret.append(str(k) + '_' + v.__class__.__name__ + '_' + str(v)) else: ret.append(str(k) + '_' + str(v)) return md5(''.join(ret))
def check_sign_ios(self): """ ios验证签名 """ args = self.request.arguments kv = [] for key in args: if key != 'sign': value = args[key][0].decode('utf-8') kv.append('%s=%s' % (key, value)) raw_str = '' for s in sorted(kv): raw_str += s raw_str += self.config['ymserver_key']['ios'] return utils.md5(raw_str)
def login(): reader = codecs.getreader("utf-8") data = json.load(reader(request.body)) email=data['email'] userPass=utils.md5(data['userPass']) sql="select * from User where email='%s' and userPass='******'" %(email, userPass) #return sql response={} result=mysql.query(sql,1) if result: response['status']="login successful" else: response['status']="wrong password or username" return response
def post(self): error = None try: upload = self.get_uploads()[0] email_hash = md5(self.user.email) avatar = Avatar.get_by_id(email_hash) if not avatar: avatar = Avatar.create(email_hash, avatar=upload.key()) else: avatar.avatar = upload.key() avatar.put() except: error = 'Error occurred during file upload' finally: self.redirect_to('dashboard', **({'error': error} if error else {}))