Solved

encrypt/decrypt .net 4.0 best practice c#

Posted on 2013-12-09
15
2,030 Views
Last Modified: 2014-01-01
In .NET 4.0 what is the safest way to encrypt/decrypt  a value I am passing as a query string. What is the best practice, please provide the code (complete class) and the website or book or article, etc showing it is best bractice, you see, I have to proof to our security person we are complying with industry standards.
0
Comment
Question by:ClassicCPLus
[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
  • 10
  • 2
15 Comments
 

Author Comment

by:ClassicCPLus
ID: 39707044
We are using this. However, according to our security guy it is no longer good enough.
public byte[] Encrypt(byte[] plainText, byte[] optionalEntropy)

            {
                  bool retVal = false;
                  DATA_BLOB plainTextBlob = new DATA_BLOB();
                  DATA_BLOB cipherTextBlob = new DATA_BLOB();
                  DATA_BLOB entropyBlob = new DATA_BLOB();
                  CRYPTPROTECT_PROMPTSTRUCT prompt = new CRYPTPROTECT_PROMPTSTRUCT();
                  InitPromptstruct(ref prompt);
                  int dwFlags;
                  try
                  {
                        try
                        {
                              int bytesSize = plainText.Length;
                              plainTextBlob.pbData = Marshal.AllocHGlobal(bytesSize);
                              if(IntPtr.Zero == plainTextBlob.pbData)
                              {
                                    throw new Exception("Unable to allocate plaintext buffer.");
                              }
                              plainTextBlob.cbData = bytesSize;
                              Marshal.Copy(plainText, 0, plainTextBlob.pbData, bytesSize);
                        }
                        catch(Exception ex)
                        {
                              throw new Exception("Exception marshalling data. " + ex.Message);
                        }
                        if(Store.USE_MACHINE_STORE == store)
                        {//Using the machine store, should be providing entropy.
                              dwFlags = CRYPTPROTECT_LOCAL_MACHINE|CRYPTPROTECT_UI_FORBIDDEN;
                              //Check to see if the entropy is null
                              if(null == optionalEntropy)
                              {//Allocate something
                                    optionalEntropy = new byte[0];
                              }
                              try
                              {
                                    int bytesSize = optionalEntropy.Length;
                                    entropyBlob.pbData = Marshal.AllocHGlobal(optionalEntropy.Length);;
                                    if(IntPtr.Zero == entropyBlob.pbData)
                                    {
                                          throw new Exception("Unable to allocate entropy data buffer.");
                                    }
                                    Marshal.Copy(optionalEntropy, 0, entropyBlob.pbData, bytesSize);
                                    entropyBlob.cbData = bytesSize;
                              }
                              catch(Exception ex)
                              {
                                    throw new Exception("Exception entropy marshalling data. " +
                                          ex.Message);
                              }
                        }
                        else
                        {//Using the user store
                              dwFlags = CRYPTPROTECT_UI_FORBIDDEN;
                        }
                        retVal = CryptProtectData(ref plainTextBlob, "", ref entropyBlob,
                              IntPtr.Zero, ref prompt, dwFlags,
                              ref cipherTextBlob);
                        if(false == retVal)
                        {
                              throw new Exception("Encryption failed. " +
                                    GetErrorMessage(Marshal.GetLastWin32Error()));
                        }
                        //Free the blob and entropy.
                        if(IntPtr.Zero != plainTextBlob.pbData)
                        {
                              Marshal.FreeHGlobal(plainTextBlob.pbData);
                        }
                        if(IntPtr.Zero != entropyBlob.pbData)
                        {
                              Marshal.FreeHGlobal(entropyBlob.pbData);
                        }
                  }
                  catch(Exception ex)
                  {
                        throw new Exception("Exception encrypting. " + ex.Message);
                  }
                  byte[] cipherText = new byte[cipherTextBlob.cbData];
                  Marshal.Copy(cipherTextBlob.pbData, cipherText, 0, cipherTextBlob.cbData);
                  Marshal.FreeHGlobal(cipherTextBlob.pbData);
                  return cipherText;
            }
0
 
LVL 75

Expert Comment

by:käµfm³d 👽
ID: 39707125
Any particular reason why you're not using the classes found under the System.Security.Cryptography namespace?
0
 

Author Comment

by:ClassicCPLus
ID: 39707150
No particular reason, only this is a legacy application that has been upgraded, I want to use RijndaelManaged
0
Automating Your MSP Business

The road to profitability.
Delivering superior services is key to ensuring customer satisfaction and the consequent long-term relationships that enable MSPs to lock in predictable, recurring revenue. What's the best way to deliver superior service? One word: automation.

 

Accepted Solution

by:
ClassicCPLus earned 0 total points
ID: 39714688
0
 

Author Comment

by:ClassicCPLus
ID: 39714761
I've requested that this question be closed as follows:

Accepted answer: 0 points for ClassicCPLus's comment #a39714688

for the following reason:

The example I found on Microsoft  works great!
0
 

Author Comment

by:ClassicCPLus
ID: 39714763
See my two previous posts with the solution I am using.
0
 

Author Comment

by:ClassicCPLus
ID: 39721775
I am using this http://msdn.microsoft.com/en-us/library/system.security.cryptography.rijndaelmanaged(v=vs.110).aspx?cs-save-lang=1&cs-lang=vb#code-snippet-2. Is it possible to save the key and vector byte() on the web.config? if so how? an example would be greatly appreciated.
0
 
LVL 63

Assisted Solution

by:btan
btan earned 200 total points
ID: 39731127
Is it possible to save the key and vector byte() on the web.config? if so how?

> The plain key should not be store in web.config exposed but web.config can have section encrypted which is more preferred compared to even using encoding such as base64 for the key. You may want to catch below which has encryption and decryption of the contents of a Web.config file performed using a ProtectedConfigurationProvider class.

The following list describes the protected configuration providers included in the .NET Framework:
DpapiProtectedConfigurationProvider. Uses the Windows Data Protection API (DPAPI) to encrypt and decrypt data.
RsaProtectedConfigurationProvider. Uses the RSA encryption algorithm to encrypt and decrypt data.

E.g. Walkthrough: Encrypting Configuration Information Using Protected Configuration
http://msdn.microsoft.com/en-us/library/dtkwfdky.aspx

E.g. AES Decryption using the MachineKey DecryptionKey
http://forums.asp.net/t/1190098.aspx

The key is to protect the web.config if it contains the plain key and to know ASP.NET 2.0 uses the RijndaelManaged implementation of the AES algorithm when it processes view state data. http://support.microsoft.com/kb/911722
0
 

Author Comment

by:ClassicCPLus
ID: 39736559
I am using ASP.NET 4.0 with VS 2010 not ASP.NET 4.0
0
 

Author Comment

by:ClassicCPLus
ID: 39736567
This application was written in 2.0 and has been upgraded to 4.0
0
 

Author Comment

by:ClassicCPLus
ID: 39736587
Will you send me an example of how to create the key and the vector and then how to convert it to a format I can save on the web.config, you see, I created it using RijndaelManaged.GenerateKey() and RijndaelManaged.GenerateIV() then converted to a string and saved it on the web.config . However when I retrieve the value from the web.config and then use Encoding.ASCII.GetBytes("Key") to pass the value to RijndaelManged.Key I get error: "Specified key is not a valid size for this algorithm". I hope this is clear, I really appreciate your help with this, I am stuck.
0
 
LVL 63

Expert Comment

by:btan
ID: 39737149
The RijndaelManaged algorithm supports key lengths of 128, 192, or 256 bits. Your key one should be one of these sizes, default is 128 bits. E.g.

The string "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz012345678912" when base64-decoded yields 48 bytes (384 bits). RijndaelManaged supports 128, 192 and 256 bit keys.

A valid 128-bit key is new byte[]{ 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0A, 0x0B, 0x0C, 0x0D, 0x0E, 0x0F } or if you need to get it from base64 : Convert.FromBase64String("AAECAwQFBgcICQoLDA0ODw==").

The default blocksize is 128 bits, so the same byte-array will work as the IV.

Pls see this
http://vbcity.com/forums/t/89938.aspx

Also alternatively the use of Rfc2898DeriveBytes
http://www.codeproject.com/Articles/38804/Encryption-and-Decryption-on-the-NET-Framework
0
 

Author Closing Comment

by:ClassicCPLus
ID: 39749627
0

Featured Post

How Do You Stack Up Against Your Peers?

With today’s modern enterprise so dependent on digital infrastructures, the impact of major incidents has increased dramatically. Grab the report now to gain insight into how your organization ranks against your peers and learn best-in-class strategies to resolve incidents.

Question has a verified solution.

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

Suggested Solutions

Title # Comments Views Activity
How to set focus on a dynamic control 18 48
EF5 How do I stop pre-compiled views? 8 51
CSS styling problem 3 27
VB .net 2010 Byte array 2 19
Provide an easy one stop to quickly get the relevant information on common asked question on Ransomware in Expert Exchange.
This paper addresses the security of Sennheiser DECT Contact Center and Office (CC&O) headsets. It describes the DECT security chain comprised of “Pairing”, “Per Call Authentication” and “Encryption”, which are all part of the standard DECT protocol.
This video teaches viewers how to create their own website using cPanel and Wordpress. Tutorial walks users through how to set up their own domain name from tools like Domain Registrar, Hosting Account, and Wordpress. More specifically, the order in…
This video teaches users how to migrate an existing Wordpress website to a new domain.

737 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