C# Encryption and Decryption of a String With a Simple Function Call
Cryptography is a big subject area and extremely important for modern software and programs. If you are writing any type of software you need an understanding of software security and methods to keep data, code and users secure. Encrypting data keeps it secure because it hides its meaning, converting the plaintext (or cleartext) to ciphertext. To see the data again you need to decrypt the ciphertext back to plaintext. A simple example is the encryption of passwords to protect them from use by others.
Encryption and decryption of a password or other strings containing data can be done in many ways. There are many character substitution or transposition methods that pre-date the computing era and can be traced back to classical times. Modern computer based methods use symmetric key and asymmetric key mathematical algorithms. There are lots of well established algorithms from which to choose. However not everyone wants to take a course in cryptography just to be able to encrypt a string to hide some data and decrypt it back again. That’s where this example C# encryption and decryption code comes in handy. This code was tested in Visual Studio 2013.
This C# code has been boiled down to an encryption function that takes a plaintext string and passphrase and returns an encrypted string. There is the reverse function that takes the ciphertext and the passphrase and returns the plaintext. This is a quick and easy method of adding some encryption to a C# project, or any .NET project. The encrypt decrypt C# string functions are in a simple class. An example project shows how simple it is to use them.
The code presented here is not going to be explained in detail. Instead it is recommended that it is studied. The reader should to refer to online resources and the Microsoft .NET Framework documentation on the System.Security.Cryptography namespace. The code was picked up from the Stack Overflow question Encrypting and Decrypting a String in C#.
This code is using a symmetric key algorithm known as Rijndael (after the inventors Vincent Rijmen and Joan Daemen) implemented by the .NET Framework. This algorithm performs substitutions and permutations on data blocks with keys sized in multiples of 32 bits. The cipher mode is Cipher Block Chaining (CBC) which can take a different Initialisation Vector (IV) for each use to further obfuscate the cipher text. In which case the same passphrase and plaintext will produce different ciphertexts if a different IV is used. Change the IV string for you own value or generate a random one (this can be done at https://www.random.org/strings/). The passphrase is not salted but can be, see the documentation for PasswordDeriveBytes. Note that the encryption and decryption is performed on bytes and not Unicode characters hence the conversion from strings to byte arrays in the code (it also means that these functions can be adapted for other data types if required).
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
|
//Don’t forget the using System.Security.Cryptography; statement wher you add this class
public static class Encrypt
{
// This size of the IV (in bytes) must = (keysize / 8). Default keysize is 256, so the IV must be
// 32 bytes long. Using a 16 character string here gives us 32 bytes when converted to a byte array.
private const string initVector = “pemgail9uzpgzl88”;
// This constant is used to determine the keysize of the encryption algorithm
private const int keysize = 256;
//Encrypt
public static string EncryptString(string plainText, string passPhrase)
{
byte[] initVectorBytes = Encoding.UTF8.GetBytes(initVector);
byte[] plainTextBytes = Encoding.UTF8.GetBytes(plainText);
PasswordDeriveBytes password = new PasswordDeriveBytes(passPhrase, null);
byte[] keyBytes = password.GetBytes(keysize / 8);
RijndaelManaged symmetricKey = new RijndaelManaged();
symmetricKey.Mode = CipherMode.CBC;
ICryptoTransform encryptor = symmetricKey.CreateEncryptor(keyBytes, initVectorBytes);
MemoryStream memoryStream = new MemoryStream();
CryptoStream cryptoStream = new CryptoStream(memoryStream, encryptor, CryptoStreamMode.Write);
cryptoStream.Write(plainTextBytes, 0, plainTextBytes.Length);
cryptoStream.FlushFinalBlock();
byte[] cipherTextBytes = memoryStream.ToArray();
memoryStream.Close();
cryptoStream.Close();
return Convert.ToBase64String(cipherTextBytes);
}
//Decrypt
public static string DecryptString(string cipherText, string passPhrase)
{
byte[] initVectorBytes = Encoding.UTF8.GetBytes(initVector);
byte[] cipherTextBytes = Convert.FromBase64String(cipherText);
PasswordDeriveBytes password = new PasswordDeriveBytes(passPhrase, null);
byte[] keyBytes = password.GetBytes(keysize / 8);
RijndaelManaged symmetricKey = new RijndaelManaged();
symmetricKey.Mode = CipherMode.CBC;
ICryptoTransform decryptor = symmetricKey.CreateDecryptor(keyBytes, initVectorBytes);
MemoryStream memoryStream = new MemoryStream(cipherTextBytes);
CryptoStream cryptoStream = new CryptoStream(memoryStream, decryptor, CryptoStreamMode.Read);
byte[] plainTextBytes = new byte[cipherTextBytes.Length];
int decryptedByteCount = cryptoStream.Read(plainTextBytes, 0, plainTextBytes.Length);
memoryStream.Close();
cryptoStream.Close();
return Encoding.UTF8.GetString(plainTextBytes, 0, decryptedByteCount);
}
}
|
This small example shows the encrypt decrypt functionality in action. Create a similar WinForm or download the code, which has this dialog.
Encryption of a string in C# with a password is as simple as:
1
|
textBoxEncrypted.Text = Encrypt.EncryptString(textBoxString.Text, textBoxPassword.Text);
|
And decryption is just as easy:
1
|
textBoxString.Text = Encrypt.DecryptString(textBoxEncrypted.Text, textBoxPassword.Text);
|
Example project and source code: EncryptString.zip
See also: Effortless .NET Encryption
No Comment