SecurityCore.cs 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411
  1. using System;
  2. using System.Collections.Generic;
  3. using Top.Api.Util;
  4. using System.Threading;
  5. using Top.Api.Report;
  6. namespace Top.Api.Security
  7. {
  8. /// <summary>
  9. /// 加、解密核心类
  10. /// </summary>
  11. public class SecurityCore : SecurityConstants
  12. {
  13. private static readonly ITopLogger Log = Top.Api.Log.Instance;
  14. // 缓存用户单独分配秘钥,需要加同步锁
  15. private static readonly IDictionary<string, SecretContext> AppUserSecretCache = new Dictionary<string, SecretContext>();
  16. private static readonly IDictionary<string, SecretContext> AppSecretCache = new Dictionary<string, SecretContext>();
  17. private static readonly object EmptyObject = new object();
  18. private static readonly object CacheLock = new object();
  19. private static readonly object AppLock = new object();
  20. private static readonly object AsynQueueKeyLock = new object();
  21. private string randomNum;// 伪随机码
  22. private DefaultTopClient topClient;
  23. private static IDictionary<string, object> asynQueueKey = new Dictionary<string, object>();
  24. private static readonly IDictionary<string, IDictionary<string, object>> AllAppConfig = new Dictionary<string, IDictionary<string, object>>();
  25. private bool streetest;
  26. public static IDictionary<string, SecretContext> GetAppUserSecretCache()
  27. {
  28. return AppUserSecretCache;
  29. }
  30. /// <summary>
  31. /// 判断密文是否支持检索
  32. /// </summary>
  33. /// <param name="key"></param>
  34. /// <param name="version"></param>
  35. /// <returns></returns>
  36. public bool IsIndexEncrypt(string key, Nullable<Int64> version)
  37. {
  38. if (version != null && version < 0)
  39. {
  40. key = PREVIOUS + key;
  41. }
  42. else
  43. {
  44. key = CURRENT + key;
  45. }
  46. IDictionary<string, Object> appConfig = getAppConfig();
  47. if (appConfig == null)
  48. {
  49. return false;
  50. }
  51. object encryptType = null;
  52. appConfig.TryGetValue(key, out encryptType);
  53. return INDEX_ENCRYPT_TYPE.Equals(encryptType);
  54. }
  55. private IDictionary<string, Object> getAppConfig()
  56. {
  57. IDictionary<string, Object> appConfig = null;
  58. AllAppConfig.TryGetValue(topClient.appKey, out appConfig);
  59. return appConfig;
  60. }
  61. /// <summary>
  62. /// 获取压缩长度
  63. /// </summary>
  64. /// <returns></returns>
  65. public int GetCompressLen()
  66. {
  67. IDictionary<string, Object> appConfig = getAppConfig();
  68. if (appConfig != null)
  69. {
  70. object compressLen = null;
  71. appConfig.TryGetValue(ENCRYPT_INDEX_COMPRESS_LEN, out compressLen);
  72. if (compressLen != null)
  73. {
  74. return Convert.ToInt32(compressLen);
  75. }
  76. }
  77. return DEFAULT_INDEX_ENCRYPT_COMPRESS_LEN;
  78. }
  79. /// <summary>
  80. /// 获取滑动窗口大小
  81. /// </summary>
  82. /// <returns></returns>
  83. public int GetSlideSize()
  84. {
  85. IDictionary<string, Object> appConfig = getAppConfig();
  86. if (appConfig != null)
  87. {
  88. object encryptSlideSize = null;
  89. appConfig.TryGetValue(ENCRYPT_SLIDE_SIZE, out encryptSlideSize);
  90. if (encryptSlideSize != null)
  91. {
  92. return Convert.ToInt32(encryptSlideSize);
  93. }
  94. }
  95. return DEFAULT_ENCRYPT_SLIDE_SIZE;
  96. }
  97. public SecurityCore(DefaultTopClient topClient, string randomNum, bool streetest)
  98. {
  99. this.streetest = streetest;
  100. this.topClient = topClient;
  101. this.randomNum = randomNum;
  102. // 初始化报表
  103. ApiReporter apiReporter = new ApiReporter();
  104. apiReporter.InitSecret(topClient);
  105. }
  106. public void SetRandomNum(string randomNum)
  107. {
  108. this.randomNum = randomNum;
  109. }
  110. /// <summary>
  111. /// 获取秘钥
  112. /// </summary>
  113. /// <param name="session"></param>
  114. /// <param name="secretVersion"></param>
  115. /// <returns></returns>
  116. public SecretContext GetSecret(string session, Nullable<Int64> secretVersion)
  117. {
  118. SecretContext secretContext = GetSecret(session, GenerateSecretKey(session, secretVersion));
  119. if (secretContext != null)
  120. {
  121. if (secretContext.IsValid())
  122. {
  123. return secretContext;
  124. }
  125. if (secretContext.IsMaxValid())
  126. {
  127. // 异步更新秘钥
  128. AsynUpdateSecret(session, secretVersion);
  129. return secretContext;
  130. }
  131. string cacheKey = GenerateSecretKey(session, secretVersion);
  132. lock (CacheLock)
  133. {
  134. if (session != null)
  135. {
  136. AppUserSecretCache.Remove(cacheKey);
  137. }
  138. else
  139. {
  140. AppSecretCache.Remove(cacheKey);
  141. }
  142. }
  143. // 同步调用获取秘钥
  144. return CallSecretApi(session, secretVersion);
  145. }
  146. else
  147. {
  148. // 同步调用获取秘钥
  149. return CallSecretApi(session, secretVersion);
  150. }
  151. }
  152. private string GenerateSecretKey(string session, Nullable<Int64> secretVersion)
  153. {
  154. if (session == null)
  155. {
  156. return this.topClient.appKey;
  157. }
  158. if (secretVersion == null)
  159. {
  160. return session;
  161. }
  162. return session + "_" + secretVersion;
  163. }
  164. /// <summary>
  165. /// 从本地获取秘钥信息
  166. /// </summary>
  167. /// <param name="session"></param>
  168. /// <param name="cacheKey"></param>
  169. /// <returns></returns>
  170. private SecretContext GetSecret(string session, string cacheKey)
  171. {
  172. SecretContext secretContext;
  173. if (session != null)
  174. {
  175. AppUserSecretCache.TryGetValue(cacheKey, out secretContext);
  176. }
  177. else
  178. {
  179. AppSecretCache.TryGetValue(cacheKey, out secretContext);
  180. }
  181. return secretContext;
  182. }
  183. /// <summary>
  184. /// 调用获取秘钥api
  185. /// </summary>
  186. /// <param name="session"></param>
  187. /// <param name="secretVersion"></param>
  188. /// <returns></returns>
  189. private SecretContext CallSecretApi(string session, Nullable<Int64> secretVersion)
  190. {
  191. // 获取伪随机码
  192. if (string.IsNullOrEmpty(randomNum))
  193. {
  194. throw new ArgumentException("randomNum can`t be empty");
  195. }
  196. TopSecretGetRequest request = new TopSecretGetRequest();
  197. request.RandomNum = randomNum;
  198. request.SecretVersion = secretVersion;
  199. if (streetest)
  200. {
  201. request.AddOtherParameter("tb_eagleeyex_t", "1");
  202. }
  203. TopSecretGetResponse response;
  204. if (session != null && session.StartsWith(UNDERLINE))
  205. {
  206. string customerUserId = session.Substring(1);
  207. if (!StringUtil.IsDigits(customerUserId))
  208. {
  209. throw new ArgumentException("session invalid");
  210. }
  211. request.CustomerUserId = Convert.ToInt64(customerUserId);
  212. response = topClient.Execute(request, null);
  213. }
  214. else
  215. {
  216. response = topClient.Execute(request, session);
  217. }
  218. if (!response.IsError)
  219. {
  220. IDictionary<string, Object> appConfig = null;
  221. if (!string.IsNullOrEmpty(response.AppConfig))
  222. {
  223. appConfig = (IDictionary<string, Object>)TopUtils.JsonToObject(response.AppConfig);
  224. putAppConfig(appConfig);
  225. }
  226. SecretContext secretContext = new SecretContext();
  227. if (response.Secret != null)
  228. {
  229. long currentTime = TopUtils.GetCurrentTimeMillis();
  230. secretContext.InvalidTime = currentTime + (response.Interval * 1000);
  231. secretContext.MaxInvalidTime = (currentTime + (response.MaxInterval * 1000));
  232. secretContext.Secret = Convert.FromBase64String(response.Secret);
  233. secretContext.SecretVersion = response.SecretVersion;
  234. }
  235. else
  236. {
  237. if (appConfig != null)
  238. {
  239. object publishStatus = null;
  240. appConfig.TryGetValue(PUBLISH_STATUS, out publishStatus);
  241. if (BETA_STATUS.Equals(publishStatus))
  242. {
  243. // 设置空缓存
  244. SetNullCache(secretContext);
  245. }
  246. }
  247. }
  248. PutToCache(session, secretVersion, secretContext);
  249. return secretContext;
  250. }
  251. else
  252. {
  253. // 查找不到历史秘钥
  254. if ("20005".Equals(response.SubErrCode))
  255. {
  256. SecretContext secretContext = new SecretContext();
  257. // 设置空缓存
  258. SetNullCache(secretContext);
  259. PutToCache(session, secretVersion, secretContext);
  260. return secretContext;
  261. }
  262. throw new SecretException(response.ErrCode, response.ErrMsg, response.SubErrCode, response.SubErrMsg);
  263. }
  264. }
  265. private void putAppConfig(IDictionary<string, Object> appConfig)
  266. {
  267. lock (AppLock)
  268. {
  269. if (!AllAppConfig.ContainsKey(topClient.appKey))
  270. {
  271. AllAppConfig.Add(topClient.appKey, appConfig);
  272. }
  273. }
  274. }
  275. private void PutToCache(string session, Nullable<Int64> secretVersion, SecretContext secretContext)
  276. {
  277. string cacheKey = GenerateSecretKey(session, secretVersion);
  278. lock (CacheLock)
  279. {
  280. if (session != null)
  281. {
  282. if (AppUserSecretCache.ContainsKey(cacheKey))
  283. {
  284. AppUserSecretCache[cacheKey] = secretContext;
  285. }
  286. else
  287. {
  288. AppUserSecretCache.Add(cacheKey, secretContext);
  289. }
  290. }
  291. else
  292. {
  293. if (AppSecretCache.ContainsKey(cacheKey))
  294. {
  295. AppSecretCache[cacheKey] = secretContext;
  296. }
  297. else
  298. {
  299. AppSecretCache.Add(cacheKey, secretContext);
  300. }
  301. }
  302. }
  303. }
  304. /// <summary>
  305. /// 设置空缓存
  306. /// </summary>
  307. /// <param name="secretContext"></param>
  308. private void SetNullCache(SecretContext secretContext)
  309. {
  310. long currentTime = TopUtils.GetCurrentTimeMillis();
  311. secretContext.InvalidTime = currentTime + (DEFAULT_INTERVAL * 1000);
  312. secretContext.MaxInvalidTime = currentTime + (DEFAULT_MAX_INTERVAL * 1000);
  313. }
  314. /// <summary>
  315. /// 异步更新秘钥
  316. /// </summary>
  317. /// <param name="session"></param>
  318. /// <param name="secretVersion"></param>
  319. private void AsynUpdateSecret(string session, Nullable<Int64> secretVersion)
  320. {
  321. string cacheKey = GenerateSecretKey(session, secretVersion);
  322. lock (AsynQueueKeyLock)
  323. {
  324. // 不需要重复提交秘钥请求
  325. if (asynQueueKey.ContainsKey(cacheKey))
  326. {
  327. return;
  328. }
  329. SecretContext secretContext = GetSecret(session, GenerateSecretKey(session, secretVersion));
  330. if (secretContext != null && secretContext.IsValid())
  331. {
  332. return;
  333. }
  334. asynQueueKey.Add(cacheKey, EmptyObject);
  335. }
  336. WaitCallback secretApiCallback = (state) =>
  337. {
  338. try
  339. {
  340. CallSecretApi(session, secretVersion);
  341. }
  342. catch (Exception e)
  343. {
  344. Log.Error(string.Format("asyn update secret error: {0}", e.Message));
  345. }
  346. finally
  347. {
  348. lock (AsynQueueKeyLock)
  349. {
  350. asynQueueKey.Remove(cacheKey);
  351. }
  352. }
  353. };
  354. try
  355. {
  356. ThreadPool.QueueUserWorkItem(secretApiCallback);
  357. }
  358. catch (Exception e)
  359. {
  360. lock (AsynQueueKeyLock)
  361. {
  362. asynQueueKey.Remove(cacheKey);
  363. }
  364. Log.Error(string.Format("add QueueUserWorkItem error: {0}", e.Message));
  365. }
  366. }
  367. }
  368. }