HOW TO:使用 C# .NET 加密和解密文件
察看本文应用于的产品
文章编号 : 307010 
最后修改 : 2001年11月5日 
修订 : 1.0 本文的发布号曾为 CHS307010
本页
 概要 
   要求  
   加密和解密  
     确认它可以使用  
   完整代码列表  
   参考  
 这篇文章中的信息适用于: 概要
本文演示如何使用 Microsoft .NET 框架提供的加密类对文本文件进行加密,使其处于不可读的状态,然后再对该信息进行解密,以恢复到原来的格式。 
 回到顶端 要求 
下表概括了推荐使用的硬件、软件、网络架构以及所需的 Service Pack: • Microsoft Windows 2000 Professional、Windows 2000 Server、Windows 2000 Advanced Server 或 Windows NT 4.0 Server  
• Microsoft Visual Studio .NET   回到顶端 加密和解密 
Microsoft .NET 框架内的 System.Security.Cryptographic 名称空间提供了多种加密和解密辅助工具。 CryptoStream 类就是所提供的诸多类中的一个,在将内容以流的形式输出到文件时,该类用于对内容进行加密或解密。 若要加密文件,请按照下列步骤操作: 1. 打开 Visual Studio .NET。  
2. 在 Microsoft C# .NET 中,新建一个控制台应用程序。Visual C# .NET 为您创建一个静态类,以及一个空的 Main() 过程。  
3. 对 System、System.Security、System.Security.Cryptography、System.Text 和 System.IO 名称空间使用 using 语句,这样,在后面的代码中就不需要限定这些名称空间中的声明了。这些语句必须放在所有其他声明之前。 
using System;
using System.IO;
using System.Security;
using System.Security.Cryptography;
using System.Text;
 
4. 将一个常数添加到您的类中,表示用于加密/解密的密钥。 
//Must be 64 bits, 8 bytes.
private const string sSecretKey = "Password";
 
5. 在您的类中创建一个名为 EncryptFile 的方法,该方法带有三个参数: sInputFile、sOutputFile 和 sKey(用于加密和解密文件的密钥)。 
static void EncryptFile(string sInputFilename,
string sOutputFilename,
string sKey)
 
6. 在 EncryptFile 过程中,创建用于处理目标文件读写操作的输入和输出 FileStream 对象。 
FileStream fsInput = new FileStream(sInputFilename,
FileMode.Open,
FileAccess.Read);FileStream fsEncrypted = new FileStream(sOutputFilename,
FileMode.Create,
FileAccess.Write);
 
7. 声明一个 DESCryptoServiceProvider 类的实例,该实例表示实际采用的文件加密/解密技术。 此时,如果您打算使用 RSA 或另一种加密技术,则可以创建一个不同的提供程序。 
DESCryptoServiceProvider DES = new DESCryptoServiceProvider();
 
8. 必须以字节数组的形式给加密提供程序提供密钥。 System.Text 名称空间提供了一个现成的 GetBytes() 函数(作为其编码功能的一部分),该函数的参数为一个字符串,并返回一个字节数组。 各种加密技术采用的密钥长度是不相同的;数据加密标准 (DES) 使用 64 位密钥,等同于 8 个字节或 8 个字符。 如果您未提供密钥,提供程序就会随机生成一个密钥,该密钥可对文件成功地进行编码,确保无法进行解密。 注意,您还需要提供初始化向量 (IV);该值也是加密过程的一部分,与密钥相似,如果您未提供该值,提供程序就会随机生成一个初始化向量。 由于该值对于加密和解密必须相同,所以不能使用随机生成的值。 
DES.Key = ASCIIEncoding.ASCII.GetBytes(sKey);
DES.IV = ASCIIEncoding.ASCII.GetBytes(sKey);
 
9. 创建一个 CryptoStream 类的实例,方法是:使用加密提供程序获得一个加密对象 (CreateEncryptor),并且将现有的输出 FileStream 对象作为构造函数的一部分。 
ICryptoTransform desencrypt = DES.CreateEncryptor();
CryptoStream cryptostream = new CryptoStream(fsEncrypted,
desencrypt,
CryptoStreamMode.Write);
 
10. 最后,读取输入文件并通过 CryptoStream 对象写入到输出文件,在这一过程中使用提供的密钥对其进行加密。 
byte[] bytearrayinput = new byte[fsInput.Length - 1];
fsInput.Read(bytearrayinput, 0, bytearrayinput.Length);
cryptostream.Write(bytearrayinput, 0, bytearrayinput.Length);
 
11. 创建一个名为 DecryptFile 的方法。 解密过程与加密过程非常相似,但 DecryptFile 与 EncryptFile 过程之间有两个主要的差异。 首先,在创建 CryptoStream 对象时,使用 CreateDecryptor 代替 CreateEncryptor 来指定该对象的使用方式。 其次,在将解密后的文本写入目标文件时,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 out the contents of the decrypted file.
StreamWriter fsDecrypted = new StreamWriter(sOutputFilename);
fsDecrypted.Write(new StreamReader(cryptostreamDecr).ReadToEnd());
fsDecrypted.Flush();
fsDecrypted.Close();
}

解决方案 »

  1.   


    12. 在 Main() 过程中添加代码行以调用 EncryptFile 和 DecryptFile。 
    static void Main(string[] args)
    {
        EncryptFile("c:\\temp\\test.txt",
                "c:\\temp\\Encrypted.txt",
                sSecretKey); DecryptFile("c:\\temp\\Encrypted.txt",
            "c:\\temp\\Decrypted.txt",
            sSecretKey);
    }
     
    13. 保存并运行应用程序,确保输入文件名使用的路径指向一个现有(不是特别重要的)文件。  确认它可以使用 
    用一个文本文件 (.txt) 测试此代码,确认它确实已对文件进行了正确的加密和解密。 确保将文件解密到一个新的文件(如在本文的 Main() 过程中所示),而不是原来的文件。 检查解密后的文件,并与源文件进行比较。 
     回到顶端 完整代码列表 
    using System;
    using System.IO;
    using System.Security;
    using System.Security.Cryptography;
    using System.Text;namespace CSEncryptDecrypt
    {
    /// <summary>
      /// Summary description for Class1.
    /// </summary>
      class Class1
      {
        //Must be 64 bits, 8 bytes.
        private const string sSecretKey = "Password";    static void Main(string[] args)
        {
          EncryptFile("c:\\temp\\test.txt",
            "c:\\temp\\Encrypted.txt",
            sSecretKey);      DecryptFile("c:\\temp\\Encrypted.txt",
            "c:\\temp\\Decrypted.txt",
            sSecretKey);
        }    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 out the contents of the decrypted file.
          StreamWriter fsDecrypted = new StreamWriter(sOutputFilename);
          fsDecrypted.Write(new StreamReader(cryptostreamDecr).ReadToEnd());
          fsDecrypted.Flush();
          fsDecrypted.Close();
        }  }
    }
     回到顶端 参考 
    有关使用 .NET 加密功能的更多信息,以及有关加密的一般性信息,请访问以下 Microsoft Developer Network (MSDN) Web 站点: &#8226; System.Security.Cryptography 参考资料 
    http://msdn.microsoft.com/library/dotnet/cpref/frlrfsystemsecuritycryptography.htm (http://msdn.microsoft.com/library/dotnet/cpref/frlrfsystemsecuritycryptography.htm) 
    &#8226; MSDN Online .NET Developer Center 
    http://msdn.microsoft.com/net (http://msdn.microsoft.com/net)