EncryptionHelper.cs 34 KB

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