A Simple Encrypting and Decrypting class in .net using System.Security.Cryptography Namespace

A Simple Encrypting and Decrypting class can be built in .net using System.Security.Cryptography Namespace. This can be used to encrypt or decrypt the connection strings The DESCryptoServiceProvider, RC2CryptoServiceProvider, and RijndaelManaged algorithms are used.

Please note: The following class will throw all exceptions to the calling class.  
Excpetion handling is to be done in the calling class.





To call the Decrypt method,
use a method like follows:



//Method call : argument (Encrypted Database connection string)

DecryptDBConnectionString(ConfigurationSettings.AppSettings["Database"]);


public static string DecryptDBConnectionString(string encryptedString)

{

SymmCrypto symmCry = new SymmCrypto(SymmCrypto.SymmProvEnum.DES);

return symmCry.Decrypting(encryptedString,"TARGET");

}


//Encrypting and Decrypting class using the System.Security.Cryptography Namespace


public
class SymmCrypto { #region Enum Crypto Service Providers /// <summary> /// Enum Containing CryptoServiceProviders /// </summary> public enum SymmProvEnum { DES, RC2, Rijndael, } #endregion Crypto Service Providers #region Member variables //Member Variable to hold the SymmetricAlgorithm used private SymmetricAlgorithm caSymmetricAlgorithm; #endregion Member variables #region Constructors /// <summary> /// Constructor method /// </summary> /// <param name="NetSelected">Enum SymmetricAlgorithm</param> public SymmCrypto(SymmProvEnum NetSelected) { switch(NetSelected) { case SymmProvEnum.DES: caSymmetricAlgorithm = new DESCryptoServiceProvider(); break; case SymmProvEnum.RC2: caSymmetricAlgorithm = new RC2CryptoServiceProvider(); break; case SymmProvEnum.Rijndael: caSymmetricAlgorithm = new RijndaelManaged(); break; } } /// <summary> /// Constructor method /// </summary> /// <param name="saSymmetricAlgorithm">SymmetricAlgorithm</param> public SymmCrypto(SymmetricAlgorithm saSymmetricAlgorithm) { caSymmetricAlgorithm = saSymmetricAlgorithm; } #endregion Constructors #region Encrypting /// <summary> /// Method to Encrypt data /// </summary> /// <param name="sourceData">Source String</param> /// <param name="keyValue">Key</param> /// <returns>Encrypted string</returns> public string Encrypting(string sourceData, string keyValue) { byte[] bytIn = System.Text.ASCIIEncoding.ASCII.GetBytes(sourceData); //create a MemoryStream so that the process can be done without I'O files System.IO.MemoryStream msMemoryStream = new System.IO.MemoryStream(); byte[] bytKey = GetKey(keyValue); // set the private key caSymmetricAlgorithm.Key = bytKey; caSymmetricAlgorithm.IV = bytKey; // create an Encryptor from the Provider Service instance ICryptoTransform ictEncrypto = caSymmetricAlgorithm.CreateEncryptor(); // create Crypto Stream that transforms a stream using the encryption CryptoStream csCryptoStream = new CryptoStream(msMemoryStream, ictEncrypto, CryptoStreamMode.Write); // write out encrypted content into MemoryStream csCryptoStream.Write(bytIn, 0, bytIn.Length); csCryptoStream.FlushFinalBlock(); // get the output and trim the '\0' bytes byte[] bytOut = msMemoryStream.GetBuffer(); int count = 0;
for(count = 0; count < bytOut.Length - 1; count++) { if (bytOut[count] == 0) { break; } }
//convert into Base64 so that the result can be used in xml return System.Convert.ToBase64String(bytOut, 0, count); } #endregion Encrypting #region GetKey /// <summary> /// Method to return key /// </summary> /// <param name="keyValue"></param> /// <returns></returns> public byte[] GetKey(string keyValue) { string tempValue; if (caSymmetricAlgorithm.LegalKeySizes.Length > 0) { int lessSize = 0; int moreSize = caSymmetricAlgorithm.LegalKeySizes[0].MinSize; //key sizes are in bits while (keyValue.Length * 8 > moreSize) { lessSize = moreSize; moreSize += caSymmetricAlgorithm.LegalKeySizes[0].SkipSize; } tempValue = keyValue.PadRight(moreSize / 8, ' '); } else { tempValue = keyValue; } // convert the secret key to byte array return ASCIIEncoding.ASCII.GetBytes(tempValue); } #endregion GetKey #region Decrypting /// <summary> /// Method to Encrypt data /// </summary> /// <param name="source">Source String</param> /// <param name="key">Key</param> /// <returns>Encrypted string</returns> public string Decrypting(string sourceData, string keyValue) { // convert from Base64 to binary try { byte[] bytIn = System.Convert.FromBase64String(sourceData); //create a MemoryStream with the input System.IO.MemoryStream msMemoryStream = new System.IO.MemoryStream(bytIn, 0, bytIn.Length); byte[] bytKey = GetKey(keyValue); //set the private key caSymmetricAlgorithm.Key = bytKey; caSymmetricAlgorithm.IV = bytKey; //create a Decryptor from the Provider Service instance ICryptoTransform ictEncrypto = caSymmetricAlgorithm.CreateDecryptor(); //create Crypto Stream that transforms a stream using the decryption CryptoStream cs = new CryptoStream(msMemoryStream, ictEncrypto, CryptoStreamMode.Read); //read out the result from the Crypto Stream System.IO.StreamReader srStreamReader = new System.IO.StreamReader(cs); return srStreamReader.ReadToEnd(); } catch (Exception ex) { throw ex; } } #endregion Decrypting } }
By [)ia6l0 iii   Popularity  (4871 Views)