/ Published in: C#
Class to encrypt and decrypt strings.
Expand |
Embed | Plain Text
public class DataEncryption { #region Constructors /// <summary> /// Encrypts and descrypts string using DES encryption /// </summary> public DataEncryption() { // } /// <summary> /// Encrypts and descrypts string using DES encryption /// </summary> /// <param name="salt"></param> public DataEncryption(string prefix) { m_prefix = prefix; } /// <summary> /// Encrypts and descrypts string using DES encryption /// </summary> /// <param name="salt">A prefix to append to the beginning of the data. Also known as a salted hash</param> /// <param name="encryptionKey">The encyption key used to encrypt the data</param> public DataEncryption(string prefix, string encryptionKey) { m_prefix = prefix; m_encryptionKey = encryptionKey; } #endregion #region Member Variables private string m_encryptionKey = SHS.CHA.Security.EncryptionKey.Configuration.encryptionKey; private string m_prefix = SHS.CHA.Security.EncryptionKey.Configuration.prefix; #endregion #region Properties /// <summary> /// Gets or Sets the salt used to prefix the encryption /// </summary> public string Prefix { get { return m_prefix; } set { m_prefix = value; } } /// <summary> /// Gets or Sets the encryption key used to encrypt and descrypt the data /// </summary> public string EncryptionKey { get { return m_encryptionKey; } set { m_encryptionKey = value; } } #endregion #region Methods #region Public Methods /// <summary> /// Encrypts string using DES encryption /// </summary> /// <param name="strData">String to encrypt</param> /// <returns>Encrypted string</returns> public string EncyptData(string strData) { return EncryptData(m_encryptionKey, strData); } /// <summary> /// Decrypts string using DES encryption /// </summary> /// <param name="strData">Encrypted value</param> /// <returns>A decrypted string</returns> public string DecryptData(string strData) { return DecryptData(m_encryptionKey, strData); } /// <summary> /// Encrypts a query string parameter value and returns a result that can be used in the query string. /// </summary> /// <param name="parameterValue">Query string parameter value</param> /// <returns>An encrypted parameter value</returns> public string EncryptQueryStringParameterValue(string parameterValue) { string encryptedValue = string.Empty; if (!string.IsNullOrEmpty(parameterValue)) { encryptedValue = EncryptData(m_encryptionKey, parameterValue); if (parameterValue != encryptedValue) encryptedValue = System.Web.HttpUtility.UrlEncode(encryptedValue); } return encryptedValue; } /// <summary> /// Decrypts an encrypted query string parameter value. /// </summary> /// <param name="parameterValue">Encrypted query string parameter value</param> /// <returns>A decrypted parameter value</returns> public string DecryptQueryStringParameterValue(string parameterValue) { string decryptedValue = string.Empty; if (!string.IsNullOrEmpty(parameterValue)) { parameterValue = HttpUtility.HtmlDecode(parameterValue); parameterValue = System.Web.HttpUtility.UrlDecode(parameterValue); parameterValue = parameterValue.Replace(" ", "+"); decryptedValue = DecryptData(m_encryptionKey, parameterValue); } return decryptedValue; } /// <summary> /// Determines if a string has been encrypted by this class' methods /// </summary> /// <param name="strData">A string to test</param> /// <returns>A boolean indicating if a string is encrypted</returns> public bool IsEncrypted(string strData) { bool isEncrypted = false; int prefixLength = m_prefix.Length; if (strData.Length > prefixLength && strData.Substring(0, prefixLength) == m_prefix) isEncrypted = true; return isEncrypted; } #endregion #region Protected methods /// <summary> /// Encrypts string using DES encryption /// </summary> /// <param name="encryptionKey">Encryption key, which is also used to decrypt data</param> /// <param name="strData">String to encrypt</param> /// <returns>Encrypted string</returns> protected string EncryptData(string encryptionKey, string strData) { string strResult = string.Empty; MemoryStream mStream = null; MemoryStream mOut = null; int prefixLength = m_prefix.Length; try { // Check if string already encrypted if (strData.Length > prefixLength) { if (strData.Substring(0, prefixLength) == m_prefix) return strData; // Already encrypted } // String length cannot exceed 90Kb. Otherwise, buffer will overflow. if (strData.Length > 92160) // Generate the Keys if (!InitKey(encryptionKey)) // Prepare the String // The first 5 character of the string is formatted to store the actual length of the data. strData = String.Format("{0,5:00000}" + strData, strData.Length); // Encrypt the Data aEnc.GetBytes(strData, 0, strData.Length, rbData, 0); ICryptoTransform desEncrypt = descsp.CreateEncryptor(m_Key, m_IV); // Perpare the streams: // mOut is the output stream. // mStream is the input stream. // cs is the transformation stream. // Start performing the encryption int bytesRead; do { bytesRead = cs.Read(output, 0, 1024); if (bytesRead != 0) mOut.Write(output, 0, bytesRead); } while (bytesRead > 0); // Returns the encrypted result after it is base64 encoded // In this case, the actual result is converted to base64 so that it can be transported over the HTTP protocol without deformation. if (mOut.Length == 0) strResult = ""; else strResult = Convert.ToBase64String(mOut.GetBuffer(), 0, (int)mOut.Length); strResult = m_prefix + strResult; } catch (Exception exp) { throw exp; } finally { if (mStream != null) { mStream.Flush(); mStream.Close(); mStream.Dispose(); } if (mOut != null) { mOut.Flush(); mOut.Close(); mOut.Dispose(); } } return strResult; } /// <summary> /// Decrypts string using DES encryption /// </summary> /// <param name="encryptionKey"></param> /// <param name="strData"></param> /// <returns></returns> protected string DecryptData(string encryptionKey, string strData) { string strResult = string.Empty; MemoryStream mOut = null; int prefixLength = m_prefix.Length; try { // Check if encrypted if (strData.Length < prefixLength) return strData; // Already decrypted else if (strData.Substring(0, prefixLength) != m_prefix) return strData; // Already decrypted else // encrypted strData = strData.Substring(prefixLength); //1. Generate the Key used for decrypting if (!InitKey(encryptionKey)) { strResult = Resources.Resource.DecryptionKeyGenerationFail; return strResult; } //2. Initialize the service provider int nReturn = 0; ICryptoTransform desDecrypt = descsp.CreateDecryptor(m_Key, m_IV); //3. Prepare the streams: // mOut is the output stream. // cs is the transformation stream. //4. Remember to revert the base64 encoding into a byte array to restore the original encrypted data stream try { bPlain = Convert.FromBase64CharArray(strData.ToCharArray(), 0, strData.Length); } catch (Exception) { } long lRead = 0; long lTotal = strData.Length; try { //5. Perform the actual decryption while (lTotal >= lRead) { cs.Write(bPlain, 0, (int)bPlain.Length); //descsp.BlockSize=64 lRead = mOut.Length + Convert.ToUInt32(((bPlain.Length / descsp.BlockSize) * descsp.BlockSize)); }; strResult = aEnc.GetString(mOut.GetBuffer(), 0, (int)mOut.Length); //6. Trim the string to return only the meaningful data // Remember that in the encrypt function, the first 5 character holds the length of the actual data // This is the simplest way to remember to original length of the data, without resorting to complicated computations. String strLen = strResult.Substring(0, 5); int nLen = Convert.ToInt32(strLen); strResult = strResult.Substring(5, nLen); nReturn = (int)mOut.Length; } catch (Exception) { } } catch (Exception exp) { throw exp; } finally { if (mOut != null) { mOut.Flush(); mOut.Close(); mOut.Dispose(); } } return strResult; } #endregion #region Private Methods /// <summary> /// Generates the keys /// </summary> /// <param name="encryptionKey"></param> /// <returns></returns> private bool InitKey(string encryptionKey) { try { // Convert Key to byte array aEnc.GetBytes(encryptionKey, 0, encryptionKey.Length, bp, 0); // Hash the key using SHA1 byte[] bpHash = sha.ComputeHash(bp); int i; // use the low 64-bits for the key value for (i = 0; i < 8; i++) m_Key[i] = bpHash[i]; for (i = 8; i < 16; i++) m_IV[i - 8] = bpHash[i]; return true; } catch (Exception exp) { throw exp; } } #endregion #endregion }
You need to login to post a comment.
