Solved

encrypt the app.config connectionstring

Posted on 2015-01-12
3
206 Views
Last Modified: 2015-01-12
I am trying to encrypt the connection string in a win form and I found this code on Expert Exchange. I encrypted the connection string but how do I put the encrypted string in the config file?
code to get encrypted string
 private void Form1_Load(object sender, EventArgs e)
        {
            string conString = ConfigurationManager.ConnectionStrings["MyConString"].ToString();
            textBox1.Text = vault.Encrypt(conString);
            
        }

Open in new window

Encrypted string
7sIgbZ0r6wGpIahLvIZrJmCjYAJNJGMno464rU6TMaimMYfOKAxZD2NyPYgT76/J09BUqjeT9/1X9ZfvbaY7rKYCBz2H+xqE2PWStpQJ3Da9nENakNNqx683yj5EEp514CKaVG7EUw4MiUG9ASNKLjUcnVyw340Vpu0PSNjMMs/WoZS/zQvy8CFXZtpvOS+C

Open in new window


Encryption/decryption code
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Security.Cryptography;
using System.Text;
using System.Threading.Tasks;


namespace EncryptTest
{
    class vault
    {
        /************************************************************************************************************************************/
        #region Public Methods

        public static string Encrypt(string plainText)
        {
            RijndaelManaged key = GetKey();
            byte[] plainTextBytes = Encoding.UTF8.GetBytes(plainText);
            using (ICryptoTransform encryptor = key.CreateEncryptor())
            {
                using (MemoryStream memoryStream = new MemoryStream())
                {
                    using (CryptoStream cryptoStream = new CryptoStream(memoryStream, encryptor, CryptoStreamMode.Write))
                    {
                        cryptoStream.Write(plainTextBytes, 0, plainText.Length);
                        cryptoStream.FlushFinalBlock();
                        
                        return Convert.ToBase64String(memoryStream.ToArray());
                    }
                }
            }
        }

        public static string Decrypt(string encryptedString)
        {
            RijndaelManaged key = GetKey();
            byte[] encryptedData = Convert.FromBase64String(encryptedString);
            using (ICryptoTransform decryptor = key.CreateDecryptor(key.Key, key.IV))
            {
                using (MemoryStream memoryStream = new MemoryStream(encryptedData))
                {
                    using (CryptoStream cryptoStream = new CryptoStream(memoryStream, decryptor, CryptoStreamMode.Read))
                    {
                        byte[] plainText = new byte[encryptedData.Length];
                        int decryptedCount = cryptoStream.Read(plainText, 0, plainText.Length);
                        return Encoding.UTF8.GetString(plainText, 0, decryptedCount);
                    }
                }
            }
        }

        #endregion
        /************************************************************************************************************************************/
        #region Private Methods

        //Create encryption key
        private static RijndaelManaged GetKey()
        {
            RijndaelManaged key = new RijndaelManaged();
            byte[] passwordBytes = Encoding.UTF8.GetBytes(Properties.Resources.Password);
            byte[] saltBytes = Encoding.UTF8.GetBytes(Properties.Resources.Salt);
            PasswordDeriveBytes p = new PasswordDeriveBytes(passwordBytes, saltBytes);
            key.IV = p.GetBytes(key.BlockSize / 8);
            key.Key = p.GetBytes(key.KeySize / 8);
            return key;
        }

        #endregion
        /************************************************************************************************************************************/
    }
}

Open in new window

0
Comment
Question by:r3nder
3 Comments
 
LVL 69

Expert Comment

by:Éric Moreau
Comment Utility
0
 
LVL 32

Accepted Solution

by:
it_saige earned 500 total points
Comment Utility
Just take your encrypted string and put it in the config file in place of your connections string; e.g. -
<?xml version="1.0"?>
<configuration>
    <configSections>
    </configSections>
    <connectionStrings>
        <add name="EE_Q28594935.Properties.Settings.EE_Q28594935ConnectionString" connectionString="WNleCk4R3mJzlLlq+/KyKYk8QDCpZY6yL357est4jhpydSLju7UxCuMjYIlP/rsFpv0cXxt85dEoZn0W5KsQ/9ZbtdFscZVoTjeh2lHA4U8Abca6BWJgmEVhPOJqZ+iT+uV9RvaTVrZ3GHRLbNBEOSJlxcGP2u5KSRgBdhds8fE=" providerName="System.Data.SqlClient"/>
    </connectionStrings>
<startup><supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.0"/></startup></configuration>

Open in new window


Then you would access it as such:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Configuration;

namespace EE_Q28594935
{
	public partial class Form1 : Form
	{
		public Form1()
		{
			InitializeComponent();
		}

		private void Form1_Load(object sender, EventArgs e)
		{
			string conString = ConfigurationManager.ConnectionStrings["EE_Q28594935.Properties.Settings.EE_Q28594935ConnectionString"].ToString();
			textBox1.Text = vault.Decrypt(conString);
		}
	}
}

Open in new window

Produces the following output -Capture.JPG-saige-
0
 
LVL 6

Author Closing Comment

by:r3nder
Comment Utility
Thank you - explains alot
0

Featured Post

Highfive Gives IT Their Time Back

Highfive is so simple that setting up every meeting room takes just minutes and every employee will be able to start or join a call from any room with ease. Never be called into a meeting just to get it started again. This is how video conferencing should work!

Join & Write a Comment

Displaying an arrayList in a listView using the default adapter is rarely the best solution. To get full control of your display data, and to be able to refresh it after editing, requires the use of a custom adapter.
Exception Handling is in the core of any application that is able to dignify its name. In this article, I'll guide you through the process of writing a DRY (Don't Repeat Yourself) Exception Handling mechanism, using Aspect Oriented Programming.
In this fifth video of the Xpdf series, we discuss and demonstrate the PDFdetach utility, which is able to list and, more importantly, extract attachments that are embedded in PDF files. It does this via a command line interface, making it suitable …
In this seventh video of the Xpdf series, we discuss and demonstrate the PDFfonts utility, which lists all the fonts used in a PDF file. It does this via a command line interface, making it suitable for use in programs, scripts, batch files — any pl…

772 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

12 Experts available now in Live!

Get 1:1 Help Now