.Net demystifies encryption

Daily Newsletters

Sign up to ZDNet UK's daily newsletter.

ANALYSIS
One way .Net benefits Windows developers is by bringing together previously separate APIs and SDKs under one framework. For example, consider the adaptation of the CryptoAPI to the .Net System.Security.Cryptography namespace. The cryptographic services have left their mysterious corner of the Platform SDK to become, in a sense, "just another .Net namespace." Of course, there is more to it than that, but the point is that the cryptographic services are more approachable because of what they share with the rest of the framework as a whole. Now, you just have to learn what the System.Security.Cryptography namespace does and which classes are appropriate for specific situations. Grab the code
You can download the .cs files for this article here.
System.Security.Cryptography namespace
The namespace contains classes that implement security solutions such as:
  • Encryption and decryption of data.
  • Management of persisted encryption keys.
  • Verification of the integrity of a piece of data to ensure that it has not been tampered with.
I will limit this article to encryption and decryption, but keep in mind that this is only one piece of the puzzle; a truly secure solution will make use of the other pieces as well. Our examples start with the encryption of a local text file and then move on to the more complicated encryption of messages between networked computers. Symmetric algorithms
To encrypt a local text file, we use one of the symmetric algorithms; symmetric because the same key and initialisation vector (IV) are used to both encrypt and decrypt a piece of data. (The IV's relationship to the key is explained in the Cryptography Overview section of the .Net documentation.) .Net implementations of symmetric algorithms derive from a common abstract base class, SymmetricAlgorithm, highlighting that the programmer can treat each of the specific algorithms -- DES, TripleDES, and Rijndael -- in the same fashion. The algorithms differ in how they encrypt the data, but the public interfaces are the same. This doesn't mean that all algorithms are equal. For instance, as you may have guessed by the name, TripleDES is a more secure successor to DES. Because the same key encrypts and decrypts data, symmetric algorithms are best suited for situations where the key does not need to be broadcast. Network encryption calls for a combination of asymmetric and symmetric algorithms, as you'll later see. But first let's put the symmetric algorithms to good use. Encrypting a text file
Listing A contains a console program, TextFileCrypt, which encrypts a text file you specify on the command line. The top of Listing A shows how to invoke the program. Let's look at some of the more important pieces of the code. The symmetric algorithms work by encrypting data as it passes through a stream. We create a "normal" output stream (such as a file I/O stream), followed by an instance of the CryptoStream class, which will then piggyback on that normal stream. You write byte arrays to the CryptoStream, and as the data streams through, it gets encrypted and put into the normal stream. To put the original text file into an array of bytes to be fed to the CryptoStream, you employ the FileStream class to read it. You also use another instance of FileStream as the output mechanism that the CryptoStream will hand the encrypted data to.FileStream fsIn = File.Open(file,FileMode.Open, FileAccess.Read);FileStream fsOut = File.Open(tempfile, FileMode.Open,FileAccess.Write); It's all about streams
.Net makes considerable use of streams to read and write data. In fact, the symmetric algorithm classes require you to use them. If you aren't comfortable with .Net's stream-based input and output, I encourage you to familiarise yourself with it.
We can instantiate and use any one of the symmetric algorithm providers while specifying the object variable as the abstract type SymmetricAlgorithm. I chose Rijndael, but you could just as easily instantiate DES or TripleDES: SymmetricAlgorithm symm = new RijndaelManaged();
// could just as easily be "new TripleDESCryptoServiceProvider()" .Net sets these provider instances with strong random keys. It can be dangerous to try to choose your own keys; acceptance of the "computer-generated" key is good practice. Next, the algorithm instance provides an object to perform the actual data transformation. Each algorithm has CreateEncryptor and CreateDecryptor methods for this purpose, and they return objects implementing the ICryptoTransform interface: ICryptoTransform transform = symm.CreateEncryptor(); Finally, a special CryptoStream is instantiated and told which underlying stream it should piggyback on, which object will perform the transformation of the data, and whether the purpose of the stream is to read or write data: CryptoStream cstream = new CryptoStream(fsOut,transform,CryptoStreamMode.Write);

Post your comment

In order to post a comment you need to be registered and logged in.

You can also log in with Facebook. Log in or create your ZDNet UK account below

  • Login

Will not be displayed with your comment

By signing up for this service, you indicate that you agree to our Terms and Conditions and have read and understood our Privacy Policy. Questions about membership? Find the answers in the Community FAQ

Get ZDNet UK's daily newsletter

Enter your email address to sign up

ZDNet UK Live

UnderINK

I agree with the previous commenter wholeheartedly. I couldn't say it better myself. This is very 'Big Brother'. And while I agree with protecting...

1 hour ago by UnderINK on European e-identity plan to be unveiled this month
Simon Bisson and Mary Branscombe

Nice to see that Turing's idea of a general purpose computer doing once-hardware-powered tasks in software is now universal ;-) Mary

7 hours ago by Simon Bisson and Mary Branscombe on Software with everything
Jason Burchell

seriously now. I've only bothered to read a small bit of the comments. do me and the rest of the world a favour. stop saying it does not work or...

11 hours ago by Jason Burchell via Facebook on Music industry negotiating over 24-bit downloads
Philip Charles Cohen

Read about it and weep, John Donahoe ... In addition to Visa’s V.me, there is now MasterCard’s PayPass digital wallet soon to arrive; another...

15 hours ago by Philip Charles Cohen via Facebook on PayPal takes phone-based payments to the high street
apexwm

Leslie Satenstein : Where have you ever seen Mozilla even mention this? Firefox is the most popular browser in the GNU/Linux OS, so I don't see...

15 hours ago by apexwm on Firefox rapid release improves Fedora Linux
songmaster

SHleG: Do you remember building a clockwork scorpion kit (I'm pretty sure I have a photo of it somewhere) — I think it was called something like...

17 hours ago by songmaster on Software with everything
Chris Wortman

Good I love Yahoo! Their search engine is getting better than Google as of late. I find more of what I want on the first page, and usually within...

18 hours ago by Chris Wortman via Facebook on Linux Mint 13 ramps up for KDE release
PatrickG

openhgs has made the point for Windows 8 multiple monitors without realising it! With Windows 7 you have to switch the mouse and so your focus...

19 hours ago by PatrickG on Windows 8 could speed multi-monitor uptake
Leslie Satenstein

Mozilla has threatened to stop supporting Linux. I guess that UBUNTU is going with another browser. I indicated that if Mozilla stops supporting...

21 hours ago by Leslie Satenstein via Facebook on Firefox rapid release improves Fedora Linux
Andy Bolstridge

Much as I abhor Microsoft's licensing practices, this is almost certainly down to purchasing IT equipment via 3rd party consultants - you get the...

21 hours ago by Andy Bolstridge via Facebook on 6 million wasted licences and £1,200 PCs: welcome to government IT
Jack Schofield

@openhgs Windows users have had multiple desktops since Linus started writing Linux. They just haven't shipped as standard because not enough...

2 days ago by Jack Schofield on Windows 8 could speed multi-monitor uptake
Jack Schofield

@Phil at Cloud4 What, Microsoft gets £1,200 per PC and £1,622 per server? Gosh, I'm amazed....

2 days ago by Jack Schofield on 6 million wasted licences and £1,200 PCs: welcome to government IT
craigsc

You guys have no idea what is going on at Autonomy. Autonomy could have been a much more profitable organization. The sales operations at Autonomy...

2 days ago by craigsc on HP cuts 27,000 staff as Autonomy chief Lynch leaves
Moley

How does this impact on dual or multi booting? Seems to me to more or less prohibit this, from Windows 8 anyway. Will Grub 2 recognise Windows 8,...

2 days ago by Moley on Windows 8 start-up speed forces USB boot workaround
apexwm

I don't understand why there cannot be a slight pause during the boot process so the user can press a key. Many operating systems do this, even if...

2 days ago by apexwm on Windows 8 start-up speed forces USB boot workaround
Gavin Goodman

You can now buy the Xi3 modular computer in the UK at http://www.ocdistribution.com . This can be bought with the Tand3m software, pricing and...

2 days ago by Gavin Goodman on CES 2012: Xi3 microSERV3R
Phil at Cloud4

I agree: Mike Lynch can clearly build a business and manage strategy. I suspect the exit of Mike is more likely the end of a planned handover...

2 days ago by Phil at Cloud4 on HP cuts 27,000 staff as Autonomy chief Lynch leaves
Phil at Cloud4

This is unbeleivable government wastage with only one winner... Microsoft 1 - Tax payer Nil!

2 days ago by Phil at Cloud4 on 6 million wasted licences and £1,200 PCs: welcome to government IT
Mispam

So what do you do when you can't boot into windows? Why can't I just hold Shift while I power up instead of having to boot into windows and click a...

2 days ago by Mispam on Windows 8 start-up speed forces USB boot workaround
apexwm

I've also seen that Mac OS X for Intel machines is supposed to run in VirtualBox, which would also be a nice solution. I've never tried it though.

2 days ago by apexwm on xTreme Triple Booting: Linux, Mac & Windows