处理 wechat server 推送消息

        :params msg: 加密内容
        :params msg_signature: 消息签名
        :params timestamp: 时间戳
        :params nonce: 随机数
194699
def parse_message(self, msg, msg_signature, timestamp, nonce):
        
        content = self.crypto.decrypt_message(msg, msg_signature, timestamp, nonce)
        message = xmltodict.parse(to_text(content))['xml']
        message_type = message['InfoType'].lower()
        message_class = COMPONENT_MESSAGE_TYPES.get(message_type, ComponentUnknownMessage)
        msg = message_class(message)
        if msg.type == 'component_verify_ticket':
            self.session.set(msg.type, msg.verify_ticket)
        elif msg.type in ('authorized', 'updateauthorized'):
            msg.query_auth_result = self.query_auth(msg.authorization_code)
        return msg
151017
def generate_query_string(self, otp, nonce, timestamp=False, sl=None,
                              timeout=None):
        
        data = [('id', self.client_id),
                ('otp', otp),
                ('nonce', nonce)]

        if timestamp:
            data.append(('timestamp', '1'))

        if sl is not None:
            if sl not in range(0, 101) and sl not in ['fast', 'secure']:
                raise Exception('sl parameter value must be between 0 and '
                                '100 or string "fast" or "secure"')

            data.append(('sl', sl))

        if timeout:
            data.append(('timeout', timeout))

        query_string = urlencode(data)

        if self.key:
            hmac_signature = self.generate_message_signature(query_string)
            hmac_signature = hmac_signature
            query_string += '&h=%s' % (hmac_signature.replace('+', '%2B'))

        return query_string
357372
def sign(self, msg, key):
        
        hasher = hashes.Hash(self.hash_algorithm(), backend=default_backend())
        hasher.update(msg)
        digest = hasher.finalize()
        sig = key.sign(
            digest,
            padding.PSS(
                mgf=padding.MGF1(self.hash_algorithm()),
                salt_length=padding.PSS.MAX_LENGTH),
            utils.Prehashed(self.hash_algorithm()))
        return sig
914534
private void logMqttFly(UnitRequest request, String msgStr) {
        long start = request.getContext().getSentTimestamp();
        LOG.debug(new JSONObject() {{
            put(Constant.COST, System.currentTimeMillis() - start);
            put("type", "mqttFly");//从发出到收到，主要用于监控内网间通信性能
            put("ssid", request.getContext().getSsid());
            put("from", request.getContext().getSourceNodeId());
            put("length", msgStr.length());
            put("msgType", request.getContext().getMessageType());
            put("payload", msgStr);
        }});
    }
1122525
static function get_jsapi_signature($jsapi_ticket, $nonceStr, $timestamp, $url)
    {
        //排序
        try {
            $str = "jsapi_ticket=$jsapi_ticket&noncestr=$nonceStr&timestamp=$timestamp&url=$url";
            return sha1($str);
        } catch (\Exception $e) {
            @error_log('get_jsapi_signature Error: ' . $e->getMessage(), 0);
            return FALSE;
        }
    }
1343284
def verify_request_signature(request: RequestType, public_key: Union[str, bytes]):
    
    key = encode_if_text(public_key)
    date_header = request.headers.get("Date")
    if not date_header:
        raise ValueError("Rquest Date header is missing")

    ts = parse_http_date(date_header)
    dt = datetime.datetime.utcfromtimestamp(ts).replace(tzinfo=pytz.utc)
    delta = datetime.timedelta(seconds=30)
    now = datetime.datetime.utcnow().replace(tzinfo=pytz.utc)
    if dt < now - delta or dt > now + delta:
        raise ValueError("Request Date is too far in future or past")

    HTTPSignatureHeaderAuth.verify(request, key_resolver=lambda **kwargs: key)
1340603
public function signature($url = null, $nonce = null, $timestamp = null)
    {
        $url = $url ? $url : $this->getUrl();
        $nonce = $nonce ? $nonce : uniqid();
        $timestamp = $timestamp ? $timestamp : time();
        $ticket = $this->ticket();
        $sign = [
            'appId' => Yii::$app->wechat->appId,
            'nonceStr' => $nonce,
            'timestamp' => $timestamp,
            'url' => $url,
            'signature' => $this->getSignature($ticket, $nonce, $timestamp, $url),
        ];

        return $sign;
    }
442734
public void queryMessages(final String msgId, final long timestamp, final int limit,
                            final AVIMMessagesQueryCallback callback) {
    if (StringUtil.isEmpty(msgId) && timestamp == 0) {
      this.queryMessages(limit, callback);
      return;
    }
    // 如果屏蔽了本地缓存则全部走网络
    if (!AVIMOptions.getGlobalOptions().isMessageQueryCacheEnabled()) {
      queryMessagesFromServer(msgId, timestamp, limit, null, 0, new AVIMMessagesQueryCallback() {

        @Override
        public void done(List<AVIMMessage> messages, AVIMException e) {
          if (callback != null) {
            if (e != null) {
              callback.internalDone(e);
            } else {
              callback.internalDone(messages, null);
            }
          }
        }
      });
      return;
    }

    // 先去本地缓存查询消息
    storage.getMessage(msgId, timestamp, conversationId,
            new AVIMMessageStorage.StorageMessageCallback() {

              @Override
              public void done(final AVIMMessage indicatorMessage,
                               final boolean isIndicateMessageBreakPoint) {
                if (indicatorMessage == null || isIndicateMessageBreakPoint) {
                  String startMsgId = msgId;
                  long startTS = timestamp;
                  int requestLimit = limit;
                  queryMessagesFromServer(startMsgId, startTS, requestLimit, null, 0,
                          new AVIMMessagesQueryCallback() {
                            @Override
                            public void done(List<AVIMMessage> messages, AVIMException e) {
                              if (e != null) {
                                callback.internalDone(e);
                              } else {
                                List<AVIMMessage> cachedMsgs = new LinkedList<AVIMMessage>();
                                if (indicatorMessage != null) {
                                  // add indicatorMessage to remove breakpoint.
                                  cachedMsgs.add(indicatorMessage);
                                }
                                if (messages != null) {
                                  cachedMsgs.addAll(messages);
                                }
                                processContinuousMessages(cachedMsgs);
                                queryMessagesFromCache(msgId, timestamp, limit, callback);
                              }
                            }
                          });
                } else {
                  // 本地缓存过而且不是breakPoint
                  storage.getMessages(msgId, timestamp, limit, conversationId,
                          new AVIMMessageStorage.StorageQueryCallback() {
                            @Override
                            public void done(List<AVIMMessage> messages, List<Boolean> breakpoints) {
                              processStorageQueryResult(messages, breakpoints, msgId, timestamp, limit,
                                      callback);
                            }
                          });
                }
              }
            });
  }
820193
def verifySignature(self, msg):
        
        if isinstance(msg, self.authnWhitelist):
            return
        if isinstance(msg, Propagate):
            typ = 'propagate'
            req = TxnUtilConfig.client_request_class(**msg.request)
        else:
            typ = ''
            req = msg

        key = None

        if isinstance(req, Request):
            key = req.key

        if not isinstance(req, Mapping):
            req = req.as_dict

        with self.metrics.measure_time(MetricsName.VERIFY_SIGNATURE_TIME):
            identifiers = self.authNr(req).authenticate(req, key=key)

        logger.debug("{} authenticated {} signature on {} request {}".
                     format(self, identifiers, typ, req['reqId']),
                     extra={"cli": True,
                            "tags": ["node-msg-processing"]})
819087
function server(options) {
  status = 'server.started'
  config = _.extend(defaultServerOptions, options)

  open(config.datafile)

  if (config.logToConsole)
    console.log("✔ log to stdout")

  // ws [
  var ServerMessageLog = {}
  var queueMessages = []
  var timer

  function flushMessages(n) {
    queueMessages = _.sortBy(queueMessages, 'time')
    var messages = queueMessages.slice(0, n)
    queueMessages = queueMessages.slice(n)
//    console.log(messages);
    _.each(messages, function (m) {
//      var filename = options.logpath+'/1.log'
//      logString(filename, m.text)
      logMessage(new Date(m.time), m.path, m.data, m.type == 'log' ? '' : m.type)
    })
  }

  console.log("✔ ws server listening on port %d", config.port)

  var wss = new WebSocketServer({port: config.port});

  wss.on('connection', function(ws) {
    ws.on('message', function(m) {
      var message = JSON.parse(m)
      queueMessages.push(message)
      if (queueMessages.length > config.queueMessagesMax)
        flushMessages(config.flushMessagesCount)

      if (timer)
        clearTimeout(timer)
      timer = setTimeout(function () {
        timer = null
        flushMessages(queueMessages.length)
      }, config.serverFlushTimeout)
    })
  })
  // ws ]
}
1146399
def tls_session_update(self, msg_str):
        
        self.tls_session.handshake_messages.append(msg_str)
        self.tls_session.handshake_messages_parsed.append(self)
919440
def check_signature(self, msgbuf, srcSystem, srcComponent):
            ''''''
            if isinstance(msgbuf, array.array):
                msgbuf = msgbuf.tostring()
            timestamp_buf = msgbuf[-12:-6]
            link_id = msgbuf[-13]
            (tlow, thigh) = struct.unpack('<IH', timestamp_buf)
            timestamp = tlow + (thigh<<32)

            # see if the timestamp is acceptable
            stream_key = (link_id,srcSystem,srcComponent)
            if stream_key in self.signing.stream_timestamps:
                if timestamp <= self.signing.stream_timestamps[stream_key]:
                    # reject old timestamp
                    # print('old timestamp')
                    return False
            else:
                # a new stream has appeared. Accept the timestamp if it is at most
                # one minute behind our current timestamp
                if timestamp + 6000*1000 < self.signing.timestamp:
                    # print('bad new stream ', timestamp/(100.0*1000*60*60*24*365), self.signing.timestamp/(100.0*1000*60*60*24*365))
                    return False
                self.signing.stream_timestamps[stream_key] = timestamp
                # print('new stream')

            h = hashlib.new('sha256')
            h.update(self.signing.secret_key)
            h.update(msgbuf[:-6])
            sig1 = str(h.digest())[:6]
            sig2 = str(msgbuf)[-6:]
            if sig1 != sig2:
                # print('sig mismatch')
                return False

            # the timestamp we next send with is the max of the received timestamp and
            # our current timestamp
            self.signing.timestamp = max(self.signing.timestamp, timestamp)
            return True
1158327
def render_message(self):
        
        message = None
        if self.title:
            message = '标题：{0}'.format(self.title)
        if self.message_time:
            message = '{0}\n时间：{1}'.format(message, self.time)
        if message:
            message = '{0}\n内容：{1}'.format(message, self.content)
        else:
            message = self.content
        return message
14469
function UserInfo() {
	//使用者帳號(索引用)
	this.strAccount = "";
	//電子信箱
	this.strEmail = "";
	//信箱通知勾選
	this.bEmailNotify = false;
	//電話資料
	this.strPhone = "";
	//簡訊通知勾選
	this.bSMSNotify = false;
	//使用者名稱(暱稱?)
	this.strUserName = "";
	//語系控制
	this.strLanguages = "";
	//系統保護
	this.bSystemAegis = false;
	//登入次數
	this.iLoginCount = 0;
	//登入時間
	this.iLogin = 0;
	//最後登出時間
	this.iLastLogout = 0;
}
487541
public GetSignatureResponse getSignature(String nonceStr, long timestame, String url) {
        BeanUtil.requireNonNull(url, "请传入当前网页的URL，不包含#及其后面部分");
        GetSignatureResponse response = new GetSignatureResponse();
        String jsApiTicket = this.config.getJsApiTicket();
        String sign;
        try {
            sign = JsApiUtil.sign(jsApiTicket, nonceStr, timestame, url);
        } catch (Exception e) {
            LOG.error("获取签名异常:", e);
            response.setErrcode(ResultType.OTHER_ERROR.getCode().toString());
            response.setErrmsg("获取签名异常");
            return response;
        }
        response.setNoncestr(nonceStr);
        response.setSignature(sign);
        response.setTimestamp(timestame);
        response.setUrl(url);
        response.setErrcode(ResultType.SUCCESS.getCode().toString());
        return response;
    }
1307135
def verify_signature(self, signature, nonce, timestamp, signed_id):
        
        message = "%s%s%s%s" % (self.api_key, nonce, timestamp, signed_id)

        if self._pub_key is None:
            warnings.warn("Skipping RSA signature verification. Please pass public key on class initialization to ensure highest level of security!")
            return True

        try:
            rsa.verify(message.encode('utf-8'), signature, self._pub_key)
        except rsa.VerificationError:
            return False

        return True
258021
def verifyCode(self, sessionId, code):
        

        desc = {
            "name": "SMSVerifyCodeResult",
            "desc": " VerifyCode 返回结果",
            "fields": [{
                "name": "code",
                "type": "Integer",
                "desc": "返回码，200 为正常。"
            }, {
                "name": "success",
                "type": "Boolean",
                "desc": "true 验证成功，false 验证失败。"
            }, {
                "name": "errorMessage",
                "type": "String",
                "desc": "错误信息。"
            }]
        }
        r = self.call_api(
            method=('SMS', 'POST', 'application/x-www-form-urlencoded'),
            action='/verifyCode.json',
            params={"sessionId": sessionId,
                    "code": code})
        return Response(r, desc)