307010 HOW TO:使用 C# .NET 加密和解密文件 (From MKBA)

本文的发布号曾为 CHS307010
本文讨论一种 Microsoft 产品的 Beta 版本。本文中的信息按“原样”提供,如有更改恕不另行通知。

对于该 Beta 产品,Microsoft 不提供正式的产品支持。有关获取对 Beta 版本的支持的信息,请参阅 Beta 产品文件中包括的文档资料,或查看您下载此版本的站点。

有关本文的 Microsoft Visual Basic .NET 版本,请参见 301070

本任务的内容

概要

本文演示如何使用 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. SystemSystem.SecuritySystem.Security.CryptographySystem.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 的方法,该方法带有三个参数: sInputFilesOutputFile 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();
    }
  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 站点: 返回页首








这篇文章中的信息适用于:

  • Microsoft Visual C# .NET Beta 2
最近更新:2001-11-5 (1.0)
关键字kbhowto kbHOWTOmaster KB307010 kbAudDeveloper
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值