Library tutorials & articles
Using Encryption in .NET
- Overview
- Ciphers & Key Strength
- Choosing a Cipher
- Getting Started
- Encrypting & Decrypting
- Cipher Modes & Initialization Vectors
- Conclusion
Encrypting & Decrypting
ICryptoTransform
You'll get to be good friends with this interface as you put encryption to work in your applications. ICryptoTransform is the standard interface through which you ask the cipher to encrypt and decrypt data. Note that this interface is also used by other cryptographic classes, such as hashes. Let's have a quick look at the members of this interface.
TransformBlock – Call this method to transform (encrypt or decrypt) 1 or more blocks before the end of the message.
TransformFinalBlock – Call this method to transform 1 or more blocks at the end of the message. Given our discussion of padding, you should understand why it is necessary to transform blocks at the end of the message differently than those before the end.
CanReuseTransform – Returns a boolean indicating whether the current transform can be reused. In the case of the FCL ciphers, this will always return true.
CanTransformMultipleBlocks – Returns a boolean indicating whether multiple blocks can be transformed in a single call to either TransformBlock or TransformFinalBlock. In the case of the FCL ciphers, this property also always returns true, indicating that you need not add logic to your code to process individual blocks of data. The one caveat, of course, is that you must call the appropriate transform depending on whether the data is at the end of the message (TransformFinalBlock) or not (TransformBlock).
InputBlockSize/OutputBlockSize – These properties return an integer indicating the input and output block sizes, respectively. In the case of ciphers, these will always be the same, and their return value will be dependent upon the value you specified in the BlockSize property of the cipher.
Encrypting and Decrypting
We now have enough background to begin encrypting and decrypting data. To perform the actual transformation of Encryption or Decryption, you need to create an instance of what is called a Transform class. You do this in .NET by calling the cipher's CreateEncryptor or CreateDecryptor methods, depending, of course, on whether you're encrypting data or decrypting data. The CreateEncryptor/Decryptor methods return an ICryptoTransform interface to the newly created transform class. Once you have the ICryptoTransform interface, you simply need to call the TransformBlock and TransformFinalBlock methods as appropriate. Let's add two new methods to our CipherWrapper class: EncryptMessage and DecryptMessage.
public byte[] EncryptMessage(byte[] plainText)
{
ICryptoTransform transform = _cipher.CreateEncryptor();
byte[] cipherText = transform.TransformFinalBlock(plainText, 0, plainText.Length);
return cipherText;
}
public byte[] DecryptMessage(byte[] cipherText)
{
ICryptoTransform transform = _cipher.CreateDecryptor();
byte[] plainText = transform.TransformFinalBlock(cipherText, 0, cipherText.Length);
return plainText;
}
Note that the only difference between the two functions is the call to either CreateEncryptor or CreateDecryptor. These two methods return an ICryptoTransform interface to a new transform class which actually performs the correct cryptographic transformations depending on the encryption mode, Encrypt or Decrypt. It is necessary to return a new class instance, because the transformation must maintain state in the case of transformation performed in multiple steps.
The example above assumes that we're using a message-based protocol where we know the entire contents of either the plain or cipher text at encryption/decryption time. Since we also know that the FCL ciphers always return true from CanTransformMultipleBlocks, we need not call TransformBlock method at all. We can simply transform the entire message in one go by calling TransformFinalBlock. If you are implementing a system where you may not know the entire message, you will have to modify this simple example to call TransformBlock/TransformFinalBlock as appropriate. It's not terribly difficult to use the TransformBlock method. Basically, the only difference from a coding standpoint is that it does not return any data. Instead, you must pass in a buffer, into which the cipher will place the transformed bytes, as well as an offset into the buffer where you would like the data to be stored.
Crypto Streams
For stream-based protocols, it would be nice to have built-in functionality to allow us to read and write individual bytes at a time or at least to write chunks not broken into perfect blocks. Fortunately, the FCL provides this functionality in the CryptoStream class. I don't want to clutter the article with code that is specific to streaming rather than cryptography, so I'll just provide a couple of examples that demonstrate the basics of using the CryptoStream class.
byte[] EncryptMessageUsingStream(byte[] plainText)
{
ICryptoTransform transform = _cipher.CreateEncryptor();
MemoryStream ms = new MemoryStream();
CryptoStream cs = new CryptoStream(ms, transform, CryptoStreamMode.Write);
cs.Write(plainText, 0, plainText.Length);
// Remember padding! This instructs the transform to pad and finish.
cs.FlushFinalBlock();
byte[] cipherText = ms.ToArray();
return cipherText;
}
Notes: In order to implement this in a stream-based protocol, you would break this method up into possibly several methods that initialize the stream once, then call CryptoStream.Write in iterations, then call FlushFinalBlock and read the data.
byte[] DecryptMessageUsingStream(byte[] cipherText)
{
ICryptoTransform transform = _cipher.CreateDecryptor();
MemoryStream ms = new MemoryStream(cipherText);
CryptoStream cs = new CryptoStream(ms, transform, CryptoStreamMode.Read);
byte[] plainTextBuffer = new byte[cipherText.Length];
// Remember padding! The length read may be different than the
// length of the plain text.
int plainTextLength = cs.Read(plainTextBuffer, 0, cipherText.Length);
byte[] plainText = new byte[plainTextLength];
Array.Copy(plainTextBuffer, 0, plainText, 0, plainTextLength);
return plainText;
}
Notes: The notes on EncryptMessageUsingStream also apply here. The reason that the length of the cipher text and the actual number of bytes that are read from the stream are different is, of course, padding. You don't necessarily have to allocate a temporary buffer, as I have done. You could simply return the entire plainTextBuffer with an integer indicating the length of the actual plain text, which is returned from the CryptoStream.Read call. Alternatively, if you know the length of the plain text, you could pass this as a parameter and only allocate and read the appropriate length.
Related articles
Related discussion
-
Problem after strong naming an assembly
by rinkurathor1 (0 replies)
-
Very slow inserts using SqlCommand.ExecuteNonQuery()
by porchelvi (1 replies)
-
VB.net class to connect to sql database
by senol01 (2 replies)
-
how to select item to datagrid from textbox
by chandradev1 (49 replies)
-
Adobe Flex reaches out to .NET developers
by ranganathanmca (1 replies)
Related podcasts
-
CodeCast Episode 4: State of .NET, IE8, ASP.NET MVC, and O'Reilly Media
CodeCast Episode 4: State of .NET, IE8, ASP.NET MVC, and O'Reilly MediaHosts Ken Levy and Markus Egger discuss the new State of .NET events, IE8, ASP.NET MVC, followed by an interview from PDC with two editors from O'Reilly Media. More on ASP.NET MVC can be found at http://asp.net/mvc. Interview...
Related jobs
-
Microsoft .Net Architect
in AMSTERDAM (€50K-€90K per annum) -
Applicatie ontwikkelaar binnen Defensie
in Amsterdam (£50K-£90K per annum) -
Business Analist (Openbaar) Vervoer
in Amsterdam (€50K-€90K per annum) -
Application Engineer (VB, .Net, Java) - Standplaats: Utrecht
in Amsterdam (€50K-€90K per annum)
Events coming up
-
Dec
6
Developing AJAX Web Applications with Castle Monorail
London, United Kingdom
Monorail is the model-view-controller engine of the Castle Project, bringing many of the best ideas of Ruby on Rails to the .NET world. In this talk, David De Florinier and Gojko Adzic show how Monorail makes it easy to develop .NET based AJAX applications, and how to use the Castle Project to build Web 2.0 applications effectively. Come to this session if you are a .NET web developer. Everyone is welcome!
I totally agree that varbinary could have been used. My only problem with that solution is that it seems difficult to work with binary data in ADO.NET and SQL Server. I may be wrong. I haven't tried it, but I seem to remember seeing some nasty code dealing with storing images and other binary data in SQL Server. The conversion to and from Base64 strings is 1 line of code in each case and then I can deal with regular char and varchar fields.
Couldn't you also store this in a Varbinary field instead of trying to convert it to a string for a varchar field?
Dear Steve,
I was wondering if you had some insight as to how to best to file encrypting with the rijndael encryption. Most examples I've found only give info. about how to encrypt messages. I know you said that the CryptoStream object was beyond your scope, but that's where I'm needing to go with this and I like to use a FileStream instead of a MemoryStream. I would also like to save the encrypted file in place of the original (which I may just have to rename them differently and then delete the original). I also know you said that you don't have to write the encryption byte for byte, but how do you do this with a FileStream? And if you do have to do it byte for byte with a FileStream, then how many bytes do I/should I set it to? Also, all examples I've seen only demonstrate how to Encrypt a file and not Decrypt it again. On the decryption, though, I only need to display it and not keep or save it anywhere. Maybe loading it into a MemoryStream might be better? Keep in mind that this files could be big (most are images). Is there any advice you could give or maybe another discussion you have?
Thanks!
Exactly. If you don't use the same IV for encryption and decryption, the message can't be properly decoded.
Problem seems to be fixed now - I'd uncommented the initialisation vector code and it looks like it's mandetory.
Also - replaced the hex encoding with base64 strings (many thanks to Ben Mills on the other thread about storing values in SQL server for pointing me in this direction).
Many thanks Ben - I've got a working solution now!
I think the problem was the fact I'd commented out the initialisation vector code.. I didn't think this was essential.
Anyhow - I've also removed my conversion routines to and from hex as the conversion to base64 strings is a lot more elegant (and the strings generated shorter).
Thanks again.
I actually ended up cracking the problem in a different way. Here's what I do to encode a .NET string:
1. Turn the string into a byte array using the ASCII encoder.
2. Run the byte array through the Rijndael encryptor (some bytes cannot now be represented as ASCII chars).
3. Convert the resulting array of bytes to a Base64 string using Convert.ToBase64String().
4. The result is an ASCII string which can be strored in regular (non-unicode) database columns.
To decrypt the string I do the reverse:
1. Convert the string from the database into a byte array using Convert.FromBase64String().
2. Run the byte array through the Rijndael decryptor.
3. Convert the resulting array back into a string using the ASCII encoder.
The trick with all of this is that the an 8 bit unicode string can be stored as a 7 bit ASCII string by converting it into a Base64 string. Base 64 strings use 4 bytes to represent every block of 3 byte unicode characters. See http://email.about.com/cs/standards/a/base64_encoding.htm for a good intro on base64 strings. The one thing you have to think about is how long to make your database columns. Just remember that every block of 3 unencrypted characters results in 4 encrypted characters in the database.
I hope this helps,
Ben Mills
Hi all,
Excellent article - made a lot of sense.
I've created a little test app which converts the byte arrays to hex strings (for storing in DB) - and then does the reverse. This all seems to work, but for some strange reason the first 32 characters of the decrypted string are garbled (everything after this point is fine!!).
I'm guessing it's something to do with padding, but not sure - maybe I'm missing something really obvious!
Any help would be hugely appreciated. I've posted the code from my test form below (hope you're okay about this and hope it benefits others)..
cheers.
using System;
using System.Drawing;
using System.Collections;
using System.ComponentModel;
using System.Windows.Forms;
using System.Data;
using System.Security.Cryptography;
using System.Text;
using System.IO;
using System.Globalization; // for NumberStyles
namespace EncryptionTool
{
/// <summary>
/// Summary description for Form1.
/// </summary>
public class Form1 : System.Windows.Forms.Form
{
private System.Windows.Forms.TextBox txtToEncrypt;
private System.Windows.Forms.Label label1;
private System.Windows.Forms.Button btnDecrypt;
private System.Windows.Forms.Label label2;
private System.Windows.Forms.TextBox txtKey;
private System.Windows.Forms.Label label3;
private System.Windows.Forms.Button btnEncrypt;
private System.Windows.Forms.TextBox txtEncrypted;
private System.Windows.Forms.TextBox txtDecrypted;
private System.Windows.Forms.Label label4;
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.Container components = null;
public Form1()
{
//
// Required for Windows Form Designer support
//
InitializeComponent();
//
// TODO: Add any constructor code after InitializeComponent call
//
}
/// <summary>
/// Clean up any resources being used.
/// </summary>
protected override void Dispose( bool disposing )
{
if( disposing )
{
if (components != null)
{
components.Dispose();
}
}
base.Dispose( disposing );
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.txtToEncrypt = new System.Windows.Forms.TextBox();
this.label1 = new System.Windows.Forms.Label();
this.txtEncrypted = new System.Windows.Forms.TextBox();
this.btnDecrypt = new System.Windows.Forms.Button();
this.label2 = new System.Windows.Forms.Label();
this.txtKey = new System.Windows.Forms.TextBox();
this.label3 = new System.Windows.Forms.Label();
this.btnEncrypt = new System.Windows.Forms.Button();
this.txtDecrypted = new System.Windows.Forms.TextBox();
this.label4 = new System.Windows.Forms.Label();
this.SuspendLayout();
//
// txtToEncrypt
//
this.txtToEncrypt.Location = new System.Drawing.Point(8, 72);
this.txtToEncrypt.Multiline = true;
this.txtToEncrypt.Name = "txtToEncrypt";
this.txtToEncrypt.Size = new System.Drawing.Size(448, 80);
this.txtToEncrypt.TabIndex = 1;
this.txtToEncrypt.Text = "";
//
// label1
//
this.label1.Location = new System.Drawing.Point(8, 56);
this.label1.Name = "label1";
this.label1.TabIndex = 2;
this.label1.Text = "Text to encrypt";
//
// txtEncrypted
//
this.txtEncrypted.Location = new System.Drawing.Point(8, 176);
this.txtEncrypted.Multiline = true;
this.txtEncrypted.Name = "txtEncrypted";
this.txtEncrypted.Size = new System.Drawing.Size(448, 80);
this.txtEncrypted.TabIndex = 3;
this.txtEncrypted.Text = "";
//
// btnDecrypt
//
this.btnDecrypt.Location = new System.Drawing.Point(464, 184);
this.btnDecrypt.Name = "btnDecrypt";
this.btnDecrypt.TabIndex = 4;
this.btnDecrypt.Text = "&Decrypt";
this.btnDecrypt.Click += new System.EventHandler(this.btnDecrypt_Click);
// <
Hi,
I'm attempting to do the same thing. I've gone down the route of converting the cipher's byte array to a Hex string using the following: -
BitConverter.ToString(bytEncryptedMessage);
This creates a hyphon delimitted string (e.g. 0A-10-FA etc...) which can be stored in the database.
When I want to decrypt I'm first calling the following function: -
// Assumes the hex string values are "-" delimitted. e.g. 0A-FA-BD
public byte[] HexStringToBytes(string sHexString)
{
string[] sStringArray;
byte[] bytByteArray;
int iCount = 0;
sStringArray = sHexString.Split('-');
bytByteArray = new byte[sStringArray.Length];
foreach (string sHexValue in sStringArray)
{
bytByteArray[iCount] = byte.Parse(sHexValue, NumberStyles.HexNumber);
iCount ++;
}
return bytByteArray;
}
which re-creates the byte array.
I thought I'd cracked it, but something really weird is happening!! When decrypted - the first 32 characters are garbage - everything after is fine!!!
I'm guessing this is something to do with the padding, but not sure.
Hope this points you in the right direction and would also really appreciate any assistance with the problem I'm having!
First of all, I'd like to say that this was a fantastic article. I was struggling through the MSDN info and other online articles and your article finally made everything clear.
I want to use this technique to encrypt credit card data before I store it in SQL Server. I take the ASCII credit card number, convert it to an array of bytes using the ASCII encoder and then encrypt the bytes. The trouble is that the bytes are now out of the ASCII range (0 to 127), so I can't convert the bytes back to an ASCII string to store in a VarChar column of a SQL Server table.
It seems like a solution is to convert the encrypted bytes to a unicode string using the unicode encoder and store that value in a NVarChar column. The only problem with this is that I usually avoid unicode SQL Server columns. Is this the only solution or do you have any other ideas?
Regarding my comment that "there is "no way" to reverse this process without the key."
I want to be clear that I mean that there is no trivial way to do this. What I'm trying to say is that the process is as secure as the key and the underlying cipher.
There is, of course, no such thing as "no way" in cryptography. We just try to use the best technology we can to make it as difficult and expensive as possible for an attacker to break the system.
Steve Johnson
Using CBC as an example, encryption proceeds as follows:
1 - XOR Plain Text Block #1 with IV
2 - Encrypt the block resulting from step 1 with the key
3 - The Cipher Text block resulting from step 3 is used as Cipher Text block #1
4 - XOR Plain Text block #2 with Cipher Text block #1
5 - Encrypt the block resulting from step 4 with the key
6 - The Cipher Text block resulting from step 5 is used as Cipher Text block #2
7 - etc, etc...
There's no way to reverse this process without the key. The IV is not being used to seed a PRNG; it's simply used as random data, with which to mix the first block of plain text on encryption and to retrieve the initial plain text block on decryption. As you can see, there is no intermediate "non-randomized" state that can be determined using the cipher text and the IV.
Steve Johnson
Wouldn't this mean that for eavesdroppers using the same random generator (which can not be that big a problem) and the transmitted seed it is possible to retrieve the 'un-randomized' (if thats a word) still encrypted content?
Wilfred Kuijpers
dbHost
You transmit the IV in the clear (unencrypted). Just add the IV to your transmitted message so the receiving computer can decrypt the message. There's no need to encrypt the IV because it is used simply to randomize the cipher text to prevent repetition.
Steve Johnson
Hi,
Great article,
Just one question though, how do you transmit your IV's? I mean, decryction usually happens at another computer and for encryption and decryption you suggest to use the iv?
regards,
Wilfred Kuijpers
dbhost
This thread is for discussions of Using Encryption in .NET.