Solved

encrypt the app.config connectionstring

Posted on 2015-01-12
3
214 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 70

Expert Comment

by:Éric Moreau
ID: 40544685
0
 
LVL 33

Accepted Solution

by:
it_saige earned 500 total points
ID: 40544693
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
ID: 40544823
Thank you - explains alot
0

Featured Post

Resolve Critical IT Incidents Fast

If your data, services or processes become compromised, your organization can suffer damage in just minutes and how fast you communicate during a major IT incident is everything. Learn how to immediately identify incidents & best practices to resolve them quickly and effectively.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

In this post we will learn how to connect and configure Android Device (Smartphone etc.) with Android Studio. After that we will run a simple Hello World Program.
This article will inform Clients about common and important expectations from the freelancers (Experts) who are looking at your Gig.
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 …

820 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