???? ID: 307010 - ????? ???????: 29 ??????? 2010 - ??????: 4.0

?????????? ?? ????? C# ?? ????? ?? ???? ????? ?? ????????? ???? ????

?????? ??????This article applies to a different operating system than the one you are using. Article content that may not be relevant to you is disabled.
?? ???? ?? Microsoft Visual Basic .NET ??????? ?? ???, ?????301070  (http://support.microsoft.com/kb/301070/ ) .
?? ???? ?? ???????? ???? ?? ????? Microsoft .NET Framework ????? ????????? ????????:
  • System.IO
  • System.Security
  • System.Security.Cryptography
???:?? ???? Microsoft .NET Framework 2.0 ?? ??? ???? ???? ?????

?? ????? ??

??? ?? ??????? ???? | ??? ?? ??????? ????

??????

This article describes how to use the cryptography classes that are provided by the Microsoft .NET Framework to encrypt a text file to an unreadable state, and then to decrypt that text file back to its original format.

??????????

The following list outlines the recommended hardware, software, network infrastructure, and service packs that you must have:
  • 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

TheSystem.Security.Cryptographicnamespace in the Microsoft .NET Framework provides a variety of tools to help you with encryption and with decryption. TheCryptoStreamclass is one of the many classes that is provided. TheCryptoStreamclass is designed to encrypt or to decrypt content as it is streamed out to a file.

Encrypt a file

To encrypt a file, follow these steps:
  1. Start Visual Studio 2005 or Visual Studio .NET.
  2. ????? ????,Visual C#?? ???????Projects?? ????-????? ????, ?? ???? ???????? ??????????? ???????????????. Visual C# .NET creates aStaticclass for you, together with an emptyMain()procedure.
  3. ?????usingstatement (as indicated in the sample code that follows) on the following namespaces:
    • ??????
    • System.Security
    • System.Security.Cryptography
    • System.Text
    • System.IO
    so that you do not have to qualify declarations from these namespaces later in your code. You must use these statements before any other declarations.
    using System;
    using System.IO;
    using System.Security;
    using System.Security.Cryptography;
    using System.Runtime.InteropServices;
    using System.Text;
    					
  4. Generate a secret key to encrypt and to decrypt the data. TheDESCryptoServiceProvideris based on a symmetric encryption algorithm. The symmetric encryption requires a key and an initialization vector (IV) to encrypt the data. To decrypt the data, you must have the same key and the same IV. ?? ?? ?? ??????????? ?????????? ?? ?? ????? ???? ?????? ?? ?? ?? ????? ??????? ?? ????? ?? ????? ????? ?? ???? ???:
    • ?????? 1:?? ?????????? ?? ??????? ?? ??? ????? ??? ???? ???? ????? ?? IV ?? ??? ???, ?? ??????? ?? ????? ?????
    • ???? 2?? ?? ????????? ??????????????? ???? ?? ?? ?? ??????? ????? ???, ?? ?? ????? ?? IV ???????? ??? ?? ???? ???? ??? ???? ?? ???? IV ???????? ????????? ??????????????? ???? ?? ?????????? ???? ?? ??? ?? ????? ?? ????????? ???? ?? ??? ?????? ??????? ?? ?? ??? ?? ????? ?? ????? ?????

      For more information about how to generate and distribute keys, see the Microsoft .NET Framework SDK Documentation, or see the following Microsoft Developer Network (MSDN) Web site:
      Generating keys 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 a session (as noted in Method 2 of 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 in your class that is namedEncryptFile. TheEncryptFileclass must have the following three parameters:
    • sInputFilename
    • sOutputFilename
    • sKey(The secret key that is used to encrypt and decrypt the file.)
    static void EncryptFile(string sInputFilename,
    		string sOutputFilename,
    		string sKey)
    					
  7. ?????EncryptFileprocedure, create an inputFileStreamobject and an outputFileStream???????? ??? These objects can be read from and written to the target files.
    FileStream fsInput = new FileStream(sInputFilename, 
    				FileMode.Open, 
    				FileAccess.Read);
    
    FileStream fsEncrypted = new FileStream(sOutputFilename, 
    				FileMode.Create, 
    				FileAccess.Write);
    					
  8. Declare an instance of theDESCryptoServiceProviderclass. This represents the actual encryption and the actual decryption technology that is used on the files. At this point, you can create a different provider if you prefer to use RSAsecutiry or another cryptographic technique.
    DESCryptoServiceProvider DES = new DESCryptoServiceProvider();
    					
  9. The cryptographic provider must be provided with your secret key as an array of bytes. TheSystem.Textnamespace provides a function that is namedGetBytes(). ???? ????????? ???????? ?? ?? ??? ?? ??? ???GetBytes()?????? ??? ???????? ???? ??, ?? ???? ??? ?????? ?? ??? ???? ???? ??? ????? ?? ???? ??????????????? ??????? ???????? ?? ??? ????? ??? ?????? ?? ???, ???? ??????????? ???? (DES) ???? 64-??? ????? 8 ?????? ?? 8 ?????? ?? ??? ???? ???

    ??? ?? ??? ????? ?????? ????? ????, ??????? ?????????? ????? ??? ?? encrypts ??????????? ???? ??, ????? ????? ?? ????????? ???? ?? ??? ??? ????? ???? ??? ??? ???? ?? ???? ?? ?????? ??????? vector (IV)? ?? ??? ?? ??????????? ?? ?? ??? ?? ??? ??? ????? ???? ???? ??? ????? ?? ??? IV ?? ?????????? ??????? ??? ?? ??? ?????? ????? ??? ??????????? ?? ?????????? ?? ??? ???? ???? ?????, ??????? ?? ?? ????? ?? ????? ????? ?????? ???? ???? ??????
    DES.Key = ASCIIEncoding.ASCII.GetBytes(sKey);
    DES.IV = ASCIIEncoding.ASCII.GetBytes(sKey);
    					
  10. ?? ??????? ?????CryptoStream???????? ???? encrypting (??????? ???? ?? ??? ??? ???????????????? ??????? ?? ????? ?? ?????CreateEncryptor) ?? ?????? ??????FileStream???????? constructor ?? ???? ??? ?? ??? ??? ???
    ICryptoTransform desencrypt = DES.CreateEncryptor();
    CryptoStream cryptostream = new CryptoStream(fsEncrypted, 
    					desencrypt, 
    					CryptoStreamMode.Write);
    					
  11. ????? ????? ??? ??? ??, ?? ?? ?????? ????? ??? ????? ?? ???? ??? ?? ?????? ?? ??? ????CryptoStream???????? ???? ???? ???? ?????? ?? ?? ????? ?? ????? ?? ???????????? ???
    byte[] bytearrayinput = new byte[fsInput.Length - 1];
    fsInput.Read(bytearrayinput, 0, bytearrayinput.Length);
    cryptostream.Write(bytearrayinput, 0, bytearrayinput.Length);
    					

???? ????? ?? ????????? ????

???? ????? ?? ????????? ????, ????? ????? ?? ???? ????:
  1. ??? ???? ?????, ?? ???? ??? ???? ???DecryptFile. ?????????? ????????? ?? ???? ???? ?? ??????????? ?????????, ??? ??,DecryptFile????????? ??? ?? ?? ????? ????EncryptFile?? ??? 1 ?? ??? ?? ????..
    • CreateDecryptor?? ????? ?? ????? ???? ???? ??CreateEncryptor????? ?? ???CryptoStream????????, ?? ?? ????? ?? ?? ???? ???????? ????? ???? ?? ?????
    • ?? decrypted ??? ?????? ????? ?? ??? ???? ???? ??CryptoStream???????? ?? ?????? ??????? ?? ???? ????? ???
    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 a 
    	//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. ???? ?? ??? ????? ????????? ??????Main()????? ?? ??? ???? ?? ??? ?????????EncryptFile, ??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. ????? ??????.. ???? ????????? ?????? ????????? ???? ?? ?? ????? ???? ??? ?? ??? ????? ???? ???? ?? ?? ???? ?????? ????? ?? ????? ???? ???

????????? ?? ??????? ????

?? ??? ?? ?????? ???? ?? ??? ?????????? ?? ?? ?? ?? ??? ??? ?? ????? ?? ????????? ???? ?? ??? ??? ??? (. txt) ????? ?? ??? ??????? ????? ????????? ???? ?? ????? ???? ?? ????? ?? ????????? (??? ?? ??? ???Main()?? ???? ??? ?????????) ?? ????? ?? ??? ????? ?? ???? Decrypted ????? ?? ??????? ????, ?? ??? ??? ????? ?? ??? ?? ????? ?????

??? ??????? ?????

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 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 a 
         //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();
      }
   }
}

??????

???? ??????? ?? ??? ?????????????? ?? ???? ??? ?? .NET ?? ??????????????? ???????? ?? ????? ???? ?? ???? ???, ????? MSDN ??? ???? ?????:
System.Security.Cryptography ??? ?????
HTTP://MSDN.Microsoft.com/Library/default.asp?URL=/Library/en-us/cpref/HTML/frlrfsystemsecuritycryptography.asp (http://msdn.microsoft.com/library/default.asp?url=/library/en-us/cpref/html/frlrfsystemsecuritycryptography.asp)
Microsoft .NET Framework ?????? ??????
HTTP://msdn2.Microsoft.com/en-us/netframework/default.aspx (http://msdn2.microsoft.com/en-us/netframework/default.aspx)
????? C# .NET ?? ???? ??? ???? ??????? ??????? ?? ??? ????? Usenet ?????? ???? ?????:
Microsoft.public.dotnet.languages.csharp (http://go.microsoft.com/fwlink/?linkid=5217)

???? ???? ???? ??:
  • Microsoft Visual C# 2005
  • Microsoft Visual C# .NET 2003 Standard Edition
  • Microsoft Visual C# .NET 2002 Standard Edition
??????: 
kbsecurity kbio kbcrypt kbhowtomaster kbmt KB307010 KbMthi
???? ?????? ???????????? ?????? ????????
??????????: ?? ???? ?? ???? ??????? ?? ????? ?? Microsoft ????-?????? ?????????? ?????? ?????? ???? ??? ??. Microsoft ???? ??? ????-???????? ?? ????-???????? ????? ?????? ?? ???? ???????? ???? ?? ???? ????? ????? ??? ?? ??? ?????? ?? ???? ???? ???? ??? ????? ??. ???????, ????-???????? ???? ????? ???? ???? ???? ???. ?????, ????????, ?????-???? ?? ??????? ?? ???????? ?? ???? ???, ???? ?? ??? ?????? ???? ???? ??? ????? ??? ?? ???? ??. Microsoft ??????? ??? ???? ?? ?????? ?? ??????????, ????????? ?? ??? ?????? ?? ???? ????? ?? ???? ???????? ?? ??? ???? ????? ?? ??? ????????? ???? ??. Microsoft ????-?????? ?????????? ?? ????? ?????? ?? ?? ??? ??.
?????????? ?? ??????? ????????? ??????? ??:307010  (http://support.microsoft.com/kb/307010/en-us/ )