def set_secure_cookie(self, name, value: bytes, *, httponly=True, max_age=30): # 一般来说是 UTC # https://stackoverflow.com/questions/16554887/does-pythons-time-time-return-a-timestamp-in-utc timestamp = int(time.time()) # version, utctime, name, value # assert isinatance(value, (str, list, tuple, bytes, int)) to_sign = [1, timestamp, name, value] secret = self.app.options.cookies_secret self.set_cookie(name, create_signed_value(secret, to_sign), max_age=max_age, httponly=httponly)
def test_sign(): timestamp = int(time.clock()) to_sign = [1, timestamp, 'test name', 'test value 中文', {'asd': '测试'}] value = create_signed_value(secret, to_sign) decode_data = decode_signed_value(secret, value) assert decode_data == to_sign # 篡改数据测试 s = _value_decode(base64.b64decode(bytes(value, 'utf-8'))) s[3] = 'test value' val_changed = str(base64.b64encode(_value_encode(s)), 'utf-8') decode_data = decode_signed_value(secret, val_changed) assert decode_data is None