Encryption with Key Container

Damir Dobric Posts

Next talks:

 

    

Follow me on Twitter: #ddobric



 

 

Archives

When encrypting some data in your application, you can use various already proven algorithms, which are integrated in .NET.
However, one thing remains mostly unclear. When talking about encryption most people focus on algorithms. This is reasonable, but one algorithm is at least secure as the key is secured.
In other words, if you have strong key and best algorithm in universe, but your key is insecurely stored, all is unsecured.

For this reason I post very short sample, which shows how easy key store can be incorporated in your application. If you try in this example to change CspParameters all will work fine as long both methods EncryptByContainer and DecryptByContainer
use exactly the same settings.


        private static void Start()
        {
            byte[] decryptedData = EncryptByContainer("Daenet is award winner");
           
            string txt = DecryptByContainer(decryptedData);
        }

        private static byte[] EncryptByContainer(string txt)
        {
            byte[] binData = Encoding.Unicode.GetBytes(txt);

            CspParameters cspPrms = new CspParameters();
            cspPrms.Flags = CspProviderFlags.UseMachineKeyStore;
            cspPrms.KeyContainerName = "TestKey";
           
            RSACryptoServiceProvider rsaProv = new RSACryptoServiceProvider(cspPrms);

            byte[] encyptedData = rsaProv.Encrypt(binData, true);

            return encyptedData;
        }

        private static string DecryptByContainer(byte[] encryptedData)
        {
            string txt;
         
            CspParameters cspPrms = new CspParameters();
            cspPrms.Flags = CspProviderFlags.UseMachineKeyStore;
            cspPrms.KeyContainerName = "TestKey";

            RSACryptoServiceProvider rsaProv = new RSACryptoServiceProvider(cspPrms);

            byte[] decrypedData = rsaProv.Decrypt(encryptedData, true);

            txt = Encoding.Unicode.GetString(decrypedData);

            return txt;
        }




Posted Jul 26 2010, 01:37 AM by Damir Dobric
developers.de is a .Net Community Blog powered by daenet GmbH.