def verify_cookie(cookey): """ verify that the signature contained in the cookie corresponds to the informations sent by the app (see generate_cookie_info) """ is_correct = False debug("verify_cookie for origin: " + base64_decode(cookey)) cookie_value = request.cookies.get(cookey) if cookie_value: debug("cookie exists for this origin") s = Signer(app.secret_key) expected_cookie_content = \ generate_cookie_info(base64_decode(cookey)) expected_cookie_content = s.get_signature(expected_cookie_content) debug("verify_cookie: " + cookie_value + ", " + expected_cookie_content) if expected_cookie_content == cookie_value: debug('correct cookie') is_correct = True else: debug('incorrect cookie') return is_correct
def decode(cls, session_cookie_value, secret_key=None): """ Decode a Flask cookie """ try: if(secret_key==None): compressed = False payload = session_cookie_value if payload.startswith('.'): compressed = True payload = payload[1:] data = payload.split(".")[0] data = base64_decode(data) if compressed: data = zlib.decompress(data) return data else: app = MockApp(secret_key) si = SecureCookieSessionInterface() s = si.get_signing_serializer(app) return s.loads(session_cookie_value) except Exception as e: return "[Decoding error] {}".format(e) raise e
def decode(cls, session_cookie_value, secret_key=None): """ Decode a Flask cookie """ try: if (secret_key == None): compressed = False payload = session_cookie_value if payload.startswith('.'): compressed = True payload = payload[1:] data = payload.split(".")[0] data = base64_decode(data) if compressed: data = zlib.decompress(data) return data else: app = MockApp(secret_key) si = SecureCookieSessionInterface() s = si.get_signing_serializer(app) return s.loads(session_cookie_value) except Exception as e: return "[Decoding error] {}".format(e) raise e
def get_basic_http_authentication_info(): auth_header = request.headers.get(AUTH_HEADER_NAME) if not auth_header: raise RuntimeError('Request authentication header "{0}" is empty ' 'or missing'.format(AUTH_HEADER_NAME)) auth_header = auth_header.replace(BASIC_AUTH_PREFIX + ' ', '', 1) try: api_key = base64_decode(auth_header) # TODO parse better, with checks and all, this is shaky except TypeError: pass else: api_key_parts = api_key.split(':') if len(api_key_parts) != 2: raise RuntimeError('Invalid {0} header. Header should contain' ' exactly 2 items separated by ":" but ' 'contains {1} item(s)'. format(AUTH_HEADER_NAME, len(api_key_parts))) request_user_id = api_key_parts[0] request_password = api_key_parts[1] if not request_user_id or not request_password: raise RuntimeError('username or password not found on request') return request_user_id, request_password
def to_python(self, value): """ """ try: return ObjectId(base64_decode(value)) except (InvalidId, ValueError, TypeError): raise ValidationError()
def decode(session): # decode session and modify it session = session[1:] # get rid of first dot data = session.split(".")[0] # get data data = zlib.decompress(base64_decode(data)) # decode it data = json.loads(data) return data
def loads(self, s, *args, **kwargs): if '"' not in s and "{" not in s: try: s = base64_decode(s) except: pass return TimedSerializer.loads(self, s, *args, **kwargs)
def decode(value: str) -> dict: """ Flask uses a custom JSON serializer so they can encode other data types. This code is based on theirs, but we cast everything to strings because we don't need them to survive a round trip if we're just decoding them. Source: https://www.kirsle.net/wizards/flask-session.cgi#source :param value: Session cookie string to decode :returns: A dictionary representation of the value which was decoded """ try: compressed = False payload = value if payload.startswith('.'): compressed = True payload = payload[1:] data = payload.split(".")[0] data = base64_decode(data) if compressed: data = zlib.decompress(data) data = data.decode("utf-8") except Exception as e: raise DecodeError( f'Failed to decode cookie, are you sure ' f'this was a Flask session cookie? {e}') def hook(obj): if len(obj) != 1: return obj key, val = next(iter(obj.items())) if key == ' t': return tuple(val) elif key == ' u': return UUID(val) elif key == ' b': return b64decode(val) elif key == ' m': return Markup(val) elif key == ' d': return parse_date(val) return obj try: return json.loads(data, object_hook=hook) except json.JSONDecodeError as e: raise DecodeError( f'Failed to decode cookie, are you sure ' f'this was a Flask session cookie? {e}')
def verify_auth_token(token): s = JSONSerializer(current_app.config['SECRET_KEY']) try: data_object = s.loads(base64_decode(token).decode()) return data_object.get('company'), data_object.get('from'), \ data_object.get('to') except Exception: return None
def verify_token(token, user_group): try: user_dict = serializer.loads(base64_decode(token).decode()) if user_dict["user_group"] != user_group: raise BadTimeSignature("Expected another user type!") return user_dict["id"], user_dict["username"] except BadTimeSignature as e: raise ValueError(str(e))
def decodeCookiePayload(cls, session): start = 1 if session[0] == '.' else 0 session_payload = session[start:].split('.')[0] log.info("Session data: {}".format(session_payload)) decoded_session_payload = base64_decode(session_payload) decompressed_session_payload = zlib.decompress(decoded_session_payload) return decompressed_session_payload
def to_python(self, value): """Object ID converter to Python Returns: ObjectId from the base64 """ try: return ObjectId(base64_decode(value)) except (InvalidId, ValueError, TypeError): raise ValidationError()
def decode(cookie): compressed = False payload = cookie if payload.startswith('.'): compressed = True payload = payload[1:] data = payload.split(".")[0] data = base64_decode(data) if compressed: data = zlib.decompress(data) return data
def load_user_from_request(request): # try to login using the Token in Basic Auth Headers auth_token = request.headers.get('Authorization') if auth_token: auth_token = base64_decode(auth_token.replace('Basic ', '', 1)) user = User.verify_auth_token(auth_token) if user: return user else: api_error(ValueError, "Authorization denied.", 401) # No authentication, no user return None
def decode(self, cookie): if self.session_serializer is None: payload = cookie if payload.startswith('.'): self.compressed = True payload = payload[1:] data = payload.split(".")[0] data = base64_decode(data) if self.compressed: data = zlib.decompress(data) return json.loads(data.decode("utf-8")) else: return self.session_serializer.loads(cookie)
def decrypt_auth_token(token): """ Retrieves information in the access token :param token: The token to decrypt :return: The dictionary containing the id of the logged in user """ try: return Secure.__timed_serializer.loads( base64_decode(token.encode("utf-8"))) except SignatureExpired: raise TokenExpiredError("The token has expired") except: raise TokenError("Invalid Token")
def decode_session_cookie(cookie_data): compressed = False payload = cookie_data if payload.startswith(b'.'): compressed = True payload = payload[1:] data = payload.split(".")[0] data = base64_decode(data) if compressed: data = zlib.decompress(data) return data
def authorize(): """ authorization page GET: returns page where the user can authorize an app to access the filesystem via the webdav server POST: set a cookie """ origin = request.args.get('origin') if request.method == 'POST': response = make_response() debug(request.form.items()) if request.form.get('continue') != 'true': debug('old key was: ' + app.secret_key) generate_key() debug('new key is: ' + app.secret_key) s = Signer(app.secret_key) if s.get_signature(origin) == request.args.get('sig'): key = base64_encode(str(origin)) back = request.args.get('back_url') info = generate_cookie_info(origin=origin) debug('Correct origin, setting cookie with info: ' + info) response.set_cookie(key, value=s.get_signature(info), max_age=None, expires=None, path='/', domain=None, secure=True, httponly=True) else: return 'Something went wrong...' response.status = '301' # moved permanently response.headers['Location'] = '/' if not back else back else: debug(request.args) response = make_response( render_template('authorization_page.html', cookie_list=[ base64_decode(cookey) for cookey in request.cookies.keys() if verify_cookie(cookey) ], origin=request.args.get('origin'), back_url=request.args.get('back_url'))) return response
def reset_password(): token = request.form.get('token') password = request.form.get('password') if not password: flash(_('Please enter a new password')) return render_template('reset_password.html', token=token) try: email = signer.unsign(base64_decode(token), max_age=RESET_PASSWORD_TIMEOUT) except SignatureExpired as e: return render_template('error.html', error=e) hash = pwd_context.encrypt(password) db['users'].update(dict(email=email, hash=hash), ['email']) return render_template('reset_password_success.html')
def decode_session_cookie(cookie_data): import zlib from itsdangerous import base64_decode compressed = False payload = cookie_data if payload.startswith(b'.'): compressed = True payload = payload[1:] data = payload.split(".")[0] data = base64_decode(data) if compressed: data = zlib.decompress(data) return data
def decryption(payload): payload, sig = payload.rsplit('.', 1) payload, timestamp = payload.rsplit('.', 1) decompress = False if payload.startswith('.'): payload = payload[1:] decompress = True try: payload = base64_decode(payload) except Exception as e: raise Exception('Could not base64 decode') if decompress: try: payload = zlib.decompress(payload) except Exception as e: raise Exception('Could not zlib decompress') return session_json_serializer.loads(payload)
def _retrieve_request_credentials(): auth_header = request.headers.get(AUTH_HEADER_NAME) if not auth_header: raise RuntimeError('Request authentication header "{0}" is empty ' "or missing".format(AUTH_HEADER_NAME)) auth_header = auth_header.replace(BASIC_AUTH_PREFIX + " ", "", 1) try: api_key = base64_decode(auth_header) except TypeError: pass else: api_key_parts = api_key.split(":") request_user_id = api_key_parts[0] request_password = api_key_parts[1] if not request_user_id or not request_password: raise RuntimeError("username or password not found on request") return request_user_id, request_password
def decode(cookie: str) -> str: try: compressed = False payload = cookie if payload.startswith('.'): compressed = True payload = payload[1:] data = payload.split(".")[0] data = base64_decode(data) if compressed: data = zlib.decompress(data) return data.decode("utf-8") except Exception as e: return f'[Decoding error: {e}]'
def flask_decode(self, string): """ flask session解码 Description: 通过字符串头部是否包含“.”验证是否数据经过压缩,若有,则解压缩 通过签名对象,直接解码出数据 注意 不设置密钥时只返回解压缩后加密的data Example: >>>Code(key="hello").flask_decode('eyJtb2R1bGUiOnsiIGIiOiJZMjlrWldNPSJ9LCJuYW1lIjp7IiBiIjoiUkVWQlJFWXhVMGhmUTBGVSJ9fQ.X2hcdg.z_SIMDwrUNk0OEedqvrbEEF_fGI') {"name": "DEADF1SH_CAT", "module": "codec"} >>>Codec(key="").flask_decode('eyJtb2R1bGUiOnsiIGIiOiJZMjlrWldNPSJ9LCJzYW5nZm9yIjp7IiBiIjoiVTFKSiJ9fQ.Xfc4bg._sHWpX1GPy0q7qHpJIzqzLDM0TM') {"module":{" b":"Y29kZWM="},"name":{" b":"REVBREYxU0hfQ0FU"}} """ try: session_cookie_value = string if(self.secret_key == None or self.secret_key == ""): compressed = False payload = session_cookie_value #判断payload是否经过压缩 if payload.startswith('.'): compressed = True payload = payload[1:] data = payload.split(".")[0] #解压payload数据 data = base64_decode(data) if compressed: data = zlib.decompress(data) return data else: #验证签名 sign = SecureCookieSessionInterface() serializer = sign.get_signing_serializer(self) result = json.dumps(serializer.loads(session_cookie_value)) return result except AttributeError: raise AttributeError("Secret_key can't be NULL!")
def _retrieve_request_credentials(): auth_header = request.headers.get(AUTH_HEADER_NAME) if not auth_header: raise RuntimeError('Request authentication header "{0}" is empty ' 'or missing'.format(AUTH_HEADER_NAME)) auth_header = auth_header.replace(BASIC_AUTH_PREFIX + ' ', '', 1) try: api_key = base64_decode(auth_header) except TypeError: pass else: api_key_parts = api_key.split(':') request_user_id = api_key_parts[0] request_password = api_key_parts[1] if not request_user_id or not request_password: raise RuntimeError('username or password not found on request') return request_user_id, request_password
def Session(payload): payload, sig = payload.rsplit(b'.', 1) payload, timestamp = payload.rsplit(b'.', 1) decompress = False if payload.startswith(b'.'): payload = payload[1:] decompress = True try: payload = base64_decode(payload) except Exception as e: raise Exception('Could not base64 decode the payload because of ' 'an exception') if decompress: try: payload = zlib.decompress(payload) except Exception as e: raise Exception('Could not zlib decompress the payload before ' 'decoding the payload') return session_json_serializer.loads(payload)
def inner(*args, **kwargs): # 校验session try: compressed = False s = request.cookies.get("session") if s.startswith('.'): compressed = True s = s[1:] d = s.split(".")[0] d = base64_decode(d) if compressed: d = zlib.decompress(d) cookies_d = eval(str(d, "utf-8")) if cookies_d.get("username"): return func(*args, **kwargs) else: return bulid_fail(code=Codes.NOT_LOGIN) except Exception as e: current_app.logger.error("something error: {}".format(e)) return bulid_fail()
def decode(cookie): """Decode a Flask cookie.""" try: compressed = False payload = cookie if payload.startswith(b'.'): compressed = True payload = payload[1:] data = payload.split(".")[0] data = base64_decode(data) if compressed: data = zlib.decompress(data) return flask_loads(data) except Exception, e: print e return "[Decoding error: are you sure this was a Flask session cookie?]"
def flask_cookie_decode(app, cookie): if not app.secret_key: compressed = False payload = cookie if payload.startswith('.'): compressed = True payload = payload[1:] data = payload.split(".")[0] data = base64_decode(data) if compressed: data = zlib.decompress(data) return data else: si = SecureCookieSessionInterface() s = si.get_signing_serializer(app) return s.loads(cookie)
def getAuthToken(request): user_creds = request.headers.get('Authorization') if user_creds: user_creds = base64_decode(user_creds.replace('Basic ', '', 1)) email, pw = user_creds.split(':') if email is None or email is '' or pw is None or pw is '': api_error(ValueError, "Authorization values are missing.", 400) user = User.query.filter_by(email=email).first() if user is None: api_error( ValueError, "We could not find a user with the provided email address.", 404 ) return jsonify(jwt=user.authenticate(pw)) api_error( AttributeError, "Authorization Headers are missing.", 401 )
def get_auth_info_from_request(): user_id = None password = None token = None # TODO remember this is configurable - document app_config = current_app.config auth_header_name = app_config.get('AUTH_HEADER_NAME', AUTH_HEADER_NAME) if auth_header_name: auth_header = request.headers.get(auth_header_name) auth_token_header_name = app_config.get('AUTH_TOKEN_HEADER_NAME', AUTH_TOKEN_HEADER_NAME) if auth_token_header_name: token = request.headers.get(auth_token_header_name) if not auth_header and not token: raise Exception('Authentication information not found on request, ' 'searched for headers: {0}, {1}' .format(auth_header_name, auth_token_header_name)) if auth_header: auth_header = auth_header.replace(BASIC_AUTH_PREFIX + ' ', '', 1) try: from itsdangerous import base64_decode api_key = base64_decode(auth_header) # TODO parse better, with checks and all, this is shaky except TypeError: pass else: api_key_parts = api_key.split(':') user_id = api_key_parts[0] password = api_key_parts[1] auth_info = namedtuple('auth_info_type', ['user_id', 'password', 'token']) return auth_info(user_id, password, token)
def session_cookie_decoder(session_cookie_value): """ Decode a Flask cookie Args: session_cookie_value (string): Flask session cookie to decode """ try: compressed = False payload = session_cookie_value if payload.startswith(b'.'): compressed = True payload = payload[1:] data = payload.split(".")[0] data = base64_decode(data) if compressed: data = zlib.decompress(data) return data except Exception as e: return "[Decoding error]{}".format(e)
def decode(cookie): """ Decode a Flask cookie https://www.kirsle.net/wizards/flask-session.cgi """ try: compressed = False payload = cookie if payload.startswith('.'): compressed = True payload = payload[1:] data = payload.split(".")[0] data = base64_decode(data) if compressed: data = zlib.decompress(data) return data.decode("utf-8") except Exception as e: return f"[Decoding error: are you sure this was a Flask session cookie? {e}]"
def decryption(payload): payload, sig = payload.rsplit(b'.', 1) payload, timestamp = payload.rsplit(b'.', 1) decompress = False if payload.startswith(b'.'): payload = payload[1:] decompress = True try: payload = base64_decode(payload) except Exception as e: raise Exception('Could not base64 decode the payload because of ' 'an exception') if decompress: try: payload = zlib.decompress(payload) except Exception as e: raise Exception('Could not zlib decompress the payload before ' 'decoding the payload') return session_json_serializer.loads(payload)
def load_user_from_request(request): jwt = request.args.get("signed_request") if not jwt: # check authorization header header = request.headers.get("Authorization", "") if header.startswith("JWT "): jwt = header[4:] if jwt: headers_b64, payload_b64, signature = jwt.split(".") payload = json.loads(itsdangerous.base64_decode(payload_b64).decode('utf-8')) oauth_id = payload["iss"] install_info = HipChatInstallInfo.query.filter_by(oauth_id=oauth_id).first() if install_info: serializer = itsdangerous.JSONWebSignatureSerializer(install_info.oauth_secret) try: payload2 = serializer.loads(jwt) except itsdangerous.BadSignature: pass else: hc_user_id = payload2["prn"] hc_user = HipChatUser.query.get(hc_user_id) if not hc_user: hc_user = HipChatUser(id=hc_user_id, group=install_info.group) db.session.add(hc_user) db.session.commit() user = hc_user.user if not user: user = User(hipchat_user=hc_user) db.session.add(user) db.session.commit() # set the login cookie, so that you don't need # the signed_request header anymore for this session login_user(user) return user return None
def get_basic_http_authentication_info(): auth_header = request.headers.get(AUTH_HEADER_NAME) if not auth_header: raise RuntimeError('Request authentication header "{0}" is empty ' 'or missing'.format(AUTH_HEADER_NAME)) auth_header = auth_header.replace(BASIC_AUTH_PREFIX + ' ', '', 1) try: api_key = base64_decode(auth_header) # TODO parse better, with checks and all, this is shaky except TypeError: pass else: api_key_parts = api_key.split(':') if len(api_key_parts) != 2: raise RuntimeError('Invalid {0} header. Header should contain' ' exactly 2 items separated by ":" but ' 'contains {1} item(s)'.format( AUTH_HEADER_NAME, len(api_key_parts))) request_user_id = api_key_parts[0] request_password = api_key_parts[1] if not request_user_id or not request_password: raise RuntimeError('username or password not found on request') return request_user_id, request_password
def to_python(self, value): try: return ObjectId(base64_decode(value)) except (InvalidId, ValueError, TypeError): raise ValidationError()
unpad = lambda s: s[0:-ord("%c" % s[-1])] key = b'1234567890123456' iv = b'1234567890123456' text_lt = b'1234567890' text_eq = b'1234567890abcdef' text_gt = b'1234567890abcdef123456' cipher = AES.new(key, AES.MODE_CBC, IV=iv) data_lt = base64.b64encode(cipher.encrypt(pad(text_lt))) print("原字符串是: %s" % str(text_lt, encoding="utf-8")) print("加密后的字串是: %s" % str(data_lt, encoding="utf-8")) cipher = AES.new(key, AES.MODE_CBC, IV=iv) print("解密后的字串是: %s" % str(unpad(cipher.decrypt(base64_decode(data_lt))), encoding='utf-8')) cipher = AES.new(key, AES.MODE_CBC, IV=iv) data_eq = base64.b64encode(cipher.encrypt(pad(text_eq))) print("原字符串是: %s" % str(text_eq, encoding="utf-8")) print("加密后的字串是: %s" % str(data_eq, encoding="utf-8")) cipher = AES.new(key, AES.MODE_CBC, IV=iv) print("解密后的字串是: %s" % str(unpad(cipher.decrypt(base64_decode(data_eq))), encoding='utf-8')) cipher = AES.new(key, AES.MODE_CBC, IV=iv) data_gt = base64.b64encode(cipher.encrypt(pad(text_gt))) print("原字符串是: %s" % str(text_gt, encoding="utf-8")) print("加密后的字串是: %s" % str(data_gt, encoding="utf-8")) cipher = AES.new(key, AES.MODE_CBC, IV=iv) print("解密后的字串是: %s" %
# conding=uft-8 from Crypto.Cipher import AES from Crypto.PublicKey import RSA as rsa import hashlib, base64, json from itsdangerous import base64_encode, base64_decode obj = AES.new(b'2e8a490fd9745a68d1930aabcacb3a6a', AES.MODE_CBC, b'this is an IV456') PADDING = '\0' pan = lambda s: s + (16 - len(s) % 16) * PADDING message = "abcd" ciphertext = obj.encrypt((pan(message))) data = base64_decode(ciphertext) print(data) # obj2 = AES.new(b'this is a key123',AES.MODE_CBC,b'this is an IV456') # message1 = obj2.decrypt(base64.b64decode(data)) # print (message1) a = sorted('hdsfkdhggh') print(a) md5 = hashlib.md5() md5.update(''.join(a).encode('utf-8')) print(''.join(a).encode('utf-8')) sign_md5 = md5.hexdigest() print(sign_md5) sha1 = hashlib.sha1() sha1.update(''.join(a).encode('utf-8')) print(sha1.hexdigest()) text = sorted("retre4!@") aa = ''.join(text)
def decode(value): return base64_decode(str(value))
def uglyfy(nicetext): "Convert a nice plain text to its original form" return base64_decode(nicetext).decode()
def decodeCookiePayload(payload): if payload[0] == '.': session_payload = payload[1:].split('.')[0] decoded_session_payload = base64_decode(session_payload) decompressed_session_payload = zlib.decompress(decoded_session_payload) print "Extracted decoded uncompressed datas : {} ".format(decompressed_session_payload)
def decode_flask_cookie(cookie): """Decode a Flask cookie.""" data = cookie.split(".")[0] data = base64_decode(data) data = zlib.decompress(data) return data.decode("utf-8")