Skip to main content

Encryption and Decryption in .NET

You want to scramble data on the server side before it's saved and also want to retrieve it later and unscramble it.

Encryption and Decryption is what you want.
There are 2 types, Symmetric and Asymmetric.
Symmetric uses 1 key (private) and this same key is used to encrypt and decrypt.
Asymmetric uses 2 keys, 1 for encryption (public) and 1 for decryption (private)

So at least a key is required in all cases. This needs to be stored somewhere. Seems that hardcoded in code or in a config file seems to be the preference.
When storing the key in the web.config ensure that the section is encrypted itself so that it's not human readable http://msdn.microsoft.com/en-us/library/zhhddkxy(v=vs.100).aspx.

.NET has a bunch of classes which can be do the actual work, see the
System.Security.Cryptography namespace. See the SymmetricAlgorithm and the AsymmetricAlgorithm classes. Use the (SymmetricAlgorithm)CryptoConfig.CreateFromName(provider)) and get the provider form the web.config with something like ConfigurationManager.AppSettings["encryption"]


You can create create a key with



Additionally you can add Salt to the encryption, the following case basically adds complexity to the key before the encryption takes place. This makes it more difficult for someone to decrypt if they only have the key.
 
private static string CreateSalt(int size)
        {
            //Generate a cryptographic random number.
            RNGCryptoServiceProvider rng = new RNGCryptoServiceProvider();
            byte[] buff = new byte[size];
            rng.GetBytes(buff);
 
            var asHex = BitConverter.ToString(buff).Replace("-"",0x");
            // Return a Base64 string representation of the random number.
            return Convert.ToBase64String(buff);
        }

The generated key could then be used with some of the .NET code like follows:
private const ushort ITERATIONS = 300;
private static readonly byte[] SALT = new byte[] { 0xBA, 0x72, 0xCA, 0xC6, 0x35, 0xC2, 0x9E, 0xAB, 0x87, 0x0F, 0x58, 0xD4, 0x5F, 0xF0, 0x88, 0x6E, 0xAA, 0x74, 0x9B, 0xE9 };
 
        private static byte[] CreateKey(string password, int keySize)
        {
            DeriveBytes derivedKey = new Rfc2898DeriveBytes(password, SALT, ITERATIONS);
            return derivedKey.GetBytes(keySize >> 3);
        }
 
  public static string DoEncrypt(string plainText, string key, string provider)
  {
   
            using (SymmetricAlgorithm algo = (SymmetricAlgorithmCryptoConfig.CreateFromName(provider))
   {
                var newKey = CreateKey(key, algo.KeySize);
 
                algo.Key = newKey;
    // BlockSize is in bits.
    algo.IV = new byte[algo.BlockSize / 8];
    
    using (ICryptoTransform tx = algo.CreateEncryptor())
    {
     byte[] plainBytes = Encoding.UTF8.GetBytes(plainText);
     byte[] cipherBytes = tx.TransformFinalBlock(plainBytes, 0, plainBytes.Length);
     return BytesToHexString(cipherBytes);
    }
   }
  }

Comments

Popular posts from this blog

dotNET - Debugging

Debugging with .NET MSIL assemblies Visual Studio and debugging the CLR are different, I'll talk about both. MSIL Assemblies Assemblies compiled with .NET tools such as the CLR compiler are compiled into a file which contains MSIL (Microsoft Intermediate Language). At runtime the contents of the assembly are loaded into the CLR and ran as machine code. When you compile an assembly in debug a PDB file is generated alongside the DLL or EXE you've just created. The link between these 2 files is that the PDB contains the line numbers of the methods and classes as well as the file names of the original source code that created the assembly. When you launch the debugger in Visual Studio the assembly is loaded into the Debugger (similar to the CLR) along with the PDB file. The debugger now uses your PDB file contents to match the running code found in the assembly to locations in source files (hopefully in your present project). CLR CLR Inside Out (msdn magazine) .NET Framework Tools:...

Installer CustomAction, Debugging the CustomAction, InstallState

Custom Action The Custom Action is added to the Setup Project, select the Project node and hit the Custom Action button. This allows you add an Action to a particular phase in the Installation. But first you must create the Custom Action. To Add a Custom Action you must first have a Custom Action created, this is usually in the form of a Installer Class, this should be created in a seperate project, the Installer Class is actually one of the File Templates in the C# Projects. So it's File->New Project and select Visual C# Projects. Then add a Class Library, this will prompt you for the Class Library Types , select "Installer Class". Walkthrough - Creating Custom Action (msdn). Also here's a more comprehensive document on Setup/Installer implementations, it delves into the Registry etc Getting Started with Setup Projects (SimpleTalk). Visual Studio Setup Projects and Custom Actions (Simple Talk). Create your Installer Class and then add it as a Custom Action to the ...

dotNET - Use app.config ApplicationSettings and UserSettings

When using Settings in an Assembly or .exe you can use the Settings Designer to generate a config file using Settings. The Settings Designer provides a wrapper class which allows you to provide defaults and access the config data using Properties. But what if you're not working inside that Assembly or .exe? this presents a problem. If your loading the Assembly externally and want to access that Assembly's .config file you'll probably wish to use something in the System.Configuration namespace... unfortunately it's not of much use if you've created the .config file from the Settings Designer in Visual Studio!! This is because the Designer creates Sections and ApplicationSettings and UserSettings, the System.Configuration namespace does not provide a method to access these (it has a method to access AppSettings which are a different thing. Below I've written a workaround which locates the app.config and accesses the ApplicationSettings and UserSettings using XML i...