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.

309 lines
10 KiB

2 years ago
  1. using System;
  2. using System.Configuration;
  3. using System.IO;
  4. using System.Security.Cryptography;
  5. using System.Text;
  6. namespace EasyNet
  7. {
  8. /// <summary>
  9. /// 安全處理通用類
  10. /// </summary>
  11. public class SecurityUtil
  12. {
  13. private static readonly char[] constantN = {
  14. '0','1','2','3','4','5','6','7','8','9'
  15. };
  16. private static readonly char[] constantU = {
  17. '0','1','2','3','4','5','6','7','8','9',
  18. 'A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z'
  19. };
  20. private static readonly char[] constantL = {
  21. '0','1','2','3','4','5','6','7','8','9',
  22. 'a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z'
  23. };
  24. private static readonly char[] constantUL = {
  25. '0','1','2','3','4','5','6','7','8','9',
  26. 'a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z',
  27. 'A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z'
  28. };
  29. #region Des
  30. //加密範例
  31. public static string DESEncrypt(string data, string sKey, string sIV)
  32. {
  33. //將key轉成utf8編碼 byte array
  34. var tmpkey = Encoding.UTF8.GetBytes(sKey);
  35. //將iv轉成utf8編碼 byte ayyay
  36. var tmpIV = Encoding.UTF8.GetBytes(sIV);
  37. using (var mD5Provider = new MD5CryptoServiceProvider())
  38. {
  39. var key = mD5Provider.ComputeHash(tmpkey);
  40. var iv = mD5Provider.ComputeHash(tmpIV);
  41. //將data轉成utf8編碼 byte ayyay
  42. var byteData = Encoding.UTF8.GetBytes(data);
  43. //加密
  44. using (var aesProvider = new RijndaelManaged())
  45. {
  46. var aesEncrypt = aesProvider.CreateEncryptor(key, iv);
  47. var result = aesEncrypt.TransformFinalBlock(byteData, 0, byteData.Length);
  48. //轉成base64字串
  49. return Convert.ToBase64String(result);
  50. }
  51. }
  52. }
  53. //解密範例
  54. public static string DESDecrypt(string data, string sKey, string sIV)
  55. {
  56. //將key轉成utf8編碼 byte array
  57. var tmpkey = Encoding.UTF8.GetBytes(sKey);
  58. //將iv轉成utf8編碼 byte array
  59. var tmpIV = Encoding.UTF8.GetBytes(sIV);
  60. using (var mD5Provider = new MD5CryptoServiceProvider())
  61. {
  62. var key = mD5Provider.ComputeHash(tmpkey);
  63. var iv = mD5Provider.ComputeHash(tmpIV);
  64. //將base64字串轉成byte array
  65. var encryptData = Convert.FromBase64String(data);
  66. //解密
  67. using (var aesProvider = new RijndaelManaged())
  68. {
  69. var aesDecrypt = aesProvider.CreateDecryptor(key, iv);
  70. var result = aesDecrypt.TransformFinalBlock(encryptData, 0, encryptData.Length);
  71. //將解密後的內容還原成utf8編碼的字串
  72. return Encoding.UTF8.GetString(result);
  73. }
  74. }
  75. }
  76. #endregion Des
  77. #region md5
  78. /// <summary>
  79. /// 字符串MD5加密
  80. /// </summary>
  81. /// <param name="sData">todo: describe sData parameter on MD5</param>
  82. /// <param name="sLen">todo: describe sLen parameter on MD5</param>
  83. /// <returns>密文</returns>
  84. public static string MD5(string sData, string sLen)
  85. {
  86. if (sLen == "16")
  87. {
  88. using (var md5 = new MD5CryptoServiceProvider())
  89. {
  90. var text16 = BitConverter.ToString(md5.ComputeHash(UTF8Encoding.Default.GetBytes(sData)), 4, 8);
  91. text16 = text16.Replace("-", "");
  92. return text16;
  93. }
  94. }
  95. var bytes = Encoding.Default.GetBytes(sData);
  96. using (var mD5CryptoServiceProvider = new MD5CryptoServiceProvider())
  97. {
  98. bytes = mD5CryptoServiceProvider.ComputeHash(bytes);
  99. var text = "";
  100. var builder = new StringBuilder();
  101. builder.Append(text);
  102. for (int i = 0; i < bytes.Length; i++)
  103. {
  104. builder.Append(bytes[i].ToString("x").PadLeft(2, '0'));
  105. }
  106. text = builder.ToString();
  107. return text;
  108. }
  109. }
  110. #endregion md5
  111. #region Shr256
  112. public static string SHA256(string str)
  113. {
  114. var bytes = Encoding.UTF8.GetBytes(str);
  115. using (var managed = new SHA256Managed())
  116. {
  117. return Convert.ToBase64String(managed.ComputeHash(bytes));
  118. }
  119. }
  120. #endregion Shr256
  121. #region Aes
  122. /// <summary>
  123. /// AES 加密
  124. /// </summary>
  125. /// <param name="Data">明碼字符串</param>
  126. /// <param name="sKey">密匙</param>
  127. /// <param name="sIV">初始化向量</param>
  128. /// <returns>加密字符串</returns>
  129. public static string AESEncrypt(string Data, string sKey, string sIV)
  130. {
  131. try
  132. {
  133. var _data = Encoding.UTF8.GetBytes(Data);
  134. var Key = Encoding.UTF8.GetBytes(sKey);
  135. var tmpIV = Encoding.UTF8.GetBytes(sIV);
  136. var RijndaelAlg = Rijndael.Create();
  137. var memory = new MemoryStream();
  138. using (var cStream = new CryptoStream(memory,
  139. RijndaelAlg.CreateEncryptor(Key, tmpIV),
  140. CryptoStreamMode.Write))
  141. {
  142. try
  143. {
  144. cStream.Write(_data, 0, _data.Length);
  145. cStream.FlushFinalBlock();
  146. return Convert.ToBase64String(memory.ToArray());
  147. }
  148. catch (Exception)
  149. {
  150. throw;
  151. }
  152. finally
  153. {
  154. memory.Close();
  155. cStream.Close();
  156. }
  157. }
  158. }
  159. catch (CryptographicException e)
  160. {
  161. throw new Exception("some reason to rethrow", e);
  162. }
  163. }
  164. /// <summary>
  165. /// AES 解密
  166. /// </summary>
  167. /// <param name="Data">密文</param>
  168. /// <param name="sKey">todo: describe sKey parameter on AESDecrypt</param>
  169. /// <param name="sIV">todo: describe sIV parameter on AESDecrypt</param>
  170. /// <returns>明文</returns>
  171. public static string AESDecrypt(string Data, string sKey, string sIV)
  172. {
  173. try
  174. {
  175. var _data = Encoding.UTF8.GetBytes(Data);
  176. var Key = Encoding.UTF8.GetBytes(sKey);
  177. var tmpIV = Encoding.UTF8.GetBytes(sIV);
  178. var RijndaelAlg = Rijndael.Create();
  179. var memory = new MemoryStream(_data);
  180. using (var cStream = new CryptoStream(memory,
  181. RijndaelAlg.CreateDecryptor(Key, tmpIV),
  182. CryptoStreamMode.Read))
  183. {
  184. string val = null;
  185. try
  186. {
  187. // 明文存储区
  188. using (MemoryStream originalMemory = new MemoryStream())
  189. {
  190. var Buffer = new Byte[1024];
  191. var readBytes = 0;
  192. while ((readBytes = cStream.Read(Buffer, 0, Buffer.Length)) > 0)
  193. {
  194. originalMemory.Write(Buffer, 0, readBytes);
  195. }
  196. val = Encoding.UTF8.GetString(originalMemory.ToArray());
  197. }
  198. }
  199. catch (Exception)
  200. {
  201. throw;
  202. }
  203. finally
  204. {
  205. cStream.Close();
  206. }
  207. return val;
  208. }
  209. }
  210. catch (CryptographicException e)
  211. {
  212. throw new Exception("some reason to rethrow", e);
  213. }
  214. }
  215. #endregion Aes
  216. #region 亂數取值
  217. //Validate Code
  218. public static string GetRandomString(int Stringleng)
  219. {
  220. var k = 0;
  221. var strRd = string.Empty;
  222. var rd = new Random(unchecked((int)DateTime.Now.Ticks));
  223. var builder = new StringBuilder();
  224. builder.Append(strRd);
  225. for (k = 0; k < Stringleng; k++) // 亂數產生驗證文字
  226. {
  227. builder.Append(constantU[rd.Next(35)]);
  228. }
  229. strRd = builder.ToString();
  230. return strRd;
  231. }
  232. /// <summary>
  233. /// 生成亂數碼(純數字)
  234. /// </summary>
  235. /// <param name="iLength">todo: describe iLength parameter on GetRandomNumber</param>
  236. /// <returns></returns>
  237. public static string GetRandomNumber(int iLength = 10)
  238. {
  239. var newRandom = new StringBuilder(iLength);
  240. var rd = new Random();
  241. for (int i = 0; i < iLength; i++)
  242. {
  243. newRandom.Append(constantN[rd.Next(10)]);
  244. }
  245. return newRandom.ToString();
  246. }
  247. /// <summary>
  248. /// 加密
  249. /// </summary>
  250. /// <param name="str"></param>
  251. /// <returns></returns>
  252. public static string Encrypt(string str)
  253. {
  254. var sEncrypt = SecurityUtil.DESEncrypt(str, ConfigurationManager.AppSettings["DefaultCryptionKey"].Trim(), ConfigurationManager.AppSettings["DefaultCryptionIV"].Trim());
  255. return sEncrypt;
  256. }
  257. /// <summary>
  258. /// 解密
  259. /// </summary>
  260. /// <param name="str"></param>
  261. /// <returns></returns>
  262. public static string Decrypt(string str)
  263. {
  264. var sDecrypt = SecurityUtil.DESDecrypt(str, ConfigurationManager.AppSettings["DefaultCryptionKey"].Trim(), ConfigurationManager.AppSettings["DefaultCryptionIV"].Trim());
  265. return sDecrypt;
  266. }
  267. #endregion 亂數取值
  268. }
  269. }