|
using System;
using System.Text;
using System.IO;
using System.Security.Cryptography;
namespace EnterpriseConnString
{
// Class to encrypt and decrypt strings using the KeyWord and CryptoAPI
// I am using DES encryption to demonstrate to encypt and decrypt conn strings
// Customize the class using the required strength of cryptography
public class Cypher
{
// initialization vector, this acts like out private key !
static byte[] DESIV = {0x00, 0x12, 0x34, 0x56, 0xAA, 0x55, 0xFF, 0x56};
static Cypher()
{
}
// Encrypt input string using DES algorithm
internal static byte[] Encrypt(string keyword, string input)
{
// in the next 3 lines I am taking care of padding the string to
// an integral length of 8, otherwise DES will do padding
byte[] readBytes = new byte[input.Length + input.Length % 8];
for (int i=0; i<readBytes.Length; i++)
readBytes[i] = (i<input.Length) ? (byte)input[i] : (byte)0x00;
MemoryStream memoryStream = new MemoryStream();
DESCryptoServiceProvider DESProvider = new DESCryptoServiceProvider();
DESProvider.Key = ASCIIEncoding.ASCII.GetBytes(keyword);
DESProvider.IV = DESIV;
ICryptoTransform DESEncrypt = DESProvider.CreateEncryptor();
CryptoStream cryptoStream = new CryptoStream(memoryStream,
DESEncrypt, CryptoStreamMode.Write);
cryptoStream.Write(readBytes, 0, readBytes.Length);
cryptoStream.FlushFinalBlock();
memoryStream.Close();
cryptoStream.Close();
return memoryStream.ToArray();
}
// Decrypt input byte array using DES algorithm
internal static string Decrypt(string keyword, byte[] input)
{
MemoryStream memoryStream = new MemoryStream(input);
DESCryptoServiceProvider DESProvider = new DESCryptoServiceProvider();
ICryptoTransform DESDecrypt= DESProvider.CreateDecryptor(
ASCIIEncoding.ASCII.GetBytes(keyword), DESIV);
CryptoStream cryptoStream = new CryptoStream(memoryStream,
DESDecrypt, CryptoStreamMode.Read);
cryptoStream.Read(input, 0,input.Length);
cryptoStream.Close();
memoryStream.Close();
ASCIIEncoding ac = new ASCIIEncoding();
return ac.GetString(memoryStream.ToArray());
}
}
}
|
By viewing downloads associated with this article you agree to the Terms of Service and the article's licence.
If a file you wish to view isn't highlighted, and is a text file (not binary), please
let us know and we'll add colourisation support for it.
This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.
A list of licenses authors might use can be found here
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.