ConnectionString Encryption

Posts   
 
    
NickD
User
Posts: 224
Joined: 31-Jan-2005
# Posted on: 09-Aug-2005 20:52:49   

What is the current trend for encrypting the connection string in the web.config file? For testing, mine is simply plain text, but I know there are obvious security risks with that. What do you all do for connection string encryption?

Alvaro
User
Posts: 52
Joined: 01-Jun-2004
# Posted on: 09-Aug-2005 21:21:55   

I don't know about trends :-) but we do encrypt it, the connection string looks something like this:

data source=source;initial catalog=cat;User Id=UID;Password=CA4D49B9832A06FF

The code to read it is simple enough, using System.Security.Cryptography.

I'll paste the core below:


public static string DecryptDBPassConnectString(byte[] key,string connString) {
    string decryptedDBPassConnString = String.Empty;
    string passPart;
    string encPass;
    string decPass;
    int startIndex = connString.ToUpper().IndexOf("PASSWORD");
    int endIndex;
    if (startIndex >= 0) {
        endIndex = connString.IndexOf(";",startIndex);
        passPart = connString.Substring(startIndex,endIndex-startIndex);
        encPass = passPart.Split('=')[1].Trim();
        decPass = new SecurityHandler(key).Decrypt(encPass);
        decryptedDBPassConnString = connString.Substring(0,startIndex);
        decryptedDBPassConnString += passPart.Split('=')[0] + "=" + decPass + 
                    connString.Substring(endIndex,connString.Length -endIndex );
    }
    return decryptedDBPassConnString;
}

public string Decrypt(string text) {
    CryptoStream decryptorStream = new CryptoStream(
        _3DESDecryptorStream,
        _3DESCryptoServiceProvider.CreateDecryptor(),
        CryptoStreamMode.Write);

    byte[] dataToDecrypt = ASCII.ToBIN(text);

    // Decrypt data.
    _3DESDecryptorStream.Seek(0, SeekOrigin.Begin);
    _3DESDecryptorStream.SetLength(0);

    decryptorStream.Write(dataToDecrypt, 0, dataToDecrypt.Length);

    _3DESDecryptorStream.Seek(0, SeekOrigin.Begin);

    byte[] encData = new byte[_3DESDecryptorStream.Length];

    for (int i = 0; i < _3DESDecryptorStream.Length; i++)   {
        encData[i] = (byte) _3DESDecryptorStream.ReadByte();
    }

    string buff = ASCIIEncoding.ASCII.GetString(encData);
    char end = (char) 127;

    return buff.TrimEnd(end);
}

NickD
User
Posts: 224
Joined: 31-Jan-2005
# Posted on: 10-Aug-2005 01:32:45   

Gracias!