Posted By

dmilligan on 05/25/11


Tagged

Encryption decryption des


Versions (?)

DataEncryption


 / Published in: C#
 

Class to encrypt and decrypt strings.

  1. public class DataEncryption
  2. {
  3. #region Constructors
  4.  
  5. /// <summary>
  6. /// Encrypts and descrypts string using DES encryption
  7. /// </summary>
  8. public DataEncryption()
  9. {
  10. //
  11. }
  12.  
  13. /// <summary>
  14. /// Encrypts and descrypts string using DES encryption
  15. /// </summary>
  16. /// <param name="salt"></param>
  17. public DataEncryption(string prefix)
  18. {
  19. m_prefix = prefix;
  20. }
  21.  
  22. /// <summary>
  23. /// Encrypts and descrypts string using DES encryption
  24. /// </summary>
  25. /// <param name="salt">A prefix to append to the beginning of the data. Also known as a salted hash</param>
  26. /// <param name="encryptionKey">The encyption key used to encrypt the data</param>
  27. public DataEncryption(string prefix, string encryptionKey)
  28. {
  29. m_prefix = prefix;
  30. m_encryptionKey = encryptionKey;
  31. }
  32.  
  33. #endregion
  34.  
  35. #region Member Variables
  36.  
  37. private Byte[] m_Key = new Byte[8];
  38. private Byte[] m_IV = new Byte[8];
  39. private string m_encryptionKey = SHS.CHA.Security.EncryptionKey.Configuration.encryptionKey;
  40. private string m_prefix = SHS.CHA.Security.EncryptionKey.Configuration.prefix;
  41.  
  42. #endregion
  43.  
  44. #region Properties
  45.  
  46. /// <summary>
  47. /// Gets or Sets the salt used to prefix the encryption
  48. /// </summary>
  49. public string Prefix
  50. {
  51. get { return m_prefix; }
  52. set { m_prefix = value; }
  53. }
  54.  
  55. /// <summary>
  56. /// Gets or Sets the encryption key used to encrypt and descrypt the data
  57. /// </summary>
  58. public string EncryptionKey
  59. {
  60. get { return m_encryptionKey; }
  61. set { m_encryptionKey = value; }
  62. }
  63.  
  64. #endregion
  65.  
  66. #region Methods
  67.  
  68. #region Public Methods
  69.  
  70. /// <summary>
  71. /// Encrypts string using DES encryption
  72. /// </summary>
  73. /// <param name="strData">String to encrypt</param>
  74. /// <returns>Encrypted string</returns>
  75. public string EncyptData(string strData)
  76. {
  77. return EncryptData(m_encryptionKey, strData);
  78. }
  79.  
  80. /// <summary>
  81. /// Decrypts string using DES encryption
  82. /// </summary>
  83. /// <param name="strData">Encrypted value</param>
  84. /// <returns>A decrypted string</returns>
  85. public string DecryptData(string strData)
  86. {
  87. return DecryptData(m_encryptionKey, strData);
  88. }
  89.  
  90. /// <summary>
  91. /// Encrypts a query string parameter value and returns a result that can be used in the query string.
  92. /// </summary>
  93. /// <param name="parameterValue">Query string parameter value</param>
  94. /// <returns>An encrypted parameter value</returns>
  95. public string EncryptQueryStringParameterValue(string parameterValue)
  96. {
  97. string encryptedValue = string.Empty;
  98. if (!string.IsNullOrEmpty(parameterValue))
  99. {
  100. encryptedValue = EncryptData(m_encryptionKey, parameterValue);
  101. if (parameterValue != encryptedValue)
  102. encryptedValue = System.Web.HttpUtility.UrlEncode(encryptedValue);
  103. }
  104.  
  105. return encryptedValue;
  106. }
  107.  
  108. /// <summary>
  109. /// Decrypts an encrypted query string parameter value.
  110. /// </summary>
  111. /// <param name="parameterValue">Encrypted query string parameter value</param>
  112. /// <returns>A decrypted parameter value</returns>
  113. public string DecryptQueryStringParameterValue(string parameterValue)
  114. {
  115. string decryptedValue = string.Empty;
  116.  
  117. if (!string.IsNullOrEmpty(parameterValue))
  118. {
  119. parameterValue = HttpUtility.HtmlDecode(parameterValue);
  120. parameterValue = System.Web.HttpUtility.UrlDecode(parameterValue);
  121. parameterValue = parameterValue.Replace(" ", "+");
  122. decryptedValue = DecryptData(m_encryptionKey, parameterValue);
  123. }
  124.  
  125. return decryptedValue;
  126. }
  127.  
  128. /// <summary>
  129. /// Determines if a string has been encrypted by this class' methods
  130. /// </summary>
  131. /// <param name="strData">A string to test</param>
  132. /// <returns>A boolean indicating if a string is encrypted</returns>
  133. public bool IsEncrypted(string strData)
  134. {
  135. bool isEncrypted = false;
  136. int prefixLength = m_prefix.Length;
  137.  
  138. if (strData.Length > prefixLength && strData.Substring(0, prefixLength) == m_prefix)
  139. isEncrypted = true;
  140.  
  141. return isEncrypted;
  142. }
  143.  
  144. #endregion
  145.  
  146. #region Protected methods
  147.  
  148. /// <summary>
  149. /// Encrypts string using DES encryption
  150. /// </summary>
  151. /// <param name="encryptionKey">Encryption key, which is also used to decrypt data</param>
  152. /// <param name="strData">String to encrypt</param>
  153. /// <returns>Encrypted string</returns>
  154. protected string EncryptData(string encryptionKey, string strData)
  155. {
  156. string strResult = string.Empty;
  157. MemoryStream mStream = null;
  158. MemoryStream mOut = null;
  159. int prefixLength = m_prefix.Length;
  160.  
  161. try
  162. {
  163. // Check if string already encrypted
  164. if (strData.Length > prefixLength)
  165. {
  166. if (strData.Substring(0, prefixLength) == m_prefix)
  167. return strData; // Already encrypted
  168. }
  169.  
  170. // String length cannot exceed 90Kb. Otherwise, buffer will overflow.
  171. if (strData.Length > 92160)
  172. throw new Exception(SHS.CHA.Security.Resources.Resource.DataToLarge);
  173.  
  174. // Generate the Keys
  175. if (!InitKey(encryptionKey))
  176. throw new Exception(Resources.Resource.EncryptionKeyGenerationFail);
  177.  
  178. // Prepare the String
  179. // The first 5 character of the string is formatted to store the actual length of the data.
  180. strData = String.Format("{0,5:00000}" + strData, strData.Length);
  181.  
  182. // Encrypt the Data
  183. byte[] rbData = new byte[strData.Length];
  184. ASCIIEncoding aEnc = new ASCIIEncoding();
  185. aEnc.GetBytes(strData, 0, strData.Length, rbData, 0);
  186.  
  187. DESCryptoServiceProvider descsp = new DESCryptoServiceProvider();
  188.  
  189. ICryptoTransform desEncrypt = descsp.CreateEncryptor(m_Key, m_IV);
  190.  
  191. // Perpare the streams:
  192. // mOut is the output stream.
  193. // mStream is the input stream.
  194. // cs is the transformation stream.
  195. mStream = new MemoryStream(rbData);
  196. CryptoStream cs = new CryptoStream(mStream, desEncrypt, CryptoStreamMode.Read);
  197. mOut = new MemoryStream();
  198.  
  199. // Start performing the encryption
  200. int bytesRead;
  201. byte[] output = new byte[1024];
  202. do
  203. {
  204. bytesRead = cs.Read(output, 0, 1024);
  205. if (bytesRead != 0)
  206. mOut.Write(output, 0, bytesRead);
  207. } while (bytesRead > 0);
  208.  
  209. // Returns the encrypted result after it is base64 encoded
  210. // In this case, the actual result is converted to base64 so that it can be transported over the HTTP protocol without deformation.
  211. if (mOut.Length == 0)
  212. strResult = "";
  213. else
  214. strResult = Convert.ToBase64String(mOut.GetBuffer(), 0, (int)mOut.Length);
  215. strResult = m_prefix + strResult;
  216.  
  217. }
  218. catch (Exception exp)
  219. {
  220. throw exp;
  221. }
  222. finally
  223. {
  224. if (mStream != null)
  225. {
  226. mStream.Flush();
  227. mStream.Close();
  228. mStream.Dispose();
  229. }
  230. if (mOut != null)
  231. {
  232. mOut.Flush();
  233. mOut.Close();
  234. mOut.Dispose();
  235. }
  236. }
  237.  
  238. return strResult;
  239. }
  240.  
  241. /// <summary>
  242. /// Decrypts string using DES encryption
  243. /// </summary>
  244. /// <param name="encryptionKey"></param>
  245. /// <param name="strData"></param>
  246. /// <returns></returns>
  247. protected string DecryptData(string encryptionKey, string strData)
  248. {
  249. string strResult = string.Empty;
  250. MemoryStream mOut = null;
  251. int prefixLength = m_prefix.Length;
  252.  
  253. try
  254. {
  255. // Check if encrypted
  256. if (strData.Length < prefixLength)
  257. return strData; // Already decrypted
  258. else if (strData.Substring(0, prefixLength) != m_prefix)
  259. return strData; // Already decrypted
  260. else // encrypted
  261. strData = strData.Substring(prefixLength);
  262.  
  263. //1. Generate the Key used for decrypting
  264. if (!InitKey(encryptionKey))
  265. {
  266. strResult = Resources.Resource.DecryptionKeyGenerationFail;
  267. return strResult;
  268. }
  269.  
  270. //2. Initialize the service provider
  271. int nReturn = 0;
  272. DESCryptoServiceProvider descsp = new DESCryptoServiceProvider();
  273. ICryptoTransform desDecrypt = descsp.CreateDecryptor(m_Key, m_IV);
  274.  
  275. //3. Prepare the streams:
  276. // mOut is the output stream.
  277. // cs is the transformation stream.
  278. mOut = new MemoryStream();
  279. CryptoStream cs = new CryptoStream(mOut, desDecrypt, CryptoStreamMode.Write);
  280.  
  281. //4. Remember to revert the base64 encoding into a byte array to restore the original encrypted data stream
  282. byte[] bPlain = new byte[strData.Length];
  283. try
  284. {
  285. bPlain = Convert.FromBase64CharArray(strData.ToCharArray(), 0, strData.Length);
  286. }
  287. catch (Exception)
  288. {
  289. throw new Exception(Resources.Resource.Base64NotEncoded);
  290. }
  291.  
  292. long lRead = 0;
  293. long lTotal = strData.Length;
  294.  
  295. try
  296. {
  297. //5. Perform the actual decryption
  298. while (lTotal >= lRead)
  299. {
  300. cs.Write(bPlain, 0, (int)bPlain.Length);
  301. //descsp.BlockSize=64
  302. lRead = mOut.Length + Convert.ToUInt32(((bPlain.Length / descsp.BlockSize) * descsp.BlockSize));
  303. };
  304.  
  305. ASCIIEncoding aEnc = new ASCIIEncoding();
  306. strResult = aEnc.GetString(mOut.GetBuffer(), 0, (int)mOut.Length);
  307.  
  308. //6. Trim the string to return only the meaningful data
  309. // Remember that in the encrypt function, the first 5 character holds the length of the actual data
  310. // This is the simplest way to remember to original length of the data, without resorting to complicated computations.
  311. String strLen = strResult.Substring(0, 5);
  312. int nLen = Convert.ToInt32(strLen);
  313. strResult = strResult.Substring(5, nLen);
  314. nReturn = (int)mOut.Length;
  315. }
  316. catch (Exception)
  317. {
  318. throw new Exception(Resources.Resource.DecryptionFail);
  319. }
  320. }
  321. catch (Exception exp)
  322. {
  323. throw exp;
  324. }
  325. finally
  326. {
  327. if (mOut != null)
  328. {
  329. mOut.Flush();
  330. mOut.Close();
  331. mOut.Dispose();
  332. }
  333. }
  334.  
  335. return strResult;
  336. }
  337.  
  338. #endregion
  339.  
  340. #region Private Methods
  341.  
  342. /// <summary>
  343. /// Generates the keys
  344. /// </summary>
  345. /// <param name="encryptionKey"></param>
  346. /// <returns></returns>
  347. private bool InitKey(string encryptionKey)
  348. {
  349. try
  350. {
  351. // Convert Key to byte array
  352. byte[] bp = new byte[encryptionKey.Length];
  353. ASCIIEncoding aEnc = new ASCIIEncoding();
  354. aEnc.GetBytes(encryptionKey, 0, encryptionKey.Length, bp, 0);
  355.  
  356. // Hash the key using SHA1
  357. SHA1CryptoServiceProvider sha = new SHA1CryptoServiceProvider();
  358. byte[] bpHash = sha.ComputeHash(bp);
  359.  
  360. int i;
  361. // use the low 64-bits for the key value
  362. for (i = 0; i < 8; i++)
  363. m_Key[i] = bpHash[i];
  364.  
  365. for (i = 8; i < 16; i++)
  366. m_IV[i - 8] = bpHash[i];
  367.  
  368. return true;
  369. }
  370. catch (Exception exp)
  371. {
  372. throw exp;
  373. }
  374. }
  375.  
  376. #endregion
  377.  
  378. #endregion
  379. }

Report this snippet  

You need to login to post a comment.