You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

219 lines
8.1 KiB

  1. using System;
  2. using System.Collections.Generic;
  3. using System.IO;
  4. using System.Linq;
  5. using System.Net;
  6. using System.Net.Http;
  7. using System.Net.Http.Headers;
  8. using System.Security.Cryptography;
  9. using System.Text;
  10. using System.Text.RegularExpressions;
  11. using System.Threading;
  12. using System.Threading.Tasks;
  13. using System.Web;
  14. using System.Web.Http;
  15. namespace QZWebApi.Bus
  16. {
  17. public class TjSignUtil
  18. {
  19. //public static readonly string HospitalId = "6";
  20. //public static readonly string AESKey = "QpD3TQJNBsloXVNg9mmguc9ql5Y09Vb7";
  21. //public static readonly string AESJavaToNetKey = "tkvkfP3UFaV/AyJYnoLTCg==";
  22. public static long Get_Timestamp()
  23. {
  24. var currentTimeMillis = (long)(DateTime.UtcNow - new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc)).TotalMilliseconds;
  25. return currentTimeMillis / 1000L;
  26. }
  27. /// <summary>
  28. ///
  29. /// </summary>
  30. /// <param name="DecryptString"></param>
  31. /// <returns></returns>
  32. public static string GetSignature(string DecryptString)
  33. {
  34. SHA1CryptoServiceProvider sha1 = new SHA1CryptoServiceProvider();
  35. byte[] str1 = Encoding.UTF8.GetBytes(DecryptString);
  36. byte[] str2 = sha1.ComputeHash(str1);
  37. sha1.Clear();
  38. (sha1 as IDisposable).Dispose();
  39. return byteToHexStr(str2);
  40. }
  41. /// <summary>
  42. /// 字节数组转16进制字符串
  43. /// </summary>
  44. /// <param name="bytes"></param>
  45. /// <returns></returns>
  46. public static string byteToHexStr(byte[] bytes)
  47. {
  48. string returnStr = "";
  49. if (bytes != null)
  50. {
  51. for (int i = 0; i < bytes.Length; i++)
  52. {
  53. returnStr += bytes[i].ToString("X2");
  54. }
  55. }
  56. return returnStr;
  57. }
  58. ///// <summary>
  59. ///// 无符号右移, 相当于java里的 value>>>pos
  60. ///// </summary>
  61. ///// <param name="value"></param>
  62. ///// <param name="pos"></param>
  63. ///// <returns></returns>
  64. //public static int RightMove(int value, int pos)
  65. //{
  66. // //移动 0 位时直接返回原值
  67. // if (pos != 0)
  68. // {
  69. // // int.MaxValue = 0x7FFFFFFF 整数最大值
  70. // int mask = int.MaxValue;
  71. // //无符号整数最高位不表示正负但操作数还是有符号的,有符号数右移1位,正数时高位补0,负数时高位补1
  72. // value = value >> 1;
  73. // //和整数最大值进行逻辑与运算,运算后的结果为忽略表示正负值的最高位
  74. // value = value & mask;
  75. // //逻辑运算后的值无符号,对无符号的值直接做右移运算,计算剩下的位
  76. // value = value >> pos - 1;
  77. // }
  78. // return value;
  79. //}
  80. /**
  81. *
  82. * @param timestamp
  83. * @param openid
  84. * @return signature
  85. */
  86. public static string GetSignatureBytoken(string token, string timestamp, string openid)
  87. {
  88. string[] arr = new string[] { token, timestamp, openid };
  89. // 将token、timestamp、openid三个参数进行字典排序
  90. //System.out.println("FF_token:"+WxParamUtil.getToken()+" time:"+timestamp+" id:"+openid);
  91. Array.Sort(arr);
  92. StringBuilder content = new StringBuilder();
  93. for (int i = 0; i < arr.Length; i++)
  94. {
  95. content.Append(arr[i]);
  96. }
  97. //MessageDigest md = null;
  98. string tmpStr = null;
  99. //System.out.println("FF_content:"+content.toString());
  100. try
  101. {
  102. //md = MessageDigest.getInstance("SHA-1");
  103. // 将三个参数字符串拼接成一个字符串进行sha1加密
  104. tmpStr = GetSignature(content.ToString());
  105. }
  106. catch (Exception e)
  107. {
  108. //e.printStackTrace();
  109. }
  110. //System.out.println("FF_Signature:"+tmpStr);
  111. return tmpStr;
  112. }
  113. /// <summary>
  114. /// AES解密
  115. /// </summary>
  116. /// <param name="toDecrypt"></param>
  117. /// <param name="key"></param>
  118. /// <returns></returns>
  119. public static string Decrypt(string toDecrypt, string key)
  120. {
  121. toDecrypt = HexToBase64String(toDecrypt);
  122. byte[] keyArray = Convert.FromBase64String(key); //将TestGenAESByteKey类输出的字符串转为byte数组
  123. byte[] toEncryptArray = Convert.FromBase64String(toDecrypt);
  124. RijndaelManaged rDel = new RijndaelManaged();
  125. rDel.Key = keyArray;
  126. rDel.Mode = CipherMode.ECB; //必须设置为ECB
  127. rDel.Padding = PaddingMode.PKCS7; //必须设置为PKCS7
  128. ICryptoTransform cTransform = rDel.CreateDecryptor();
  129. byte[] resultArray = cTransform.TransformFinalBlock(toEncryptArray, 0, toEncryptArray.Length);
  130. return UTF8Encoding.UTF8.GetString(resultArray);
  131. }
  132. /// <summary>
  133. /// 16进制转Base64
  134. /// </summary>
  135. /// <param name="retrunValue"></param>
  136. /// <returns></returns>
  137. private static string HexToBase64String(string retrunValue)
  138. {
  139. MatchCollection mc = Regex.Matches(retrunValue.ToString(), "[A-F0-9]{2}"); byte[] bytes = new byte[mc.Count]; for (int i = 0; i < mc.Count; i++) { bytes[i] = byte.Parse(mc[i].Value, System.Globalization.NumberStyles.HexNumber); }
  140. return Convert.ToBase64String(bytes);
  141. }
  142. /// <summary>
  143. /// AES加密
  144. /// </summary>
  145. /// <param name="encryptString"></param>
  146. /// <param name="encryptKey"></param>
  147. /// <returns></returns>
  148. public static string AESEncode(string encryptString, string encryptKey)
  149. {
  150. if (string.IsNullOrEmpty(encryptString)) return null;
  151. Byte[] toEncryptArray = Encoding.UTF8.GetBytes(encryptString);
  152. RijndaelManaged rm = new RijndaelManaged
  153. {
  154. Key = Convert.FromBase64String(encryptKey),
  155. Mode = CipherMode.ECB,
  156. Padding = PaddingMode.PKCS7
  157. };
  158. ICryptoTransform cTransform = rm.CreateEncryptor();
  159. Byte[] resultArray = cTransform.TransformFinalBlock(toEncryptArray, 0, toEncryptArray.Length);
  160. //return Convert.ToBase64String(resultArray, 0, resultArray.Length);
  161. return byteToHexStr(resultArray);
  162. }
  163. }
  164. public class FileStreamResult : IHttpActionResult
  165. {
  166. readonly Stream _stream;
  167. readonly string _mediaType;
  168. readonly string _fileName;
  169. public FileStreamResult(Stream stream, string mediaType) : this(stream, mediaType, null) { }
  170. public FileStreamResult(Stream stream, string mediaType, string fileName)
  171. {
  172. _stream = stream;
  173. _mediaType = mediaType;
  174. _fileName = fileName;
  175. }
  176. public Task<HttpResponseMessage> ExecuteAsync(CancellationToken cancellationToken)
  177. {
  178. return Task.FromResult<HttpResponseMessage>(Execute());
  179. }
  180. private HttpResponseMessage Execute()
  181. {
  182. HttpResponseMessage httpResponseMessage = new HttpResponseMessage(HttpStatusCode.OK);
  183. try
  184. {
  185. httpResponseMessage.Content = new StreamContent(_stream);
  186. httpResponseMessage.Content.Headers.ContentType = new MediaTypeHeaderValue(_mediaType);
  187. if (!string.IsNullOrEmpty(_fileName))
  188. {
  189. httpResponseMessage.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment")
  190. {
  191. FileName = HttpUtility.UrlEncode(_fileName, Encoding.UTF8),
  192. };
  193. }
  194. return httpResponseMessage;
  195. }
  196. catch
  197. {
  198. httpResponseMessage.Dispose();
  199. throw;
  200. }
  201. }
  202. }
  203. }