def interaction(): state = "" exit = False while (exit == False): print("--1. Encrypt a message with Camellia algo\n") print("--2. Encrypt a file with Camellia EBC\n") print("--3. Decrypt a file with Camellia EBC\n") print("--4. Encrypt a file with Camellia CBC\n") print("--5. Decrypt a file with Camellia CBC\n") print("--6. Generate a paire of public/private key\n") print("--7. Diffie-Hellman simulation\n") print("--8. Verification of certification simulation\n") print("--9. MD5 message\n") print("--10. Sponge function with MD5\n") print("--11. Sign the message\n") print("--0. Exit") state = input('what do you want\n') if state == "1": Camellia.Camellia_message() elif state == "2": Camellia.ECB_encry() print("\n\n\n") elif state == "3": Camellia.ECB_decry() print("\n\n\n") elif state == "4": init_vec = 0xffffffffffffffffffffffffffffffff Camellia.CBC_encry(init_vec) print("\n\n\n") elif state == "5": init_vec = 0xffffffffffffffffffffffffffffffff Camellia.CBC_decry(init_vec) print("\n\n\n") elif state == "6": print("Generating...\n") sig.gen_keys() print("\n\n\n") elif state == "7": dh.Diffie_Hellman_sim() elif state == "8": sig.Signature_sim() elif state == "9": Message = input("Type the word to hash\n") print(MD5.md5(Message)) elif state == "10": Message = input("Type the word to hash\n") print(MD5.eponge(Message)) elif state == "11": sig.sign_message() elif state == "0": return 0
def lala(file,newfile): with open(newfile,'w') as nf: with open('%s' % (file), 'r') as ff: for line in ff.readlines(): ls=line.split(",") ip=ls[0] pay_time=ls[1] pay_phone=ls[2] newpay_phone=MD5.md5_data(pay_phone) phone=ls[3] newphone=MD5.md5_data(phone) pay_order_id=ls[4] nf.write("%s,%s,%s,%s,%s"%(ip,pay_time,newpay_phone,newphone,pay_order_id))
def AddFallPic(pic_name: str, device_name: str, content: str = "", id: int = -1): cur = conn.cursor() createdtime = time.strftime("%Y:%m:%d %H:%M:%S", time.localtime()) event_id = MD5.md5(pic_name, str(time.time())) sql = "INSERT INTO notice (event_id,content,device,pic_name,createtime) VALUES ('{}','{}','{}','{}','{}')".format( event_id, content, device_name, pic_name, createdtime) try: Lock.acquire(AddFallPic, "AddFallPic") num = cur.execute(sql) conn.commit() Lock.release() except Exception as e: conn.rollback() cur.close() print("Failed to execute sql:{}|{}".format(sql, e)) log_mysql.error("Failed to execute sql:{}|{}".format(sql, e)) Auto_KeepConnect() # status -200 Execute sql failed sql语句错误 return {"id": id, "status": -200, "message": "Failure to operate database", "data": {}} if num == 1: info_list = GetDevice2PhoneList(device=device_name) for info in info_list: result = Sms.SendFallMessage(info["phone"], info["name"]) sms_status = result["result"] sms_message = result["errmsg"] if sms_message == "OK": sms_message = "Successful" if sms_status != 0: return {"id": id, "status": sms_status, "message": sms_message, "data": {}} # status 0 事件成功处理 return {"id": id, "status": 0, "message": "Successful", "data": {"pic_name": pic_name}} else: # status -200 Execute sql failed sql语句错误 return {"id": id, "status": -200, "message": "Failure to operate database", "data": {}}
def AddDevice(device: str, id: int = -1) -> dict: check_device = CheckDeviceIfExist(device) if check_device == True: # status 101 Duplicate device 重复的设备名称 return {"id": id, "status": 101, "message": "Duplicate device", "data": {}} device_id = MD5.md5(device, "helpaged") cur = conn.cursor() sql = "INSERT INTO devices (device_id,device_name) VALUES ('{}','{}')".format(device_id, device) try: Lock.acquire(AddDevice, "AddDevice") num = cur.execute(sql) conn.commit() Lock.release() except Exception as e: cur.close() print("Failed to execute sql:{}|{}".format(sql, e)) log_mysql.error("Failed to execute sql:{}|{}".format(sql, e)) Auto_KeepConnect() # status -200 Execute sql failed sql语句错误 return {"id": id, "status": -200, "message": "Failure to operate database", "data": {}} cur.close() if num == 1: # status 0 successful 成功处理事件 return {"id": id, "status": 0, "message": "successful", "data": {}} else: # status 100 Failed to add device 添加设备失败 return {"id": id, "status": 100, "message": "Failed to add device", "data": {}}
def file_upload(filename: str, key: str, storageclass: str = 'STANDARD', contentype: str = 'text/html; charset=utf-8') -> str: """ 简单上传·文件流模式,以fp的形式打开文件流读取数据并上传。 :param filename: 要被上传的文件名(完整路径) :param key: 对象键(Key)是对象在存储桶中的唯一标识 :param storageclass: 设置文件的存储类型,STANDARD,STANDARD_IA,默认值:STANDARD :param contentype: 内容类型,设置 Content-Type,默认值:text/html; charset=utf-8 :return 返回被上传的文件的MD5值 """ if online_check() == True: with open(filename, 'rb') as fp: response = client.put_object( Bucket=bucket, # Bucket由bucketname-appid组成 Body=fp, Key=key, StorageClass=storageclass, ContentType=contentype) # print(response['ETag']) return response['ETag'] else: try: with open(filename, 'rb') as fp: file_data = fp.read() with open(os.path.join(Main_filepath, "data", "local", key), "wb") as fp2: fp2.write(file_data) return MD5.md5(file_data, b"") except: return ""
def bytes_upload(body: bytes, key: str) -> str: """ 简单上传·字节流模式,以bytes的形式上传数据 :param bucket: Bucket 名称,由 bucketname-appid 构成 :param body: 文件字节流 :param key: 对象键(Key)是对象在存储桶中的唯一标识 :return: 返回被上传的文件的MD5值 """ if online_check() == True: try: response = client.put_object(Bucket=bucket, Body=body, Key=key) except Exception as e: print(type(e)) log_cos.warning("{}:{}".format(e, type(e))) # 容灾处理,上传失败时先放置在本地。 try: with open(os.path.join(Main_filepath, "data", "local", key), "wb") as fp: fp.write(body) return MD5.md5_bytes(body, b"") except: raise e else: # 容灾处理,本地缓存 try: with open(os.path.join(Main_filepath, "data", "local", key), "wb") as fp: fp.write(body) return MD5.md5_bytes(body, b"") except: pass print(response['ETag']) return response['ETag'] else: try: with open(os.path.join(Main_filepath, "data", "local", key), "wb") as fp: fp.write(body) return MD5.md5_bytes(body, b"") except: raise Exception("<Code>Faild</Code><Message>lalala</Message>", CosServiceError)
def login(): print("点击登录按钮") user, key = login_frame.get_input() # 密码转md5 key = MD5.gen_md5(key) if user == "" or key == "": messagebox.showwarning(title="提示", message="用户名或者密码为空") return print("user: "******", key: " + key) if client.check_user(user, key): # 验证成功 goto_main_frame(user) else: # 验证失败 messagebox.showerror(title="错误", message="用户名或者密码错误")
def sign_message(): message = input("Please input the message to sign\n") print("generating...") [p, g] = FM.gen_prime_set_multi(512) priv_key = random.randint(1, p - 2) pub_key = FM.Expo_rapide(g, priv_key, p) print("public key generated: ", pub_key) print("private key generated: ", priv_key) k = FM.gen_prime(512) while (k > p - 2): k = FM.gen_prime(512) k_reverse = findModReverse(k, p - 1) r = FM.Expo_rapide(g, k, p) s = ((int(MD5.md5(message), 16) - priv_key * r) * k_reverse) % (p - 1) Signature = [r, s] print("Signature: ", Signature)
def Login(phone: str, password: str, enduring: int = 0) -> tuple: """ Login API,return a tuple(status,result string) :param phone: username :param password: with base64 :return: a tuple(status,result string) """ cur = conn.cursor() sql = "SELECT password,salt FROM users WHERE phone = '{}'".format(phone) # print(sql) try: Lock.acquire(Login, "Login") num = cur.execute(sql) # conn.commit() Lock.release() except Exception as e: # conn.rollback() cur.close() print("Failed to execute sql:{}|{}".format(sql, e)) log_mysql.error("Failed to execute sql:{}|{}".format(sql, e)) Auto_KeepConnect() # status -200 sql执行失败 return (-200, "Failure to operate database") if num == 1: row = cur.fetchone() pass_db = row[0] salt = row[1] cur.close() if pass_db == MD5.md5(password, salt): token = AddToken(phone, enduring=enduring) if token == "": # status 300 添加token失败 return (300, "Add token failed") # status 0 执行成功,返回token return (0, token) else: # status 101 账号密码错误 return (101, "Error password") elif num == 0: # status 100 无记录 return (100, "Incorrect user") else: # status 200 记录数量有误 return (200, "Invalid record number")
def getInfo(): # 接受消息 while True: data = ck.recv(1024) # 用于接受服务器发送的信息 key = "569716548" box = RC4.init_box(key) mingwen = RC4.ex_decrypt(data, box) # 解密消息 p = chaifen(mingwen) # 返回一个包含明文和签名的元组 print("拆分出的签名:") print(p[1]) s = p[1] s = s[2:len(s) - 1] #base前两位字符是b' ,所以从第三个字符开始才是签名 s = s.encode(encoding="utf-8") m = MD5.md5(p[0]) # 对明文部分使用md5算法生成摘要 # signal2=KEY.sign(m) v = RSA.Verify(m, s) # 验证签名 judge(v) # 判断安全性 text.insert(tkinter.INSERT, p[0])
def sendMail(): friend = efriend.get() #发给谁 sendStr = esend.get() #发送的消息 #用MD5生成消息摘要 abstract = MD5.md5(sendStr) #用RSA算法对消息摘要进行签名 signal1 = RSA.sign(str(abstract)) #生成消息 message = sendStr + '@' + str(signal1) #用RC4算法对消息进行加密 key = "569716548" box = RC4.init_box(key) cipher = RC4.ex_encrypt(message, box) #发送消息 sendStr = friend + ":" + cipher ck.send(sendStr.encode("utf-8"))
def register_submit(): print("开始注册") user, key, confirm = reg_frame.get_input() if user == "" or key == "" or confirm == "": messagebox.showwarning("错误", "请完整填写注册表单") return if not key == confirm: messagebox.showwarning("错误", "两次密码输入不一致") return # 发送注册请求 result = client.register_user(user, MD5.gen_md5(key)) if result == "0": # 注册成功,跳往登陆界面 messagebox.showinfo("成功", "注册成功") close_reg_window() elif result == "1": # 用户名重复 messagebox.showerror("错误", "该用户名已被注册") elif result == "2": # 未知错误 messagebox.showerror("错误", "发生未知错误")
def ForgetPass(phone: str, password: str, id: int = -1) -> dict: """ 忘记密码,重置密码 :param phone: 用户账号 :param password: 新密码 :param id: 事件请求id :return: json_dict """ cur = conn.cursor() # 生成10位salt salt = "" for i in range(10): # 每循环一次,随机生成一个字母或数字 # 使用ASCII码,A-Z为65-90,a-z为97-122,0-9为48-57,使用chr把生成的ASCII码转换成字符 char1 = random.choice([chr(random.randint(65, 90)), chr(random.randint(48, 57)), chr(random.randint(97, 122))]) salt += char1 pass_db = MD5.md5(password, salt) sql = "UPDATE users SET password = '******',salt = '{}' WHERE phone = '{}'".format(pass_db, salt, phone) try: Lock.acquire(ForgetPass, "ForgetPass") num = cur.execute(sql) conn.commit() Lock.release() except Exception as e: conn.rollback() cur.close() print("Failed to execute sql:{}|{}".format(sql, e)) log_mysql.error("Failed to execute sql:{}|{}".format(sql, e)) Auto_KeepConnect() # status Failure to operate database sql语句错误 return {"id": id, "status": -200, "message": "Failure to operate database", "data": {}} if num == 1: # status 0 执行成功s return {"id": id, "status": 0, "message": "successful", "data": {}} else: # status -200 sql执行失败 return {"id": id, "status": -200, "message": "Failure to operate database", "data": {}}
def md5(data = ''): return MD5.md5(data)
import tasTableau import binomiale import time from collections import defaultdict folder = "../Shakespeare/" '''Q6.12''' a = abr.ABR() start_time = time.time() for f in os.listdir(folder): f = open(folder + f, "r") for line in f: a.insert((MD5.md5(line.rstrip("\n\r")))) print("Temps d'execution = " + str(time.time() - start_time)) m = [] for f in os.listdir(folder): f = open(folder + f, "r") for line in f: if line.rstrip("\n\r") not in m: m.append(line.rstrip("\n\r")) print("Nombre de mots dans l'oeuvre de Shakespeare: " + str(len(m))) '''Q6.13''' ''' d = defaultdict(list) for f in os.listdir(folder):
a = input() plain = read_out_file() #明文 #print(des_encrypt(bin_key, plain))#二进制 bin_cipher = des_encrypt(bin_key, plain) #二进制加密值 print("加密明文中...") a = input() cipher_key = X_n_mod_P(int_key, e, n) plain_key = X_n_mod_P(cipher_key, d, n) print("加密对称密钥:", cipher_key) #这里应该是加密 对称密钥加密和传输信息密文 #检测传输信息是否出错,如果出错,直接 a = input() #print(int_key,plain_key) MAC = MD5(str(cipher_key) + str(bin_cipher)) print("加密'对称密钥加密和传输信息密文'得到的hash值:", MAC) a = input() flag = (MAC == MD5(str(cipher_key) + str(bin_cipher))) print("验证MAC:", flag) if (flag): a = input() cipher = bin_to_str(bin_cipher) bin_key = bin(int_key)[2:] print("解密传输内容:") print(libnum.b2s(des_decrypt(bin_key, cipher))) #还原明文 else: print("传输信息出错,拒绝解密!")
def Md5(e): return MD5(e)
def AddToken(phone: str, enduring: int = 0) -> str: """ Add token in database :param phone: username :return: result string,success return token,failed return void string. """ createdtime = time.strftime("%Y:%m:%d %H:%M:%S", time.localtime()) time_now = int(time.time()) time_expiration = time_now + 10 * 60 token = MD5.md5(phone + str(time_now), "helpaged") cur = conn.cursor() sql = 'INSERT INTO tokens (token,phone,createdtime,expiration,counting,enduring)' \ 'VALUES ("{}","{}","{}",{},{},{})'.format(token, phone, createdtime, time_expiration, 1, enduring) try: Lock.acquire(AddToken, "AddToken") cur.execute(sql) conn.commit() Lock.release() except Exception as e: conn.rollback() cur.close() print("Failed to execute sql:{}|{}".format(sql, e)) log_mysql.error("Failed to execute sql:{}|{}".format(sql, e)) Auto_KeepConnect() return "" # 检查并删除过期的token,不删除长效token sql = "DELETE FROM tokens WHERE expiration < {} AND enduring = 0".format(int(time.time())) # sql = "DELETE FROM tokens WHERE phone = '{}' AND expiration < {}".format(phone,int(time.time())) try: Lock.acquire(AddToken, "AddToken") num = cur.execute(sql) conn.commit() Lock.release() # print("【Thread-Token】Deleted {} tokens".format(num)) except Exception as e: conn.rollback() print("Failed to execute sql:{}|{}".format(sql, e)) log_mysql.error("Failed to execute sql:{}|{}".format(sql, e)) Auto_KeepConnect() # return "" # 检查并删除多余的token sql = "SELECT token FROM tokens WHERE (" \ "SELECT SUM(counting) FROM tokens WHERE phone = '{0}' AND enduring = 0)>10 " \ "AND phone = '{0}' AND enduring = 0 ORDER BY createdtime ASC".format(phone) try: Lock.acquire(AddToken, "AddToken") cur.execute(sql) Lock.release() # conn.commit() except Exception as e: # conn.rollback() cur.close() print("Failed to execute sql:{}|{}".format(sql, e)) log_mysql.error("Failed to execute sql:{}|{}".format(sql, e)) Auto_KeepConnect() return "" data = cur.fetchall() num = len(data) # print("over num:",num) data = data[0:(num - 10)] for row in data: sql = "DELETE FROM tokens WHERE token = '{}'".format(row[0]) try: Lock.acquire(AddToken, "AddToken") cur.execute(sql) conn.commit() Lock.release() except Exception as e: conn.rollback() cur.close() print("Failed to execute sql:{}|{}".format(sql, e)) log_mysql.error("Failed to execute sql:{}|{}".format(sql, e)) Auto_KeepConnect() return "" print("Deleted over-flowing record:{}".format(row[0])) cur.close() # 全部成功返回新token return token
def Register(phone: str, password: str) -> tuple: """ Register API,return a tuple(status,result string) :param phone: username :param password: with MD5 :return: a tuple(status,result string) """ cur = conn.cursor() sql = "SELECT phone FROM users WHERE phone='{}'".format(phone) try: Lock.acquire(Register, "Register") num = cur.execute(sql) Lock.release() # print("INSERT:",num) # conn.commit() except Exception as e: # conn.rollback() cur.close() print("Failed to execute sql:{}|{}".format(sql, e)) log_mysql.error("Failed to execute sql:{}|{}".format(sql, e)) Auto_KeepConnect() # status -200 sql执行失败 return (-200, "Failure to operate database") if num > 0: # status 101 手机号已存在 return (101, "Phone number existed") createdtime = time.strftime("%Y:%m:%d %H:%M:%S", time.localtime()) # 生成10位salt salt = "" for i in range(10): # 每循环一次,随机生成一个字母或数字 # 使用ASCII码,A-Z为65-90,a-z为97-122,0-9为48-57,使用chr把生成的ASCII码转换成字符 char1 = random.choice([chr(random.randint(65, 90)), chr(random.randint(48, 57)), chr(random.randint(97, 122))]) salt += char1 pass_db = MD5.md5(password, salt) sql = "INSERT INTO users (phone,password,createdtime,`group`,salt) " \ "VALUES ('{}','{}','{}','__NORMAL__','{}')".format(phone, pass_db, createdtime, salt) # print(sql) try: Lock.acquire(Register, "Register") num = cur.execute(sql) conn.commit() Lock.release() except Exception as e: conn.rollback() cur.close() print("Failed to execute sql:{}|{}".format(sql, e)) log_mysql.error("Failed to execute sql:{}|{}".format(sql, e)) Auto_KeepConnect() # status -200 sql执行失败 return (-200, "Failure to operate database") if num == 1: ## 创建userinfo表 sql = "INSERT INTO usersinfo (phone,`level`) VALUES ('{}',1)".format(phone) # print(sql) try: Lock.acquire(Register, "Register") num2 = cur.execute(sql) # print("INSERT:",num) conn.commit() Lock.release() except Exception as e: conn.rollback() cur.close() print("Failed to execute sql:{}|{}".format(sql, e)) log_mysql.error("Failed to execute sql:{}|{}".format(sql, e)) Auto_KeepConnect() # status -200 sql执行失败 return (-200, "Failure to operate database") cur.close() if num2 == 1: # status 0 执行成功,返回token return (0, "Successful") elif num2 == 0: # status 102 创建用户信息失败 return (102, "Incorrect user information") else: # status 200 记录数量有误 return (200, "Invalid record number") elif num == 0: cur.close() # status 100 无记录 return (101, "Incorrect user data") else: cur.close() # status 200 记录数量有误 return (200, "Invalid record number ")
def Signature_sim(): #global known parameters: p, g [p, g] = FM.gen_prime_set_multi(512) print("p: ", p) print("g: ", g) # p = 18949989762814550689665544419568283713542842550147948035871102421985313794580994094215156236872009333105224488587695869229596754776136431853972927455905747 # g = 2 priv_key_certif = random.randint(1, p - 2) pub_key_certif = FM.Expo_rapide(g, priv_key_certif, p) priv_key_site = random.randint(1, p - 2) pub_key_site = FM.Expo_rapide(g, priv_key_site, p) priv_key_user = random.randint(1, p - 2) pub_key_user = FM.Expo_rapide(g, priv_key_user, p) print("CA public key: ", pub_key_certif) print("\n") print("CA private key: ", priv_key_certif) print("\n") print("Site public key: ", pub_key_site) print("\n") print("Site private key: ", priv_key_site) print("\n") #Certificateur signs the public key of site with its own private key(priv_key_certif) k = FM.gen_prime(512) while (k > p - 2): k = FM.gen_prime(512) k_reverse = findModReverse(k, p - 1) r = FM.Expo_rapide(g, k, p) s = ((int(MD5.md5(str(pub_key_site)), 16) - priv_key_certif * r) * k_reverse) % (p - 1) Signature = [r, s] print("CA signes the public key of site with CA's Private key") print("Certification: ", Signature) print("\n") # print(pub_key_site) # print(str(pub_key_site)) # print(md5(str(pub_key_site))) # print(hex(int(md5(str(pub_key_site)), 16))) # signature = [r, s] # #verification of the signature print("Verification of certification") print("\n\n") print("Calculate from public key of site: ", FM.Expo_rapide(g, (int(MD5.md5(str(pub_key_site)), 16)), p)) print("\n") print("Calculate from certification: ", (FM.Expo_rapide(pub_key_certif, r, p) * FM.Expo_rapide(r, s, p)) % p) if ((FM.Expo_rapide(g, (int(MD5.md5(str(pub_key_site)), 16)), p)) == ( (FM.Expo_rapide(pub_key_certif, r, p) * FM.Expo_rapide(r, s, p)) % p)): print("verified") file_write_list = [] file_write_list.append("CA public key: ") file_write_list.append(str(pub_key_certif)) file_write_list.append("\n") file_write_list.append("CA private key: ") file_write_list.append(str(priv_key_certif)) file_write_list.append("\n") file_write_list.append("Site public key: ") file_write_list.append(str(pub_key_site)) file_write_list.append("\n") file_write_list.append("Site private key: ") file_write_list.append(str(priv_key_site)) file_write_list.append("\n") file_write_list.append("Certification: ") file_write_list.append(str(Signature)) file_write_list.append("\n") with open("certificate_file", mode='w') as file: #print("file should write : ",file_write_list) file.write(''.join(file_write_list)) file.close() print("\x1b[6;30;42mCerticicat file successfully created\x1b[0m\n")
def captcha(): data = request.json print(data) # 判断键值对是否存在 try: keys = data.keys() except Exception as e: # status -1 json的key错误。此处id是因为没有进行读取,所以返回默认的-1。 return json.dumps({ "id": -1, "status": -1, "message": "Error JSON key", "data": {} }) # 先获取json里id的值,若不存在,默认值为-1 if "id" in data.keys(): id = data["id"] else: id = -1 # 判断指定所需字段是否存在,若不存在返回status -1 json。 for key in ["type", "subtype", "data"]: if not key in data.keys(): # status -1 json的key错误。 return json.dumps({ "id": id, "status": -1, "message": "Error JSON key", "data": {} }) # 处理json if data["type"] == "img": if data["subtype"] == "generate": data = data["data"] # code,addr = ImgCaptcha.CreatCode() code, b64_data = ImgCaptcha.CreatCode() code = code.lower() # 将所有的验证码转成小写 rand_str = "" for i in range(5): char1 = random.choice([ chr(random.randint(65, 90)), chr(random.randint(48, 57)), chr(random.randint(97, 122)) ]) rand_str += char1 hash = MD5.md5(code, salt=rand_str) result = Redis.AddImgHash(hash) # todo 优化验证机制 if result == False: # status -404 Unkown Error return json.dumps({ "id": id, "status": -404, "message": "Unknown Error", "data": {} }) # status 0 ImgCaptcha生成成功 # return json.dumps({ # "id":id, # "status":0, # "message":"Successful", # "data":{"code":code,"addr":addr,"rand":rand_str} return json.dumps({ "id": id, "status": 0, "message": "Successful", "data": { "imgdata": b64_data, "rand": rand_str } # 改动:将code字段删除 }) elif data["subtype"] == "validate": data = data["data"] for key in data.keys(): if key not in ["hash"]: # status -3 json的value错误。 return json.dumps({ "id": id, "status": -3, "message": "Error data key", "data": {} }) hash = data["hash"] result = Redis.SafeCheck(hash) if result == True: # status 0 校验成功。 return json.dumps({ "id": id, "status": 0, "message": "successful", "data": {} }) elif result == False: # status 100 验证码hash值不匹配(包括验证码过期)。 return json.dumps({ "id": id, "status": 100, "message": "Error captcha hash", "data": {} }) else: # status -404 Unkown Error return json.dumps({ "id": id, "status": -404, "message": "Unknown Error", "data": {} }) else: # status -2 json的value错误。 return json.dumps({ "id": id, "status": -2, "message": "Error JSON value", "data": {} }) elif data["type"] == "sms": if data["subtype"] == "generate": data = data["data"] for key in ["phone"]: # if key not in ["phone","hash"]: if key not in data.keys(): # status -3 Error data key | data_json key错误 return json.dumps({ "id": id, "status": -3, "message": "Error data key", "data": {} }) # hash = data["hash"] # result = Redis.SafeCheck(hash) # if result != 0: # # status -4 json的value错误。 # return json.dumps({"id": id, "status": -4, "message": "Error Hash", "data": {}}) phone = str(data["phone"]) command_type = 1 if "command_type" in data.keys(): command_type = data["command_type"] code = random.randint(10000, 99999) if command_type == 1: result = SmsCaptcha.SendCaptchaCode(phone_number=phone, captcha=code, command_str="注册账号", ext=str(id)) elif command_type == 2: result = SmsCaptcha.SendCaptchaCode(phone_number=phone, captcha=code, command_str="找回密码", ext=str(id)) else: # status -204 Arg's value error 键值对数据错误。 return json.dumps({ "id": id, "status": -204, "message": "Arg's value error", "data": {} }) status = result["result"] message = result["errmsg"] if message == "OK": message = "Successful" rand_str = "" if status == 0: for i in range(5): char1 = random.choice([ chr(random.randint(65, 90)), chr(random.randint(48, 57)), chr(random.randint(97, 122)) ]) rand_str += char1 hash = MD5.md5(code, salt=rand_str) result = Redis.AddSmsHash(hash) if result == False: # status -404 Unkown Error return json.dumps({ "id": id, "status": -404, "message": "Unknown Error", "data": {} }) # status 0 SmsCaptcha生成成功 return json.dumps({ "id": id, "status": status, "message": message, "data": { "rand": rand_str } }) # 改动:将code字段删除 else: # status=result["result"] 遇到错误原样返回腾讯云信息 return json.dumps({ "id": id, "status": status, "message": message, "data": {} }) elif data["subtype"] == "validate": data = data["data"] for key in data.keys(): if key not in ["hash"]: # status -3 json的value错误。 return json.dumps({ "id": id, "status": -3, "message": "Error data key", "data": {} }) hash = data["hash"] result = Redis.SafeCheck(hash) if result == True: # status 0 校验成功。 return json.dumps({ "id": id, "status": 0, "message": "successful", "data": {} }) elif result == False: # status 100 验证码hash值不匹配(包括验证码过期)。 return json.dumps({ "id": id, "status": 100, "message": "Error captcha hash", "data": {} }) else: # status -404 Unkown Error return json.dumps({ "id": id, "status": -404, "message": "Unknown Error", "data": {} }) elif data["subtype"] == "delete": pass else: # status -2 json的value错误。 return json.dumps({ "id": id, "status": -2, "message": "Error JSON value", "data": {} }) else: # status -2 json的value错误。 return json.dumps({ "id": id, "status": -2, "message": "Error JSON value", "data": {} })
def Hash_MD5(): h = MD5.new() h.update(b'Cryptography and Blockchain Technology') print('MD5: ' + h.hexdigest())
def notice(): try: token = request.args["token"] print("token:", token) except Exception as e: print("Missing necessary args") log_main.error("Missing necessary agrs") # status -100 缺少必要的参数 return json.dumps({ "id": -1, "status": -100, "message": "Missing necessary args", "data": {} }) token_check_result, device_name = MySQL.DeviceDoki(token) if token_check_result == False: # status -101 token不正确 return json.dumps({ "id": -1, "status": -104, "message": "Error device_id token", "data": {} }) # 验证身份完成,处理数据 data = request.json # print(data) try: keys = data.keys() except Exception as e: # status -1 json的key错误。此处id是因为没有进行读取,所以返回默认的-1。 return json.dumps({ "id": -1, "status": -1, "message": "Error JSON key", "data": {} }) if "id" in data.keys(): id = data["id"] else: id = -1 # 判断指定所需字段是否存在,若不存在返回status -1 json。 for key in ["type", "subtype", "data"]: if not key in data.keys(): # status -1 json的key错误。 return json.dumps({ "id": id, "status": -1, "message": "Error JSON key", "data": {} }) type = data["type"] subtype = data["subtype"] data = data["data"] # 处理json if type == "notice": if subtype == "upload": for key in ["base64"]: if key not in data.keys(): # status -3 data数据中必需key缺失 return json.dumps({ "id": id, "status": -3, "message": "Error data key", "data": {} }) img_base64 = data["base64"] base64_head_index = img_base64.find(";base64,") if base64_head_index != -1: print("进行了替换") img_base64 = img_base64.partition(";base64,")[2] # print("-------接收到数据-------\n", img_base64, "\n-------数据结构尾-------") if "type" in data.keys(): img_type = data["type"] img_file = base64.b64decode(img_base64) content = "" if "content" in data.keys(): content = data["content"] pic_name = MD5.md5_bytes(img_file) try: COS.bytes_upload(img_file, "fallpic/{}".format(pic_name)) print("Upload fallpic:{} for device:{}".format( pic_name, device_name)) log_main.info("Upload fallpic:{} for device:{}".format( pic_name, device_name)) except Exception as e: print("Failed to Upload fallpic:{} for device:{}".format( pic_name, device_name)) print(e) log_main.error( "Failed to Upload fallpic:{} for device:{}".format( pic_name, device_name)) log_main.error(e) # status -500 COS upload Error return { "id": id, "status": -500, "message": "COS upload Error", "data": {} } json_dict = MySQL.AddFallPic(pic_name=pic_name, device_name=device_name, content=content, id=id) return json.dumps(json_dict) else: # status -2 json的value错误。 return json.dumps({ "id": id, "status": -2, "message": "Error JSON value", "data": {} }) else: # status -2 json的value错误。 return json.dumps({ "id": id, "status": -2, "message": "Error JSON value", "data": {} })