developers.de
daenet's .NET Community

Encryption with Key Container

Damir Dobric Posts

 

Damir@Phone    



My upcoming sessions:

AppFabric Applications at
NRW Conf 2011
09.Sept.2011 Wuppertal

HTML5 widgets in WP7+
Monodroid
Mobility Day
21.Sept.2011 - Zagreb

AppFabric and WCF sessions at
Advanced Developer Conference
26.-27. Oktober 2011 in Frankenthal

AppFabric Applications, queues, topics and more at
Prio Conference
02. - 03. November 2011 in Meistersingerhalle Nürnberg

AppFabric Applications deep dive hosted by
.NET User Group Frankfurt
17.Nov.2011 18.30-22.30 Microsoft - Bad Homburg 

 

 

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

Add a Comment

(required)  
(optional)
(required)  
Remember Me?
daenet GmbH