def gen_file_tk_l(acc, fn, ul, by_app): """ 生成文件服务器访问token:长字符串 :param acc: 设备id :param fn: 文件名 :param ul: 上传 :param by_app: 数据由app产生 :param share: 是否可被多人访问 """ fn = bs2utf8(fn) if not (acc and isinstance(acc, str)): return 1 if not (fn and isinstance(fn, str)): return 2 share = 1 #是否共享,app产生,主帐号,上传/下载 head = struct.pack('>BB', ((int(share) << 7) | (int(by_app) << 6) | (int(ul) << 5)), len(acc)) rnd = random.randint(0, 126) val = rnd + 1 rnd = struct.pack('>B', rnd) val = rc4_encrypt(struct.pack('>B', val), tk_pwd, None) _ = ''.join((head, acc, struct.pack('>I', int(time.time())), pad(fn, MAX_FILENAME_LEN), rnd, val)) return rc4_encrypt(_, tk_pwd, b2a_hex)
def gen_lvl_fn(share, by_app, acc, fn): """ 生成lvl文件名 :param acc: id和account都可接受 """ if not (acc and isinstance(acc, str) and len(acc) <= 0xff): return None if not (fn and isinstance(fn, str)): return None first = struct.pack('>BB', ((int(share) << 7) | (int(by_app) << 6)), len(acc)) return rc4_encrypt(''.join((first, acc, pad(fn, MAX_FILENAME_LEN))), fn_pwd, b2a_hex)
def ecb_encrypt(text, key): """ encrypt response message @param key: 用来AES(ECB模式)加密的密钥 @param text: 待加密的字符串 """ if not key or not isinstance(key, str): return None if not text or not isinstance(text, str): return None # 对明文做长度padding,必须为16的整数倍 text = pad(text, 16) return binascii.hexlify(AES.new(key, AES.MODE_ECB).encrypt(text))
def gen_ref_l(share, by_app, acc, fn): """ 生成凭据 :param acc: pid或者account:长字符串 """ if not (acc and isinstance(acc, str)): return None if not (fn and isinstance(fn, str)): return None key_cipher = rc4_decrypt(acc, ref_pwd, None) head = struct.pack('>BBB', ((int(share) << 7) | (int(by_app) << 6)), len(acc), len(key_cipher)) _ = ''.join((head, acc, key_cipher, pad(fn, MAX_FILENAME_LEN))) return rc4_encrypt(_, ref_pwd, b2a_hex)
def gen_lvl_fn(share, by_app, acc, fn): """ 生成lvl文件名 :param acc: id和account都可接受 """ if not (acc and isinstance(acc, str) and len(acc) <= 0xff): return None if not (fn and isinstance(fn, str)): return None first = struct.pack('>BB', ((int(share) << 7) | (int(by_app) << 6)), len(acc)) lvl_fn = ''.join((first, acc, pad(fn, MAX_FILENAME_LEN))) md5_inst = md5() md5_inst.update(lvl_fn) return md5_inst.hexdigest()
def encrypt(plain, key, iv, seg_size, seg_ratio=3): """ :param key: aes密钥 :param iv: aes iv :param seg_size: aes段大小,为8的倍数,此处为24,一定程度上优化性能 :param seg_ratio: 冗余参数,仅仅保证tornado设置不出错 """ assert plain and isinstance(plain, str) assert key and isinstance(key, str) and 16 == len(key) assert iv and isinstance(iv, str) and 16 == len(iv) assert seg_size and isinstance(seg_size, int) assert seg_ratio and isinstance(seg_ratio, int) \ and 8 == seg_size / seg_ratio and 0 == seg_size % seg_ratio # padding plain = pad(plain, seg_ratio) return binascii.b2a_hex( AES.new(key, AES.MODE_CFB, iv, segment_size=seg_size).encrypt(plain))