defdecrypt_session(session_data, secret_key): try: app = MockApp(secret_key) si = SecureCookieSessionInterface() s = si.get_signing_serializer(app) return s.loads(session_data) except: returnNone
defencrypt_session(data, secret_key): app = MockApp(secret_key) si = SecureCookieSessionInterface() s = si.get_signing_serializer(app) return s.dumps(data)
deftry_all_keys(session_data, path): secret_keys = [] withopen(path, "r") as f: for line in f: secret_keys.append(line.strip())
for secret_key in secret_keys: data = decrypt_session(session_data, secret_key) if data isnotNone: print(f"Success! The secret key is {secret_key}") print(f"The decrypted session data is {data}") return print("Failed! No valid secret key found")
defmain(): parser = argparse.ArgumentParser(description='Encrypt or decrypt Flask session data') parser.add_argument('-unsign', '--unsign', help='Decrypt session data', default=None) parser.add_argument('-sign', '--sign', help='Encrypt data', default=None) parser.add_argument('-s', '--secret_key', help='Secret key for encryption/decryption', default=None) parser.add_argument('--path', help='Path to a file containing secret keys for decryption', default=None) parser.add_argument('-getdata', help='Get raw data from session', default=None)
args = parser.parse_args()
if args.getdata: raw_data = get_raw_data_from_session(args.getdata) print(f"Raw data in session: {raw_data}") return if args.unsign: if args.path: try_all_keys(args.unsign, args.path) elif args.secret_key: decrypted_data = decrypt_session(args.unsign, args.secret_key) if decrypted_data isnotNone: print(f"Success! Decrypted session data is {decrypted_data}") else: print("Failed! Decryption unsuccessful.") else: print("Please provide either --secret_key or --path option for decryption.") elif args.sign: if args.secret_key: # 将输入字符串转换为一个字典 data_dict = json.loads(args.sign) encrypted_data = encrypt_session(data_dict, args.secret_key) print(f"Encrypted session data: {encrypted_data}") else: print("Please provide --secret_key option for encryption.") else: print("Please provide either -unsign or -sign option.")