How to Use Visual C # to encrypt and decrypt files

Source: Internet
Author: User

This article references the following Microsoft. NET Framework class library namespace: • system. Io
• System. Security
• System. Security. Cryptography

This page
Summary
This article describes how to use the Encryption Class provided by Microsoft. NET Framework to encrypt a text file to make it unreadable, And Then decrypt the information to restore it to the original format.
 
Requirements
The recommended hardware, software, network architecture, and required service packs are listed below: • Microsoft Windows 2000 Professional, Windows 2000 Server, Windows 2000 Advanced Server, Windows NT 4.0 Server, or Microsoft Windows XP Professional
• Microsoft Visual Studio 2005 or Microsoft Visual Studio. NET

 
Encryption and decryption
The system. Security. Cryptographic namespace in Microsoft. NET Framework provides a variety of tools to help you encrypt and decrypt data. The cryptostream class is one of the many classes provided. The cryptostream class is designed to encrypt and decrypt content when the content is output as a stream to a file.
 
Encrypted File
To encrypt a file, follow these steps: 1. Start Visual Studio 2005 or Visual Studio. NET.
2. Click "Visual C #" under "project", and then click "console application" under "template ". Visual C #. Net creates a static class and an empty main () process for you.
3. Use the using statement for the following namespace (as shown in the following sample code): • System
• System. Security
• System. Security. Cryptography
• System. Text
• System. Io
In this way, you do not have to restrict declarations from these namespaces in subsequent code. These statements must be prior to any other statement.
Using system;
Using system. IO;
Using system. Security;
Using system. Security. cryptography;
Using system. runtime. interopservices;
Using system. text;

4. Generate a key to encrypt and decrypt data. Descryptoserviceprovider is based on a symmetric encryption algorithm. Symmetric encryption requires keys and Initialization vectors (iv) to encrypt data. To decrypt the data, you must have the same key and IV. You must also use the same encryption algorithm. You can use either of the following methods to generate a key: • method 1 You can prompt the user to enter the password. Then, use the password as the key and IV.
• Method 2 when you create a new instance of the symmetric encryption class, a new key and IV are automatically created for the session. Use keys and IV generated by managed symmetric encryption classes to encrypt and decrypt files.

For more information about how to generate and distribute keys, see the Microsoft. NET Framework SDK documentation or visit the following Microsoft Developer Network (msdn) Website:
Generate a key for encryption and decryption
Http://msdn.microsoft.com/library/default.asp? Url =/library/en-US/cpguide/html/cpcongeneratingkeysforencryptiondecryption. asp (http://msdn.microsoft.com/library/default.asp? Url =/library/en-US/cpguide/html/cpcongeneratingkeysforencryptiondecryption. asp)
 
5. Add the following function to generate a new key for the session (as described in method 2 in step 4 ):
// Call this function to remove the key from memory after use for security.
[System. runtime. interopservices. dllimport ("kernel32.dll", entrypoint = "rtlzeromemory")]
Public static extern bool zeromemory (ref string destination, int length );

// Function to generate a 64 bits key.
Static string generatekey ()
{
// Create an instance of symetric algorithm. Key and IV is generated automatically.
Descryptoserviceprovider descrypto = (descryptoserviceprovider) descryptoserviceprovider. Create ();

// Use the automatically generated key for encryption.
Return asciiencoding. ASCII. getstring (descrypto. Key );
}
6. Create a method named encryptfile in your class. The encryptfile class must have the following three parameters: • sinputfilename
• Soutputfilename
• Skey (the key used to encrypt and decrypt files .)

Static void encryptfile (string sinputfilename,
String soutputfilename,
String skey)

7. Create an input filestream object and an output filestream object during the encryptfile process. These objects can be read from and written to the target file.
Filestream fsinput = new filestream (sinputfilename,
Filemode. Open,
Fileaccess. Read );

Filestream fsencrypted = new filestream (soutputfilename,
Filemode. Create,
Fileaccess. Write );

8. Declare an instance of the descryptoserviceprovider class. This indicates the actual encryption and decryption technology used for files. If you prefer rsasecutiry or another encryption technology, you can create a different provider.
Descryptoserviceprovider des = new descryptoserviceprovider ();

9. Keys must be provided to the encryption provider in the form of byte arrays. The system. Text namespace provides a function named getbytes. One of the encoding features of the getbytes () function is that it takes a string and returns a byte array. Different encryption technologies use different key lengths. For example, the Data Encryption Standard (DES) uses a 64-bit key that is equal to 8 bytes or 8 characters.

If you do not provide a key, the provider generates a random key. This will successfully encrypt the file, but the file cannot be decrypted. Note that you must also provide the initialization vector (IV ). This value is used as part of the encryption. Similar to the key, if you do not provide IV, the provider generates a random one. Because the value must be the same for encryption and decryption, the provider cannot randomly generate these values.
Des. Key = asciiencoding. ASCII. getbytes (skey );
Des. IV = asciiencoding. ASCII. getbytes (skey );

10. Create a cryptostream class instance by using the encrypted provider to obtain an encrypted object (createencryptor) and using the existing output filestream object as part of the constructor.
Icryptotransform desencrypt = des. createencryptor ();
Cryptostream = new cryptostream (fsencrypted,
Desencrypt,
Cryptostreammode. Write );

11. Read the input file and write it to the output file. Pass the cryptostream object, and the file will be encrypted using the key you provided.
Byte [] bytearrayinput = new byte [fsinput. Length-1];
Fsinput. Read (bytearrayinput, 0, bytearrayinput. Length );
Cryptostream. Write (bytearrayinput, 0, bytearrayinput. Length );

 
Decrypt a file
To decrypt a file, follow these steps: 1. Create a method and name it decryptfile. The decryption process is similar to the encryption process, but there are two key differences between the decryptfile process and the encryptfile process. • The cryptostream object is created using createdecryptor instead of createencryptor, which specifies the usage of the object.
• When the decrypted text is written to the target file, the cryptostream object is now the source, not the Target stream.

Static void decryptfile (string sinputfilename,
String soutputfilename,
String skey)
{
Descryptoserviceprovider des = new descryptoserviceprovider ();
// A 64-bit key and IV is required for this provider.
// Set secret key for DES algorithm.
Des. Key = asciiencoding. ASCII. getbytes (skey );
// Set initialization vector.
Des. IV = asciiencoding. ASCII. getbytes (skey );

// Create a file stream to read the encrypted file back.
Filestream fsread = new filestream (sinputfilename,
Filemode. Open,
Fileaccess. Read );
// Create a des decryptor from the des instance.
Icryptotransform desdecrypt = des. createdecryptor ();
// Create crypto stream set to read and do
// Des Decryption Transform on incoming bytes.
Cryptostream cryptostreamdecr = new cryptostream (fsread,
Desdecrypt,
Cryptostreammode. Read );
// Print the contents of the decrypted file.
Streamwriter fsdecrypted = new streamwriter (soutputfilename );
Fsdecrypted. Write (New streamreader (cryptostreamdecr). readtoend ());
Fsdecrypted. Flush ();
Fsdecrypted. Close ();
}

2. Add the following lines to the main () process to call encryptfile and decryptfile:
Static void main ()
{
// Must be 64 bits, 8 bytes.
// Distribute this key to the user who will decrypt this file.
String ssecretkey;

// Get the key for the file to encrypt.
Ssecretkey = generatekey ();

// For additional security pin the key.
Gchandle gch = gchandle. alloc (ssecretkey, gchandletype. Pinned );

// Encrypt the file.
Encryptfile (@ "C: \ mydata.txt ",
@ "C: \ encrypted.txt ",
Ssecretkey );

// Decrypt the file.
Decryptfile (@ "C: \ encrypted.txt ",
@ "C: \ decrypted.txt ",
Ssecretkey );

// Remove the key from memory.
Zeromemory (gch. addrofpinnedobject (), ssecretkey. length * 2 );
Gch. Free ();
}
3. Save the file. Run your application. Make sure that the path used by the input file name points to an existing file.

Test process
Use a text file (.txt) to test the code and confirm that it can be correctly encrypted and decrypted. Make sure that the file is decrypted to a new file (as shown in the main () process in this article), rather than to the original file. Check the decrypted file and compare it with the original file.
 
Complete code list
Using system;
Using system. IO;
Using system. Security;
Using system. Security. cryptography;
Using system. runtime. interopservices;
Using system. text;

Namespace csencryptdecrypt
{
Class class1
{
// Call this function to remove the key from memory after use for security
[System. runtime. interopservices. dllimport ("kernel32.dll", entrypoint = "rtlzeromemory")]
Public static extern bool zeromemory (intptr destination, int length );

// Function to generate a 64 bits key.
Static string generatekey ()
{
// Create an instance of symetric algorithm. Key and IV is generated automatically.
Descryptoserviceprovider descrypto = (descryptoserviceprovider) descryptoserviceprovider. Create ();

// Use the automatically generated key for encryption.
Return asciiencoding. ASCII. getstring (descrypto. Key );
}

Static void encryptfile (string sinputfilename,
String soutputfilename,
String skey)
{
Filestream fsinput = new filestream (sinputfilename,
Filemode. Open,
Fileaccess. Read );

Filestream fsencrypted = new filestream (soutputfilename,
Filemode. Create,
Fileaccess. Write );
Descryptoserviceprovider des = new descryptoserviceprovider ();
Des. Key = asciiencoding. ASCII. getbytes (skey );
Des. IV = asciiencoding. ASCII. getbytes (skey );
Icryptotransform desencrypt = des. createencryptor ();
Cryptostream = new cryptostream (fsencrypted,
Desencrypt,
Cryptostreammode. Write );

Byte [] bytearrayinput = new byte [fsinput. Length];
Fsinput. Read (bytearrayinput, 0, bytearrayinput. Length );
Cryptostream. Write (bytearrayinput, 0, bytearrayinput. Length );
Cryptostream. Close ();
Fsinput. Close ();
Fsencrypted. Close ();
}

Static void decryptfile (string sinputfilename,
String soutputfilename,
String skey)
{
Descryptoserviceprovider des = new descryptoserviceprovider ();
// A 64-bit key and IV is required for this provider.
// Set secret key for DES algorithm.
Des. Key = asciiencoding. ASCII. getbytes (skey );
// Set initialization vector.
Des. IV = asciiencoding. ASCII. getbytes (skey );

// Create a file stream to read the encrypted file back.
Filestream fsread = new filestream (sinputfilename,
Filemode. Open,
Fileaccess. Read );
// Create a des decryptor from the des instance.
Icryptotransform desdecrypt = des. createdecryptor ();
// Create crypto stream set to read and do
// Des Decryption Transform on incoming bytes.
Cryptostream cryptostreamdecr = new cryptostream (fsread,
Desdecrypt,
Cryptostreammode. Read );
// Print the contents of the decrypted file.
Streamwriter fsdecrypted = new streamwriter (soutputfilename );
Fsdecrypted. Write (New streamreader (cryptostreamdecr). readtoend ());
Fsdecrypted. Flush ();
Fsdecrypted. Close ();
}

Static void main ()
{
// Must be 64 bits, 8 bytes.
// Distribute this key to the user who will decrypt this file.
String ssecretkey;

// Get the key for the file to encrypt.
Ssecretkey = generatekey ();

// For additional security pin the key.
Gchandle gch = gchandle. alloc (ssecretkey, gchandletype. Pinned );

// Encrypt the file.
Encryptfile (@ "C: \ mydata.txt ",
@ "C: \ encrypted.txt ",
Ssecretkey );

// Decrypt the file.
Decryptfile (@ "C: \ encrypted.txt ",
@ "C: \ decrypted.txt ",
Ssecretkey );

// Remove the key from memory.
Zeromemory (gch. addrofpinnedobject (), ssecretkey. length * 2 );
Gch. Free ();
}
}
}

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.