本文引入的命名空间:

  • System.IO
  • System.Security
  • System.Security.Cryptography
  • 本文介绍如何使用 Microsoft .NET Framework 提供的加密类对文本文件进行加密以使其处于不可读状态,然后再对该信息进行解密,以恢复到原来的格式。
    回到顶端

    要求
    下面列出了推荐使用的硬件、软件、网络架构以及所需的 Service Pack:
    Microsoft Windows 2000 Professional、Windows 2000 Server、Windows 2000 Advanced Server、Windows NT 4.0 Server 或 Microsoft Windows XP Professional
    Microsoft Visual Studio 2005 或 Microsoft Visual Studio .NET
    回到顶端

    加密和解密
    Microsoft .NET Framework 中的 System.Security.Cryptographic 命名空间提供了多种帮助您加密和解密的工具。CryptoStream 类就是所提供的诸多类中的一个。CryptoStream 类设计用于在内容以流的形式输出到文件时加密和解密内容。
    回到顶端
    加密文件
    要加密文件,请按照下列步骤操作:
    启动 Visual Studio 2005 或 Visual Studio .NET。
    单击“项目”下的“Visual C#”,然后单击“模板”下的“控制台应用程序”。Visual C# .NET 为您创建一个静态类,以及一个空的 Main() 过程。
    对以下命名空间使用 using 语句(如以下示例代码中所示):
    System
    System.Security
    System.Security.Cryptography
    System.Text
    System.IO
    这样,在后面的代码中就不必从这些命名空间中限定声明了。这些语句必须位于任何其他声明之前。
    using System;
    using System.IO;
    using System.Security;
    using System.Security.Cryptography;
    using System.Runtime.InteropServices;
    using System.Text;

    生成密钥以加密和解密数据。DESCryptoServiceProvider 基于一种对称加密算法。对称加密需要密钥和初始化矢量 (IV) 来加密数据。要解密该数据,您必须拥有此同一密钥和 IV。您还必须使用相同的加密算法。您可以使用下列方法之一生成密钥:
    方法 1 您可以提示用户输入密码。然后,将此密码用作密钥和 IV。
    方法 2 当您创建对称加密类的新实例时,将为会话自动创建一个新的密钥和 IV。使用由受管理的对称加密类生成的密钥和 IV 来加密和解密文件。

    有关如何生成和分发密钥的更多信息,请参见 Microsoft .NET Framework SDK 文档,或访问以下 Microsoft Developer Network (MSDN) 网站:
    生成加密密钥和解密密钥
    http://msdn.microsoft.com/library/default.asp?url=/library/zh-cn/cpguide/html/cpcongeneratingkeysforencryptiondecryption.asp (http://msdn.microsoft.com/library/default.asp?url=/library/zh-cn/cpguide/html/cpcongeneratingkeysforencryptiondecryption.asp)
    添加以下函数为会话生成一个新的密钥(按照步骤 4 的方法 2 中的说明):
    //  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);
    }

    在您的类中创建一个命名为 EncryptFile 的方法。EncryptFile 类必须具有以下 3 个参数:
    sInputFilename
    sOutputFilename
    sKey(用于加密和解密文件的密钥。)
    static void EncryptFile(string sInputFilename,
      string sOutputFilename,
      string sKey)

    在 EncryptFile 过程中,创建一个输入 FileStream 对象和一个输出 FileStream 对象。这些对象可以从目标文件中读取和向其中写入。
    FileStream fsInput = new FileStream(sInputFilename,
        FileMode.Open,
        FileAccess.Read);

    FileStream fsEncrypted = new FileStream(sOutputFilename,
        FileMode.Create,
        FileAccess.Write);

    声明一个 DESCryptoServiceProvider 类的实例。这表示对文件使用的实际加密和解密技术。此时,如果您更喜欢使用 RSAsecutiry 或另一种加密技术,则可以创建一个不同的提供程序。
    DESCryptoServiceProvider DES = new DESCryptoServiceProvider();

    必须以字节数组的形式给加密提供程序提供密钥。System.Text 命名空间提供了一个名为 GetBytes() 的函数。GetBytes() 函数的编码特征之一是,它取一个字符串,然后返回一个字节数组。各种加密技术采用的密钥长度是不相同的。例如,数据加密标准 (DES) 使用等于 8 个字节或 8 个字符的 64 位密钥。

    如果您不提供密钥,提供程序就会随机生成一个密钥。这将成功地加密文件,但是无法解密文件。请注意,您还必须提供初始化矢量 (IV)。该值用作加密的一部分。与密钥相似,如果您未提供 IV,提供程序就会随机生成一个。由于该值对于加密和解密必须相同,所以不能让提供程序随机生成这些值。
    DES.Key = ASCIIEncoding.ASCII.GetBytes(sKey);
    DES.IV = ASCIIEncoding.ASCII.GetBytes(sKey);

    创建一个 CryptoStream 类的实例,方法是:使用加密提供程序获得一个加密对象(CreateEncryptor),并将现有的输出 FileStream 对象作为构造函数的一部分。
    ICryptoTransform desencrypt = DES.CreateEncryptor();
    CryptoStream cryptostream = new CryptoStream(fsEncrypted,
         desencrypt,
         CryptoStreamMode.Write);

    读入输入文件,然后写出到输出文件。传递 CryptoStream 对象,文件将使用您提供的密钥加密。
    byte[] bytearrayinput = new byte[fsInput.Length - 1];
    fsInput.Read(bytearrayinput, 0, bytearrayinput.Length);
    cryptostream.Write(bytearrayinput, 0, bytearrayinput.Length);

    回到顶端

    解密文件
    要解密文件,请按照下列步骤操作:
    创建一个方法,然后将它命名为 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 the contents of the decrypted file.
     StreamWriter fsDecrypted = new StreamWriter(sOutputFilename);
     fsDecrypted.Write(new StreamReader(cryptostreamDecr).ReadToEnd());
     fsDecrypted.Flush();
     fsDecrypted.Close();
    }

    将以下几行添加到 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();
    }

    保存文件。运行您的应用程序。确保输入文件名使用的路径指向一个现有文件。
    测试过程
    用一个文本文件 (.txt) 测试此代码,确认它可对此文件进行正确的加密和解密。确保将文件解密到一个新文件(如本文中的 Main() 过程中所示),而不是解密到原来的文件中。检查解密后的文件,然后与原文件进行比较。
    回到顶端

    完整代码列表

    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(); } } }
    回到顶端

如何使用 Visual C# 加密和解密文件相关推荐

  1. 如何在 Linux 上用密码加密和解密文件

    age 是一个简单的.易于使用的工具,允许你用一个密码来加密和解密文件.age 能帮你这样做.它是一个小型且易于使用的工具,允许你用一个密码加密一个文件,并根据需要解密. age 是一个简单的.易于使 ...

  2. Linux下使用GPG(GnuPG)加密及解密文件

    文章目录 Linux下使用GPG(GnuPG)加密及解密文件 1. 简介 2.环境及版本 3.GPG公钥生成 4.查看公钥 5.查看私钥 6.导出公钥 7.导出私钥 8.加密文件 本机加密 其他电脑加 ...

  3. linux 怎么不检查gpg,如何在Linux上使用GPG加密和解密文件 | MOS86

    如何在Linux上使用GPG加密和解密文件... GnuPrivacy Guard (GPG) allows you to securely encrypt files so that only th ...

  4. aes解压命令 linux,Linux使用tar和openssl加密和解密文件

    欢迎,来自IP地址为:110.247.246.119 的朋友 如果系统中保存有机密和敏感信息,那么采用额外的加密防护措施是十分必要的,尤其是这些文件需要在网络上传输时,对文件进行加密就显得十分重要. ...

  5. gpg加密命令 linux_使用 GPG 加密和解密文件

    目标:使用 GPG 加密文件 发行版:适用于任何发行版 要求:安装了 GPG 的 Linux 或者拥有 root 权限来安装它. 难度:简单 约定: # - 需要使用 root 权限来执行指定命令,可 ...

  6. Html源代码图片解密,通过图片加密、解密文件

    [实例简介] [实例截图] [核心代码] using System; using System.Collections.Generic; using System.ComponentModel; us ...

  7. 使用 OpenSSL 加密和解密文件

    OpenSSL 是一个实用工具,它可以确保其他人员无法打开你的敏感和机密消息. 加密是对消息进行编码的一种方法,这样可以保护消息的内容免遭他人窥视.一般有两种类型: 密钥加密或对称加密 公钥加密或非对 ...

  8. 使用 GPG 加密和解密文件

    目标:使用 GPG 加密文件 发行版:适用于任何发行版 要求:安装了 GPG 的 Linux 或者拥有 root 权限来安装它. 难度:简单 约定: # - 需要使用 root 权限来执行指定命令,可 ...

  9. 用mp3stego来加密与解密文件的几次尝试

    用法来自实验吧的"Canon"隐写题目的灵感. 先来简单的聊一下这道题目,打开题目后发现了一个mp3文件,除此之外还有一枚压缩包.然而压缩包是加密的,看来我们需要通过解出来mp3里 ...

最新文章

  1. controller不跳转页面的几个原因_光知道SpringBoot,不用thymeleaf就太不对了
  2. 【专访英特尔高级首席工程师戴金权】普通数据工程师,如何玩转深度学习?
  3. python 人工智能课程大纲_《人工智能》教学大纲
  4. 用计算机做科学计算是绝对精确的吗,科学计算与数学建模 - osc_3gfjojb2的个人空间 - OSCHINA - 中文开源技术交流社区...
  5. oracle存储日志
  6. BZOJ 3511 土地划分
  7. MySQL视图查询报错:Prepared statement needs to be re-prepared
  8. 工作214:结构 vue操作一个很有意思的报错 [Vue warn]: You may have an infinite update loop in a component
  9. latex 幻灯片演示模板
  10. 云原生全景图之五:应用程序定义和开发层
  11. linux下Qt cannot find -lGL错误的解决方法
  12. C/C++排序算法(5)归并排序
  13. Heavy Transportation
  14. 小技巧 ----- 位运算的一些结论与应用
  15. 李宏毅机器学习HW1_pm2.5prediction(adagrad/gradient descent/SGD)
  16. 中国工程院院士郑纬民:应鼓励从头研发先进的存储系统软件
  17. linux函数入参个数限制,PowerShell函数中限制数组参数个数的例子
  18. vb.net 教程 目录
  19. 【教程】Spire.PDF教程:C# 添加、获取和删除 PDF 自定义文档属性
  20. 城头土命适合做计算机电脑职业,土命人适合的职业

热门文章

  1. 洛谷——P1425 小鱼的游泳时间
  2. 展开和收起动画(jQuery)
  3. Opencv之以图像直方图可视化
  4. 数据库学习--主从复制
  5. git无法上传大文件
  6. php底层开发框架, yaf,swoole,hiphop
  7. WSL2 下的 Docker 配置,使用网易云镜像 + 更改 docker 文件系统(否则无法 apt update)
  8. 装建津说计算机丢失,宽带连接上网时老是连接不上说缺少netcfg.hlp文件怎么办...
  9. java io异常处理_IO流异常处理
  10. js 能实现监听F5页面刷新子iframe 而父页面不刷新