EncryptionHelper.cs 35 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449
  1. using System;
  2. using System.IO;
  3. using System.Text;
  4. using System.Security.Cryptography;
  5. using System.Runtime.InteropServices;
  6. using System.Diagnostics.Metrics;
  7. namespace EasyDevCore.Common.Security
  8. {
  9. /// <summary>
  10. ///
  11. /// </summary>
  12. public enum SymmetricAlgorithmMethod
  13. {
  14. /// <summary>
  15. /// The DES crypto service provider
  16. /// </summary>
  17. DESCryptoServiceProvider,
  18. /// <summary>
  19. /// The rijndael managed
  20. /// </summary>
  21. RijndaelManaged,
  22. /// <summary>
  23. /// The R c2 crypto service provider
  24. /// </summary>
  25. RC2CryptoServiceProvider,
  26. /// <summary>
  27. /// The triple DES crypto service provider
  28. /// </summary>
  29. TripleDESCryptoServiceProvider
  30. }
  31. /// <summary>
  32. ///
  33. /// </summary>
  34. public enum AsymmetricAlgorithmMethod
  35. {
  36. /// <summary>
  37. /// The DSA
  38. /// </summary>
  39. DSA,
  40. /// <summary>
  41. /// The EC diffie hellman
  42. /// </summary>
  43. ECDiffieHellman,
  44. /// <summary>
  45. /// The EC DSA
  46. /// </summary>
  47. ECDsa,
  48. /// <summary>
  49. /// The RSA
  50. /// </summary>
  51. RSA
  52. }
  53. /// <summary>Security Helper</summary>
  54. public sealed class EncryptionHelper
  55. {
  56. #region Private Variables
  57. //Original key to ensure it complex
  58. private static string _KeyStringDump = "1AXDHKDASF932CXK";
  59. #endregion
  60. #region Public Methods
  61. /// <summary>
  62. /// Sets the dump key string - original key to ensure it enough complex.
  63. /// </summary>
  64. /// <param name="dumpKey">The dump key.</param>
  65. public static void SetDumpKeyString(string dumpKey)
  66. {
  67. _KeyStringDump = dumpKey;
  68. }
  69. private static SymmetricAlgorithm GetCryptorServiceProvider(SymmetricAlgorithmMethod algorithm)
  70. {
  71. if(OperatingSystem.IsBrowser())
  72. {
  73. throw new NotSupportedException();
  74. }
  75. switch (algorithm)
  76. {
  77. case SymmetricAlgorithmMethod.DESCryptoServiceProvider:
  78. return DES.Create();
  79. case SymmetricAlgorithmMethod.RC2CryptoServiceProvider:
  80. return RC2.Create();
  81. case SymmetricAlgorithmMethod.RijndaelManaged:
  82. return Aes.Create();
  83. case SymmetricAlgorithmMethod.TripleDESCryptoServiceProvider:
  84. return TripleDES.Create();
  85. default:
  86. throw new NotSupportedException(algorithm.ToString());
  87. }
  88. }
  89. /// <summary>
  90. /// RSAs the generate keys.
  91. /// </summary>
  92. /// <param name="xmlPublicKey">The XML public key.</param>
  93. /// <param name="xmlPrivateKey">The XML private key.</param>
  94. /// <param name="keySize">Size of the key.</param>
  95. public static void RSAGenerateKeys(ref string xmlPublicKey, ref string xmlPrivateKey, int keySize)
  96. {
  97. if (OperatingSystem.IsBrowser())
  98. {
  99. throw new NotSupportedException();
  100. }
  101. using (RSACryptoServiceProvider rsa = new RSACryptoServiceProvider(keySize))
  102. {
  103. xmlPublicKey = rsa.ToXmlString(false);
  104. xmlPrivateKey = rsa.ToXmlString(true);
  105. }
  106. }
  107. /// <summary>
  108. /// RSAs the encrypt data.
  109. /// </summary>
  110. /// <param name="xmlPublicKey">The XML public key.</param>
  111. /// <param name="data">The data.</param>
  112. /// <returns></returns>
  113. public static byte[] RSAEncryptData(string xmlPublicKey, byte[] data)
  114. {
  115. if (OperatingSystem.IsBrowser())
  116. {
  117. throw new NotSupportedException();
  118. }
  119. using (RSACryptoServiceProvider rsa = new RSACryptoServiceProvider())
  120. {
  121. rsa.FromXmlString(xmlPublicKey);
  122. return rsa.Encrypt(data, false);
  123. }
  124. }
  125. /// <summary>
  126. /// RSAs the encrypt string.
  127. /// </summary>
  128. /// <param name="xmlPublicKey">The XML public key.</param>
  129. /// <param name="dataString">The data string.</param>
  130. /// <returns></returns>
  131. public static string RSAEncryptString(string xmlPublicKey, string dataString)
  132. {
  133. string valueEncodeString = string.Empty;
  134. //convert data to byte array
  135. byte[] byteData = Encoding.UTF8.GetBytes(dataString);
  136. byte[] encryptedData = RSAEncryptData(xmlPublicKey, byteData);
  137. //convert to string and Base64 encode
  138. valueEncodeString = Convert.ToBase64String(encryptedData);
  139. return valueEncodeString;
  140. }
  141. /// <summary>
  142. /// RSAs the decrypt data.
  143. /// </summary>
  144. /// <param name="xmlPrivateKey">The XML private key.</param>
  145. /// <param name="data">The data.</param>
  146. /// <returns></returns>
  147. public static byte[] RSADecryptData(string xmlPrivateKey, byte[] data)
  148. {
  149. if (OperatingSystem.IsBrowser())
  150. {
  151. throw new NotSupportedException();
  152. }
  153. using (RSACryptoServiceProvider rsa = new RSACryptoServiceProvider())
  154. {
  155. rsa.FromXmlString(xmlPrivateKey);
  156. return rsa.Decrypt(data, false);
  157. }
  158. }
  159. /// <summary>
  160. /// RSAs the decrypt string.
  161. /// </summary>
  162. /// <param name="xmlPPrivateKey">The XML P private key.</param>
  163. /// <param name="encryptedDataString">The encrypted data string.</param>
  164. /// <returns></returns>
  165. public static string RSADecryptString(string xmlPPrivateKey, string encryptedDataString)
  166. {
  167. //convert data to byte array
  168. byte[] encryptedData = Convert.FromBase64String(encryptedDataString);
  169. byte[] byteData = RSADecryptData(xmlPPrivateKey, encryptedData);
  170. // convert to string
  171. System.Text.Encoding objEncoding = System.Text.Encoding.UTF8;
  172. return objEncoding.GetString(byteData);
  173. }
  174. /// <summary>
  175. /// Encrypts the data.
  176. /// </summary>
  177. /// <param name="keyString">The key string.</param>
  178. /// <param name="algorithm">The algorithm.</param>
  179. /// <param name="data">The data.</param>
  180. /// <returns></returns>
  181. public static byte[] EncryptData(string keyString, SymmetricAlgorithmMethod algorithm, byte[] data)
  182. {
  183. string valueEncodeString = string.Empty;
  184. using (MemoryStream objMemoryStream = new MemoryStream())
  185. {
  186. if ((data.Length > 0) && keyString != string.Empty)
  187. {
  188. //convert key to atleast KeyString.Length characters for complex
  189. if (keyString.Length < _KeyStringDump.Length)
  190. {
  191. keyString += _KeyStringDump.Substring(0, _KeyStringDump.Length - keyString.Length);
  192. }
  193. //create encryption keys
  194. byte[] byteKey = Encoding.UTF8.GetBytes(keyString.Left(8));
  195. byte[] byteVector = Encoding.UTF8.GetBytes(keyString.Right(8));
  196. //encrypt
  197. using (var objCryptor = GetCryptorServiceProvider(algorithm))
  198. {
  199. CryptoStream objCryptoStream = new CryptoStream(objMemoryStream, objCryptor.CreateEncryptor(byteKey, byteVector), CryptoStreamMode.Write);
  200. objCryptoStream.Write(data, 0, data.Length);
  201. objCryptoStream.FlushFinalBlock();
  202. }
  203. }
  204. else
  205. {
  206. objMemoryStream.Write(data, 0, data.Length);
  207. }
  208. return objMemoryStream.ToArray();
  209. }
  210. }
  211. /// <summary>
  212. /// Decrypts the data.
  213. /// </summary>
  214. /// <param name="keyString">The key string.</param>
  215. /// <param name="data">The data.</param>
  216. /// <returns></returns>
  217. public static byte[] DecryptData(string keyString, byte[] data)
  218. {
  219. return DecryptData(keyString, SymmetricAlgorithmMethod.DESCryptoServiceProvider, data);
  220. }
  221. /// <summary>
  222. /// Decrypts the data.
  223. /// </summary>
  224. /// <param name="keyString">The key string.</param>
  225. /// <param name="algorithm">The algorithm.</param>
  226. /// <param name="data">The data.</param>
  227. /// <returns></returns>
  228. public static byte[] DecryptData(string keyString, SymmetricAlgorithmMethod algorithm, byte[] data)
  229. {
  230. using (MemoryStream objMemoryStream = new MemoryStream())
  231. {
  232. if ((data.Length > 0) && keyString != string.Empty)
  233. {
  234. //convert key to atleast KeyString.Length characters for complex
  235. if (keyString.Length < _KeyStringDump.Length)
  236. {
  237. keyString += _KeyStringDump.Substring(0, _KeyStringDump.Length - keyString.Length);
  238. }
  239. //create encryption keys
  240. byte[] byteKey = Encoding.UTF8.GetBytes(keyString.Left(8));
  241. byte[] byteVector = Encoding.UTF8.GetBytes(keyString.Right(8));
  242. // decrypt
  243. using (var objCryptor = GetCryptorServiceProvider(algorithm))
  244. {
  245. CryptoStream objCryptoStream = new CryptoStream(objMemoryStream, objCryptor.CreateDecryptor(byteKey, byteVector), CryptoStreamMode.Write);
  246. objCryptoStream.Write(data, 0, data.Length);
  247. objCryptoStream.FlushFinalBlock();
  248. }
  249. }
  250. else
  251. {
  252. objMemoryStream.Write(data, 0, data.Length);
  253. }
  254. return objMemoryStream.ToArray();
  255. }
  256. }
  257. /// <summary>
  258. /// Encrypts the string.
  259. /// </summary>
  260. /// <param name="keyString">The key string.</param>
  261. /// <param name="dataString">The data string.</param>
  262. /// <returns></returns>
  263. public static string EncryptString(string keyString, string dataString)
  264. {
  265. string valueEncodeString = string.Empty;
  266. if (keyString != string.Empty && dataString != null)
  267. {
  268. //convert key to atleast KeyString.Length characters for complex
  269. if (keyString.Length < _KeyStringDump.Length)
  270. {
  271. keyString += _KeyStringDump.Substring(0, _KeyStringDump.Length - keyString.Length);
  272. }
  273. //create encryption keys
  274. byte[] byteKey = Encoding.UTF8.GetBytes(keyString.Left(8));
  275. byte[] byteVector = Encoding.UTF8.GetBytes(keyString.Right(8));
  276. //convert data to byte array
  277. byte[] byteData = Encoding.UTF8.GetBytes(dataString);
  278. //encrypt
  279. using(var objCryptor = GetCryptorServiceProvider(SymmetricAlgorithmMethod.DESCryptoServiceProvider))
  280. {
  281. MemoryStream objMemoryStream = new MemoryStream();
  282. CryptoStream objCryptoStream = new CryptoStream(objMemoryStream, objCryptor.CreateEncryptor(byteKey, byteVector), CryptoStreamMode.Write);
  283. objCryptoStream.Write(byteData, 0, byteData.Length);
  284. objCryptoStream.FlushFinalBlock();
  285. //convert to string and Base64 encode
  286. valueEncodeString = Convert.ToBase64String(objMemoryStream.ToArray());
  287. }
  288. }
  289. else
  290. {
  291. valueEncodeString = dataString;
  292. }
  293. return valueEncodeString;
  294. }
  295. /// <summary>
  296. /// Decrypts the string.
  297. /// </summary>
  298. /// <param name="keyString">The key string.</param>
  299. /// <param name="dataString">The data string.</param>
  300. /// <returns></returns>
  301. public static string DecryptString(string keyString, string dataString)
  302. {
  303. if (string.IsNullOrWhiteSpace(dataString))
  304. {
  305. return dataString;
  306. }
  307. string valueEncodeString = string.Empty;
  308. if (keyString != string.Empty)
  309. {
  310. //convert key to atleast KeyString.Length characters for complex
  311. if (keyString.Length < _KeyStringDump.Length)
  312. {
  313. keyString += _KeyStringDump.Substring(0, _KeyStringDump.Length - keyString.Length);
  314. }
  315. //create encryption keys
  316. byte[] byteKey = Encoding.UTF8.GetBytes(keyString.Left(8));
  317. byte[] byteVector = Encoding.UTF8.GetBytes(keyString.Right(8));
  318. //convert data to byte array and Base64 decode
  319. byte[] byteData = new byte[dataString.Length];
  320. try
  321. {
  322. byteData = Convert.FromBase64String(dataString);
  323. }
  324. catch // invalid length
  325. {
  326. valueEncodeString = dataString;
  327. }
  328. if (valueEncodeString == string.Empty)
  329. {
  330. try
  331. {
  332. // decrypt
  333. using(var objCryptor = GetCryptorServiceProvider(SymmetricAlgorithmMethod.DESCryptoServiceProvider))
  334. {
  335. MemoryStream objMemoryStream = new MemoryStream();
  336. CryptoStream objCryptoStream = new CryptoStream(objMemoryStream, objCryptor.CreateDecryptor(byteKey, byteVector), CryptoStreamMode.Write);
  337. objCryptoStream.Write(byteData, 0, byteData.Length);
  338. objCryptoStream.FlushFinalBlock();
  339. // convert to string
  340. System.Text.Encoding objEncoding = System.Text.Encoding.UTF8;
  341. valueEncodeString = objEncoding.GetString(objMemoryStream.ToArray());
  342. }
  343. }
  344. catch // decryption error
  345. {
  346. return string.Empty;
  347. }
  348. }
  349. return valueEncodeString;
  350. }
  351. else
  352. {
  353. return dataString;
  354. }
  355. }
  356. /// <summary>
  357. /// Complex Encrypts the string.
  358. /// </summary>
  359. /// <param name="keyString">The key string.</param>
  360. /// <param name="dataString">The data string.</param>
  361. /// <returns></returns>
  362. public static string ComplexEncryptString(string keyString, string dataString)
  363. {
  364. if (string.IsNullOrEmpty(dataString))
  365. {
  366. return string.Empty;
  367. }
  368. if(dataString.IndexOf((char)0) > -1)
  369. {
  370. throw new NotSupportedException($"{nameof(dataString)} contains invalid characters !");
  371. }
  372. Random rand = new Random(DateTime.Now.Millisecond);
  373. int dump = rand.Next(1, 30 - (dataString.Length % 20));
  374. if (dump > 0)
  375. {
  376. string dumpString = string.Empty;
  377. for (int i = 0; i < dump; i++)
  378. {
  379. dumpString += (char)(rand.Next(254) + 1);
  380. }
  381. if ((dumpString.Length + dataString.Length) % 2 == 0)
  382. {
  383. dataString += (char)0 + dumpString;
  384. }
  385. else
  386. {
  387. dataString = dumpString + (char)0 + dataString;
  388. }
  389. }
  390. return EncryptString(keyString, dataString);
  391. }
  392. /// <summary>
  393. /// Complex Decrypts the string.
  394. /// </summary>
  395. /// <param name="keyString">The key string.</param>
  396. /// <param name="dataString">The data string.</param>
  397. /// <returns></returns>
  398. public static string ComplexDecryptString(string keyString, string dataString)
  399. {
  400. if (string.IsNullOrEmpty(dataString))
  401. {
  402. return string.Empty;
  403. }
  404. string decryptString = DecryptString(keyString, dataString);
  405. if (dataString.Length > 0 && decryptString.Length == 0) decryptString = dataString;
  406. int pos = decryptString.IndexOf((char)0);
  407. if (pos > 0)
  408. {
  409. if ((decryptString.Length - 1) % 2 == 0)
  410. {
  411. decryptString = decryptString.Substring(0, pos);
  412. }
  413. else
  414. {
  415. decryptString = decryptString.Substring(pos + 1);
  416. }
  417. }
  418. return decryptString;
  419. }
  420. #endregion
  421. }
  422. }