欢迎来到代码驿站!

.NET代码

当前位置:首页 > 软件编程 > .NET代码

C#对文件进行加密解密代码

时间:2020-12-06 10:15:35|栏目:.NET代码|点击:

加密代码

using System;
using System.IO;
using System.Security.Cryptography;
  
public class Example19_9
{
  public static void Main()
  {
  
    // Create a new file to work with
    FileStream fsOut = File.Create(@"c:\temp\encrypted.txt");
  
    // Create a new crypto provider
    TripleDESCryptoServiceProvider tdes =
      new TripleDESCryptoServiceProvider();
  
    // Create a cryptostream to encrypt to the filestream
    CryptoStream cs = new CryptoStream(fsOut, tdes.CreateEncryptor(),
      CryptoStreamMode.Write);
  
    // Create a StreamWriter to format the output
    StreamWriter sw = new StreamWriter(cs);
  
    // And write some data
    sw.WriteLine("'Twas brillig, and the slithy toves");
    sw.WriteLine("Did gyre and gimble in the wabe.");
    sw.Flush();
    sw.Close();
  
    // save the key and IV for future use
    FileStream fsKeyOut = File.Create(@"c:\\temp\encrypted.key");
  
    // use a BinaryWriter to write formatted data to the file
    BinaryWriter bw = new BinaryWriter(fsKeyOut);
  
    // write data to the file
    bw.Write( tdes.Key );
    bw.Write( tdes.IV );
  
    // flush and close
    bw.Flush();
    bw.Close();
  
  }
  
}

解密代码如下

using System;
using System.IO;
using System.Security.Cryptography;
  
public class Example19_10
{
  public static void Main()
  {
  
    // Create a new crypto provider
    TripleDESCryptoServiceProvider tdes =
      new TripleDESCryptoServiceProvider();
  
    // open the file containing the key and IV
    FileStream fsKeyIn = File.OpenRead(@"c:\temp\encrypted.key");
  
    // use a BinaryReader to read formatted data from the file
    BinaryReader br = new BinaryReader(fsKeyIn);
  
    // read data from the file and close it
    tdes.Key = br.ReadBytes(24);
    tdes.IV = br.ReadBytes(8);
  
    // Open the encrypted file
    FileStream fsIn = File.OpenRead(@"c:\\temp\\encrypted.txt");
  
    // Create a cryptostream to decrypt from the filestream
    CryptoStream cs = new CryptoStream(fsIn, tdes.CreateDecryptor(),
      CryptoStreamMode.Read);
  
    // Create a StreamReader to format the input
    StreamReader sr = new StreamReader(cs);
  
    // And decrypt the data
    Console.WriteLine(sr.ReadToEnd());
    sr.Close();
  
  }
  
}

以上所述就是本文的全部内容了,希望大家能够喜欢。

上一篇:探秘C# 6.0 的新特性

栏    目:.NET代码

下一篇:c# 委托的本质是什么

本文标题:C#对文件进行加密解密代码

本文地址:http://www.codeinn.net/misctech/30103.html

推荐教程

广告投放 | 联系我们 | 版权申明

重要申明:本站所有的文章、图片、评论等,均由网友发表或上传并维护或收集自网络,属个人行为,与本站立场无关。

如果侵犯了您的权利,请与我们联系,我们将在24小时内进行处理、任何非本站因素导致的法律后果,本站均不负任何责任。

联系QQ:914707363 | 邮箱:codeinn#126.com(#换成@)

Copyright © 2020 代码驿站 版权所有