Example #1
0
        /// <summary>
        /// 设置空缓存
        /// </summary>
        /// <param name="secretContext"></param>
        private void SetNullCache(SecretContext secretContext)
        {
            long currentTime = TopUtils.GetCurrentTimeMillis();

            secretContext.InvalidTime    = currentTime + (DEFAULT_INTERVAL * 1000);
            secretContext.MaxInvalidTime = currentTime + (DEFAULT_MAX_INTERVAL * 1000);
        }
Example #2
0
        public string GetSignature()
        {
            //String plain = string.Format("jsapi_ticket={0}&noncestr={1}&timestamp={2}&url={3}", ticket, nonceStr, timeStamp, url);
            string randomStr = DingTalkSignatureUtil.GetRandomStr(10);
            string timeStamp = TopUtils.GetCurrentTimeMillis().ToString();

            Dictionary <string, object> dic = new Dictionary <string, object>();

            dic.Add(Constants.JSAPI_TICKET, _cacheHelper.Get(Constants.JSAPI_TICKET).ToString());
            dic.Add(Constants.NONCESTR, randomStr);
            dic.Add(Constants.TIMESTAMP, timeStamp);
            dic.Add(Constants.URL, AppSettings.Get(Constants.URL));

            _cacheHelper.Add(Constants.NONCESTR, randomStr);
            _cacheHelper.Add(Constants.TIMESTAMP, timeStamp);

            try
            {
                byte[] bytes             = Encoding.UTF8.GetBytes(ConvertDictionaryToString(dic));
                byte[] digest            = SHA1.Create().ComputeHash(bytes);
                string digestBytesString = BitConverter.ToString(digest).Replace("-", "");
                _cacheHelper.Add(Constants.SIGNATURE, digestBytesString.ToLower());
                return(digestBytesString.ToLower());
            }
            catch (Exception e)
            {
                throw;
            }
        }
        /// <summary>
        /// 钉钉加密解密
        /// </summary>
        /// <param name="Msignature"></param>
        /// <param name="Mtimestamp"></param>
        /// <param name="Mnonce"></param>
        /// <param name="MencryptStr"></param>
        public string DingTalkCrypto(string Msignature, string Mtimestamp, string Mnonce, string MencryptStr)
        {
            DingTalkCrypt dingTalk = new DingTalkCrypt(token, aes_key, corpid);
            string PlainText = string.Empty;
            dingTalk.DecryptMsg(Msignature, Mtimestamp, Mnonce, MencryptStr, ref PlainText);
            Hashtable tb = (Hashtable)JsonConvert.DeserializeObject(PlainText, typeof(Hashtable));
            string EventType = tb["EventType"].ToString();
            //switch (EventType)
            //{
            //    default:
            //        break;
            //}

            CallbackEvent(tb);
            string timestamp = TopUtils.GetCurrentTimeMillis().ToString();
            string encrypt = "";
            string signature = "";
            string res = "success";//传递的消息体明文
            dingTalk = new DingTalkCrypt(token, aes_key, corpid);
            dingTalk.EncryptMsg(res, timestamp, Mnonce, ref encrypt, ref signature);
            Hashtable jsonMap = new Hashtable
                {
                    {"msg_signature", signature},
                    {"encrypt", encrypt},
                    {"timeStamp", timestamp},
                    {"nonce", Mnonce}
                };
            string result = JsonConvert.SerializeObject(jsonMap);
            LogHelper.Log("ReceiveCallbackSerivce result: " + result);
            return result;
        }
Example #4
0
        private void DoUploadBiz()
        {
            long uploadTime = TopUtils.GetCurrentTimeMillis() + FlushInterval;

            while (true)
            {
                try
                {
                    Thread.Sleep(SleepTime);
                    IDictionary <string, Counter> appUserCounterMap = SecurityCounter.GetUserCounter(topClient.appKey);
                    if (TopUtils.GetCurrentTimeMillis() >= uploadTime || (appUserCounterMap.Count * 4 > 65536))
                    {
                        StringBuilder counterBuilder = new StringBuilder();
                        IDictionary <string, Counter> cloneAppUserCounter = SecurityCounter.CloneUserCounter(topClient.appKey);
                        SecurityCounter.CleanUserCounter(topClient.appKey);

                        int count = 0;
                        foreach (KeyValuePair <string, Counter> currentPair in cloneAppUserCounter)
                        {
                            Counter counter = currentPair.Value;
                            if (counterBuilder.Length > 0)
                            {
                                counterBuilder.Append(";");
                            }
                            counterBuilder.Append(currentPair.Key);
                            GenerateCounter(counterBuilder, counter);

                            if ((++count) % 100 == 0)
                            {
                                DoUpload(counterBuilder.ToString(), AppUserSecretType);
                                counterBuilder = new StringBuilder();
                            }
                        }
                        if (counterBuilder.Length > 0)
                        {
                            DoUpload(counterBuilder.ToString(), AppUserSecretType);
                            counterBuilder = new StringBuilder();
                        }

                        Counter appCounter = SecurityCounter.GetAppCounter(topClient.appKey);
                        counterBuilder.Append(SecurityCore.GetAppUserSecretCache().Count);
                        GenerateCounter(counterBuilder, appCounter);
                        appCounter.Reset();

                        long uploadInterval = DoUpload(counterBuilder.ToString(), AppSecretType);
                        uploadTime = TopUtils.GetCurrentTimeMillis() + uploadInterval;
                    }
                }
                catch (Exception e)
                {
                    Log.Error(string.Format("flushSecretApiReporter error: {0}", e.Message));
                }
            }
        }
Example #5
0
 public BaseDingTalkService()
 {
     corpid      = AppSettings.Get("corpid");
     corpsecret  = AppSettings.Get("corpsecret");
     agentid     = AppSettings.Get("agentid");
     appkey      = AppSettings.Get("appkey");
     appsecret   = AppSettings.Get("appsecret");
     url         = AppSettings.Get("url");
     registerurl = AppSettings.Get("registerurl");
     timestamp   = TopUtils.GetCurrentTimeMillis().ToString();
     noncestr    = DingTalkSignatureUtil.GetRandomStr(10);
 }
Example #6
0
        /// <summary>
        /// 调用获取秘钥api
        /// </summary>
        /// <param name="session"></param>
        /// <param name="secretVersion"></param>
        /// <returns></returns>
        private SecretContext CallSecretApi(string session, Nullable <Int64> secretVersion)
        {
            // 获取伪随机码
            if (string.IsNullOrEmpty(randomNum))
            {
                throw new ArgumentException("randomNum can`t be empty");
            }

            TopSecretGetRequest request = new TopSecretGetRequest();

            request.RandomNum     = randomNum;
            request.SecretVersion = secretVersion;
            if (streetest)
            {
                request.AddOtherParameter("tb_eagleeyex_t", "1");
            }

            TopSecretGetResponse response;

            if (session != null && session.StartsWith(UNDERLINE))
            {
                string customerUserId = session.Substring(1);
                if (!StringUtil.IsDigits(customerUserId))
                {
                    throw new ArgumentException("session invalid");
                }
                request.CustomerUserId = Convert.ToInt64(customerUserId);
                response = topClient.Execute(request, null);
            }
            else
            {
                response = topClient.Execute(request, session);
            }
            if (!response.IsError)
            {
                IDictionary <string, Object> appConfig = null;
                if (!string.IsNullOrEmpty(response.AppConfig))
                {
                    appConfig = (IDictionary <string, Object>)TopUtils.JsonToObject(response.AppConfig);
                    putAppConfig(appConfig);
                }
                SecretContext secretContext = new SecretContext();
                if (response.Secret != null)
                {
                    long currentTime = TopUtils.GetCurrentTimeMillis();
                    secretContext.InvalidTime    = currentTime + (response.Interval * 1000);
                    secretContext.MaxInvalidTime = (currentTime + (response.MaxInterval * 1000));
                    secretContext.Secret         = Convert.FromBase64String(response.Secret);
                    secretContext.SecretVersion  = response.SecretVersion;
                }
                else
                {
                    if (appConfig != null)
                    {
                        object publishStatus = null;
                        appConfig.TryGetValue(PUBLISH_STATUS, out publishStatus);
                        if (BETA_STATUS.Equals(publishStatus))
                        {
                            // 设置空缓存
                            SetNullCache(secretContext);
                        }
                    }
                }

                PutToCache(session, secretVersion, secretContext);
                return(secretContext);
            }
            else
            {
                // 查找不到历史秘钥
                if ("20005".Equals(response.SubErrCode))
                {
                    SecretContext secretContext = new SecretContext();
                    // 设置空缓存
                    SetNullCache(secretContext);

                    PutToCache(session, secretVersion, secretContext);
                    return(secretContext);
                }
                throw new SecretException(response.ErrCode, response.ErrMsg, response.SubErrCode, response.SubErrMsg);
            }
        }
Example #7
0
 /// <summary>
 /// 容灾,调用api获取秘钥可能会失败,在失败情况下最长有效期
 /// </summary>
 /// <returns></returns>
 public bool IsMaxValid()
 {
     return(MaxInvalidTime > TopUtils.GetCurrentTimeMillis());
 }