[2 days left] What’s wrong with your cloud strategy? Learn why multicloud solutions matter with Nimble Storage.Register Now

x
?
Solved

encrypt the app.config connectionstring

Posted on 2015-01-12
3
Medium Priority
?
223 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 2000 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

Independent Software Vendors: We Want Your Opinion

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

Question has a verified solution.

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

In this post we will learn different types of Android Layout and some basics of an Android App.
The article shows the basic steps of integrating an HTML theme template into an ASP.NET MVC project
An introduction to basic programming syntax in Java by creating a simple program. Viewers can follow the tutorial as they create their first class in Java. Definitions and explanations about each element are given to help prepare viewers for future …
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…

656 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