
This is the Title of the Book, eMatter Edition
Copyright © 2007 O’Reilly & Associates, Inc. All rights reserved.
Encrypting and Decrypting a File
|
953
This method displays:
decryptedString: MyPassword
There does not seem to be any problem with using escape sequences such as \r, \n,
\r\n,or\t in the string to be encrypted. In addition, using a quoted string literal,
with or without escaped characters, works without a problem:
@"MyPassword"
See Also
See Recipe 17.3; see the “System.Cryptography Namespace,” “MemoryStream
Class,” “ICryptoTransform Interface,” and “RijndaelManaged Class” topics in the
MSDN documentation.
17.3 Encrypting and Decrypting a File
Problem
You have sensitive information that must be encrypted before it is written to a file
that might be in a nonsecure area. This information must also be decrypted before it
is read back in to the application.
Solution
Use multiple cryptography providers and write the data to a file in encrypted format.
This is accomplished in the following class, which has a constructor that expects an
instance of the
System.Security.Cryptography.SymmetricAlgorithm class and a path
for the file. The
SymmetricAlgorithm class is an abstract base class for all crypto-
graphic providers in .NET, so you can be reasonably assured that this class could be
extended to cover all of them. This example implements support for TripleDES and
Rijndael. It is easily be extended for ...