Recipe12.27.EncryptingDecrypting an Existing File


Recipe 12.27. Encrypting/Decrypting an Existing File

Problem

You need a simple way to encrypt an existing file on the filesystem so that only the account used to encrypt the file can decrypt it.

Solution

Use the Decrypt and Encrypt methods of the File class:

 public static void EncryptFile(string fileName) {     File.Encrypt(fileName); } public static void DecryptFile(string fileName) {     File.Decrypt(fileName); } 

Discussion

Both the Encrypt and Decrypt methods of the File class accept a single parameter, a file path/name, and return a void. The filename parameter must be a valid path and name. The result of calling the Encrypt method is an encrypted file that can be unencrypted only by the user who encrypted it in the first place. Calling the Decrypt method decrypts the file.

The Encrypt method is a wrapper around the EncryptFile method in the unmanaged Advapi32.dll, and the Decrypt method is a wrapper around the DecryptFile method, also in Advapi32.dll. These underlying methods require exclusive access to the file that is being encrypted/decrypted. This means that no other process may be currently accessing this file when the Encrypt/Decrypt methods are called. Also be aware that the filesystem must be NTFS or a NotSupportedException will be thrown by the Encrypt/Decrypt method. If the operating system is not Microsoft Windows NT or later, a PlatformNotSupportedException will be thrown and the operation will fail.

Note that before encrypting or decrypting a file, the method will first determine if the file is compressed. If so, the file is decompressed before the encryption/decryption operation can proceed. If you are encrypting/decrypting many compressed files (or files on a compressed disk) you should be aware that this will take more time than if the files are uncompressed.

See Also

See the "File Class" topic in the MSDN documentation.



C# Cookbook
Secure Programming Cookbook for C and C++: Recipes for Cryptography, Authentication, Input Validation & More
ISBN: 0596003943
EAN: 2147483647
Year: 2004
Pages: 424

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net