Encrypt.cs 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411
  1. using System.Text;
  2. using System;
  3. using System.Security.Cryptography;
  4. using System.Linq;
  5. using RSAExtensions;
  6. using Microsoft.AspNetCore.DataProtection.KeyManagement;
  7. namespace Business.Core.Utilities
  8. {
  9. /// <summary>
  10. /// 加密操作
  11. /// </summary>
  12. public static class Encrypt
  13. {
  14. #region Md5加密
  15. /// <summary>
  16. /// Md5加密,返回16位结果
  17. /// </summary>
  18. /// <param name="value">值</param>
  19. public static string Md5By16(string value)
  20. {
  21. return Md5By16(value, Encoding.UTF8);
  22. }
  23. /// <summary>
  24. /// Md5加密,返回16位结果
  25. /// </summary>
  26. /// <param name="value">值</param>
  27. /// <param name="encoding">字符编码</param>
  28. public static string Md5By16(string value, Encoding encoding)
  29. {
  30. return Md5(value, encoding, 4, 8);
  31. }
  32. /// <summary>
  33. /// Md5加密
  34. /// </summary>
  35. private static string Md5(string value, Encoding encoding, int? startIndex, int? length)
  36. {
  37. if (string.IsNullOrWhiteSpace(value))
  38. return string.Empty;
  39. var md5 = MD5.Create();
  40. string result;
  41. try
  42. {
  43. var hash = md5.ComputeHash(encoding.GetBytes(value));
  44. result = startIndex == null ? BitConverter.ToString(hash) : BitConverter.ToString(hash, startIndex.SafeValue(), length.SafeValue());
  45. }
  46. finally
  47. {
  48. md5.Clear();
  49. }
  50. return result.Replace("-", "");
  51. }
  52. /// <summary>
  53. /// Md5加密,返回32位结果
  54. /// </summary>
  55. /// <param name="value">值</param>
  56. public static string Md5By32(string value)
  57. {
  58. return Md5By32(value, Encoding.UTF8);
  59. }
  60. /// <summary>
  61. /// Md5加密,返回32位结果
  62. /// </summary>
  63. /// <param name="value">值</param>
  64. /// <param name="encoding">字符编码</param>
  65. public static string Md5By32(string value, Encoding encoding)
  66. {
  67. return Md5(value, encoding, null, null);
  68. }
  69. #endregion
  70. #region DES加密
  71. /// <summary>
  72. /// DES密钥,24位字符串
  73. /// </summary>
  74. private static string DesKey = "#s^un2ye21fcv%|f0XpR,+vh";
  75. /// <summary>
  76. /// DES加密
  77. /// </summary>
  78. /// <param name="value">待加密的值</param>
  79. public static string DesEncrypt(object value)
  80. {
  81. return DesEncrypt(value, DesKey);
  82. }
  83. /// <summary>
  84. /// DES加密
  85. /// </summary>
  86. /// <param name="value">待加密的值</param>
  87. /// <param name="key">密钥,24位</param>
  88. /// <param name="encoding">编码</param>
  89. /// <param name="cipherMode">加密模式</param>
  90. /// <param name="paddingMode">填充模式</param>
  91. public static string DesEncrypt(object value, string key, Encoding? encoding = null, CipherMode cipherMode = CipherMode.ECB, PaddingMode paddingMode = PaddingMode.PKCS7)
  92. {
  93. string text = value.SafeString();
  94. if (ValidateDes(text, key) == false)
  95. return string.Empty;
  96. using var transform = CreateDesProvider(key, cipherMode, paddingMode).CreateEncryptor();
  97. return GetEncryptResult(text, encoding, transform);
  98. }
  99. /// <summary>
  100. /// 验证Des加密参数
  101. /// </summary>
  102. private static bool ValidateDes(string text, string key)
  103. {
  104. if (text.IsEmpty() || key.IsEmpty())
  105. return false;
  106. return key.Length == 24;
  107. }
  108. /// <summary>
  109. /// 创建Des加密服务提供程序
  110. /// </summary>
  111. private static TripleDES CreateDesProvider(string key, CipherMode cipherMode, PaddingMode paddingMode)
  112. {
  113. var result = TripleDES.Create();
  114. result.Key = Encoding.ASCII.GetBytes(key);
  115. result.Mode = cipherMode;
  116. result.Padding = paddingMode;
  117. return result;
  118. }
  119. /// <summary>
  120. /// 获取加密结果
  121. /// </summary>
  122. private static string GetEncryptResult(string value, Encoding? encoding, ICryptoTransform transform)
  123. {
  124. encoding ??= Encoding.UTF8;
  125. var bytes = encoding.GetBytes(value);
  126. var result = transform.TransformFinalBlock(bytes, 0, bytes.Length);
  127. return System.Convert.ToBase64String(result);
  128. }
  129. /// <summary>
  130. /// DES解密
  131. /// </summary>
  132. /// <param name="value">加密后的值</param>
  133. public static string DesDecrypt(object value)
  134. {
  135. return DesDecrypt(value, DesKey);
  136. }
  137. /// <summary>
  138. /// DES解密
  139. /// </summary>
  140. /// <param name="value">加密后的值</param>
  141. /// <param name="key">密钥,24位</param>
  142. /// <param name="encoding">编码</param>
  143. /// <param name="cipherMode">加密模式</param>
  144. /// <param name="paddingMode">填充模式</param>
  145. public static string DesDecrypt(object value, string key, Encoding? encoding = null, CipherMode cipherMode = CipherMode.ECB, PaddingMode paddingMode = PaddingMode.PKCS7)
  146. {
  147. string text = value.SafeString();
  148. if (!ValidateDes(text, key))
  149. return string.Empty;
  150. using var transform = CreateDesProvider(key, cipherMode, paddingMode).CreateDecryptor();
  151. return GetDecryptResult(text, encoding, transform);
  152. }
  153. /// <summary>
  154. /// 获取解密结果
  155. /// </summary>
  156. private static string GetDecryptResult(string value, Encoding? encoding, ICryptoTransform transform)
  157. {
  158. encoding ??= Encoding.UTF8;
  159. var bytes = System.Convert.FromBase64String(value);
  160. var result = transform.TransformFinalBlock(bytes, 0, bytes.Length);
  161. return encoding.GetString(result);
  162. }
  163. #endregion
  164. #region AES加密
  165. /// <summary>
  166. /// 128位0向量
  167. /// </summary>
  168. private static byte[] _iv;
  169. /// <summary>
  170. /// 128位0向量
  171. /// </summary>
  172. private static byte[] Iv
  173. {
  174. get
  175. {
  176. if (_iv == null)
  177. {
  178. var size = 16;
  179. _iv = new byte[size];
  180. for (int i = 0; i < size; i++)
  181. _iv[i] = 0;
  182. }
  183. return _iv;
  184. }
  185. }
  186. /// <summary>
  187. /// AES密钥
  188. /// </summary>
  189. private static string AesKey = "QaP1AF8utIarcBqdhYTZpVGbiNQ9M6IL";
  190. /// <summary>
  191. /// AES加密
  192. /// </summary>
  193. /// <param name="value">待加密的值</param>
  194. public static string AesEncrypt(string value)
  195. {
  196. return AesEncrypt(value, AesKey);
  197. }
  198. /// <summary>
  199. /// AES加密
  200. /// </summary>
  201. /// <param name="value">待加密的值</param>
  202. /// <param name="key">密钥</param>
  203. /// <param name="encoding">编码</param>
  204. /// <param name="cipherMode">加密模式</param>
  205. /// <param name="paddingMode">填充模式</param>
  206. /// <param name="iv">初始化向量</param>
  207. public static string AesEncrypt(string value, string key, Encoding? encoding = null, CipherMode cipherMode = CipherMode.CBC, PaddingMode paddingMode = PaddingMode.PKCS7, byte[]? iv = null)
  208. {
  209. if (value.IsEmpty() || key.IsEmpty())
  210. return string.Empty;
  211. iv ??= Iv;
  212. var aes = CreateAes(key, cipherMode, paddingMode, iv);
  213. using var transform = aes.CreateEncryptor(aes.Key, aes.IV);
  214. return GetEncryptResult(value, encoding, transform);
  215. }
  216. /// <summary>
  217. /// 创建Aes
  218. /// </summary>
  219. private static Aes CreateAes(string key, CipherMode cipherMode, PaddingMode paddingMode, byte[] iv)
  220. {
  221. var result = Aes.Create();
  222. result.Key = Encoding.ASCII.GetBytes(key);
  223. result.Mode = cipherMode;
  224. result.Padding = paddingMode;
  225. result.IV = iv;
  226. return result;
  227. }
  228. /// <summary>
  229. /// AES解密
  230. /// </summary>
  231. /// <param name="value">加密后的值</param>
  232. public static string AesDecrypt(string value)
  233. {
  234. return AesDecrypt(value, AesKey);
  235. }
  236. /// <summary>
  237. /// AES解密
  238. /// </summary>
  239. /// <param name="value">加密后的值</param>
  240. /// <param name="key">密钥</param>
  241. /// <param name="encoding">编码</param>
  242. /// <param name="cipherMode">加密模式</param>
  243. /// <param name="paddingMode">填充模式</param>
  244. /// <param name="iv">初始化向量</param>
  245. public static string AesDecrypt(string value, string key, Encoding? encoding = null, CipherMode cipherMode = CipherMode.CBC, PaddingMode paddingMode = PaddingMode.PKCS7, byte[]? iv = null)
  246. {
  247. if (value.IsEmpty() || key.IsEmpty())
  248. return string.Empty;
  249. iv ??= Iv;
  250. var aes = CreateAes(key, cipherMode, paddingMode, iv);
  251. using var transform = aes.CreateDecryptor(aes.Key, aes.IV);
  252. return GetDecryptResult(value, encoding, transform);
  253. }
  254. #endregion
  255. #region HmacSha256加密
  256. /// <summary>
  257. /// HMACSHA256加密
  258. /// </summary>
  259. /// <param name="value">值</param>
  260. /// <param name="key">密钥</param>
  261. /// <param name="encoding">字符编码</param>
  262. public static string HmacSha256(string value, string key, Encoding? encoding = null)
  263. {
  264. if (value.IsEmpty() || key.IsEmpty())
  265. return string.Empty;
  266. encoding ??= Encoding.UTF8;
  267. var sha256 = new HMACSHA256(Encoding.ASCII.GetBytes(key));
  268. var hash = sha256.ComputeHash(encoding.GetBytes(value));
  269. return string.Join("", hash.ToList().Select(t => t.ToString("x2")).ToArray());
  270. }
  271. #endregion
  272. #region RSA加密
  273. /// <summary>
  274. /// RSA签名
  275. /// </summary>
  276. /// <param name="value">待加密的值</param>
  277. /// <param name="privateKey">私钥</param>
  278. /// <param name="encoding">编码</param>
  279. /// <param name="hashAlgorithm">加密算法,默认值: HashAlgorithmName.SHA1</param>
  280. /// <param name="rsaKeyType">Rsa密钥类型,默认值: Pkcs1</param>
  281. public static string RsaSign(string value, string privateKey, Encoding? encoding = null, HashAlgorithmName? hashAlgorithm = null, RSAKeyType rsaKeyType = RSAKeyType.Pkcs1)
  282. {
  283. if (value.IsEmpty() || privateKey.IsEmpty())
  284. return string.Empty;
  285. var rsa = RSA.Create();
  286. ImportPrivateKey(rsa, privateKey, rsaKeyType);
  287. encoding ??= Encoding.UTF8;
  288. hashAlgorithm ??= HashAlgorithmName.SHA1;
  289. var result = rsa.SignData(encoding.GetBytes(value), hashAlgorithm.Value, RSASignaturePadding.Pkcs1);
  290. return System.Convert.ToBase64String(result);
  291. }
  292. /// <summary>
  293. /// 导入私钥
  294. /// </summary>
  295. private static void ImportPrivateKey(RSA rsa, string privateKey, RSAKeyType rsaKeyType)
  296. {
  297. rsa.ImportPrivateKey(rsaKeyType, privateKey);
  298. }
  299. /// <summary>
  300. /// Rsa验签
  301. /// </summary>
  302. /// <param name="value">待验签的值</param>
  303. /// <param name="publicKey">公钥</param>
  304. /// <param name="sign">签名</param>
  305. /// <param name="encoding">编码</param>
  306. /// <param name="hashAlgorithm">加密算法,默认值: HashAlgorithmName.SHA1</param>
  307. public static bool RsaVerify(string value, string publicKey, string sign, Encoding? encoding = null, HashAlgorithmName? hashAlgorithm = null)
  308. {
  309. if (value.IsEmpty() || publicKey.IsEmpty() || sign.IsEmpty())
  310. return false;
  311. var rsa = RSA.Create();
  312. ImportPublicKey(rsa, publicKey);
  313. encoding ??= Encoding.UTF8;
  314. var signData = System.Convert.FromBase64String(sign);
  315. hashAlgorithm ??= HashAlgorithmName.SHA1;
  316. return rsa.VerifyData(encoding.GetBytes(value), signData, hashAlgorithm.Value, RSASignaturePadding.Pkcs1);
  317. }
  318. /// <summary>
  319. /// 导入公钥
  320. /// </summary>
  321. private static void ImportPublicKey(RSA rsa, string publicKey)
  322. {
  323. var key = System.Convert.FromBase64String(publicKey);
  324. rsa.ImportSubjectPublicKeyInfo(key, out _);
  325. }
  326. /// <summary>
  327. /// RSA加密
  328. /// </summary>
  329. /// <param name="value">待加密的值</param>
  330. /// <param name="publicKey">公钥</param>
  331. public static string RsaEncrypt(string value, string publicKey)
  332. {
  333. if (value.IsEmpty() || publicKey.IsEmpty())
  334. return string.Empty;
  335. var rsa = RSA.Create();
  336. ImportPublicKey(rsa, publicKey);
  337. return rsa.EncryptBigData(value, RSAEncryptionPadding.Pkcs1);
  338. }
  339. /// <summary>
  340. /// RSA解密
  341. /// </summary>
  342. /// <param name="value">加密后的值</param>
  343. /// <param name="privateKey">私钥</param>
  344. public static string RsaDecrypt(string value, string privateKey)
  345. {
  346. if (value.IsEmpty() || privateKey.IsEmpty())
  347. return string.Empty;
  348. var rsa = RSA.Create();
  349. ImportPrivateKey(rsa, privateKey, RSAKeyType.Pkcs1);
  350. return rsa.DecryptBigData(value, RSAEncryptionPadding.Pkcs1);
  351. }
  352. /// <summary>
  353. /// 密码解密之后的mongo连接地址
  354. /// </summary>
  355. public static string GetMongoDBConnectionSM4DecryptString(string connectionString)
  356. {
  357. if (connectionString.IndexOf("@") > 0)
  358. {
  359. var strAry = connectionString.Split("@");
  360. var userInfo = strAry[0].Substring(10).Split(new char[1] { ':' });
  361. string userInfoStr = string.Format("{0}:{1}", userInfo[0], AesDecrypt(userInfo[1]));
  362. return string.Format("mongodb://{0}@{1}", userInfoStr, strAry[1]);
  363. }
  364. else
  365. {
  366. return connectionString;
  367. }
  368. }
  369. #endregion
  370. }
  371. }