Solved

encrypt the app.config connectionstring

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

3 Use Cases for Connected Systems

Our Dev teams are like yours. They’re continually cranking out code for new features/bugs fixes, testing, deploying, testing some more, responding to production monitoring events and more. It’s complex. So, we thought you’d like to see what’s working for us.

Question has a verified solution.

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

Suggested Solutions

Title # Comments Views Activity
C# bracket error 3 31
Math Equation 23 88
SQL Help 27 45
what is the best portable software where i can test codes written in different languages 1 30
Since upgrading to Office 2013 or higher installing the Smart Indenter addin will fail. This article will explain how to install it so it will work regardless of the Office version installed.
If you’re thinking to yourself “That description sounds a lot like two people doing the work that one could accomplish,” you’re not alone.
Viewers will learn how to properly install Eclipse with the necessary JDK, and will take a look at an introductory Java program. Download Eclipse installation zip file: Extract files from zip file: Download and install JDK 8: Open Eclipse and …
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…

777 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