Solved

encrypt the app.config connectionstring

Posted on 2015-01-12
3
217 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
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
3 Comments
 
LVL 70

Expert Comment

by:Éric Moreau
ID: 40544685
0
 
LVL 34

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

Free Tool: IP Lookup

Get more info about an IP address or domain name, such as organization, abuse contacts and geolocation.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

Question has a verified solution.

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

Suggested Solutions

Title # Comments Views Activity
array not updating 8 41
Call to SQL server times out 5 53
Datagridview column resizing 8 26
Which is best Image Resizing Web service 11 39
It was really hard time for me to get the understanding of Delegates in C#. I went through many websites and articles but I found them very clumsy. After going through those sites, I noted down the points in a easy way so here I am sharing that unde…
This article shows how to deploy dynamic backgrounds to computers depending on the aspect ratio of display
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 …

739 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