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

加密代码

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();

  }

}

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

(0)

相关推荐

  • C#之IO读写文件方法封装代码

    具体不做详细介绍了,直接上代码 /// <summary> /// 功能:FileStream文件流读取文件 /// </summary> /// <param name="filePath">参数:文件路径</param> /// <returns>返回值:StreamReader对象</returns> public static StreamReader ReadFileByFs(string filePat

  • C#判断某个软件是否已安装实现代码分享

    private void button1_Click(object sender, EventArgs e) { if (checkAdobeReader() == true) { MessageBox.Show("有安裝 Adobe Reader "); } else { MessageBox.Show("沒有安裝 Adobe Reader "); } } /// <summary> /// 確認是否有安裝 Adobe Reader /// </

  • C#代码性能测试类(简单实用)

    介绍: 可以很方便的在代码里循环执行 需要测试的函数  自动统计出执行时间,支持多线程. 使用方法: PerformanceTest p = new PerformanceTest(); p.SetCount(10);//循环次数(默认:1) p.SetIsMultithread(true);//是否启动多线程测试 (默认:false) p.Execute( i => { //需要测试的代码 Response.Write(i+"<br>"); System.Threa

  • C#一个简单的定时小程序实现代码

    之前一直觉得定时程序好神秘,后来,当我自己真正写了一个小的定时程序时,发现其实没有想象中的那么难.下面,我分享一下我自己的操作过程,希望能对大家有帮助. 1)在我们的项目中添加引用文件:TaskSchedulerEngine.dll(dll定义了一个ITask接口,定义了两个方法Initialize和HandleConditionsMetEvent): 2)创建一个定时触发的类:SyncTask.cs(类名自己随便定义),该类必须实现接口 ITask.具体代码如下: public class S

  • C#实现关闭其他程序窗口或进程代码分享

    在进行winform开发过程中有时候会需要关闭其他程序或者关闭进程,以前写过一篇相关介绍的文章,今天有同事问起来,于是在次翻出来和大家分享一下. 下面介绍我所知的两种方法,应该对大家有帮助,如果有朋友知道其他的方法,谢谢共享一下. 方法1 ProcName 需要关闭的进程名称 private bool closeProc(string ProcName) { bool result = false; System.Collections.ArrayList procList = new Syst

  • C#实现开机自动启动设置代码分享

    /// <summary> /// 设置程序开机启动 /// 或取消开机启动 /// </summary> /// <param name="started">设置开机启动,或者取消开机启动</param> /// <param name="exeName">注册表中程序的名字</param> /// <param name="path">开机启动的程序路径<

  • 10个C#程序员经常用到的实用代码片段

    1 读取操作系统和CLR的版本 OperatingSystem os = System.Environment.OSVersion; Console.WriteLine("Platform: {0}", os.Platform); Console.WriteLine("Service Pack: {0}", os.ServicePack); Console.WriteLine("Version: {0}", os.Version); Consol

  • C#对称加密(AES加密)每次生成的结果都不同的实现思路和代码实例

    思路:使用随机向量,把随机向量放入密文中,每次解密时从密文中截取前16位,其实就是我们之前加密的随机向量. 代码: public static string Encrypt(string plainText, string AESKey) { RijndaelManaged rijndaelCipher = new RijndaelManaged(); byte[] inputByteArray = Encoding.UTF8.GetBytes(plainText);//得到需要加密的字节数组

  • C#生成Word文档代码示例

    public bool CreateWordFile(string _filename, "数据List或者你C#要写的数据") { #region 开始生成Word try { string strtitle = "任务导出"; object oEndOfDoc = "//endofdoc"; Object Nothing = System.Reflection.Missing.Value; Object filename = _filenam

  • C#实现老板键功能的代码

    C#设置热键隐藏指定窗口的代码 using System; using System.Text; using System.Collections; using System.Runtime.InteropServices; namespace WindowHider { /// <summary> /// Object used to control a Windows Form. /// </summary> public class Window { /// <summ

  • C#实现的json序列化和反序列化代码实例

    using System; using System.Collections.Generic; using System.Web.Script.Serialization; using System.Configuration; using System.Runtime.Serialization.Json; using System.Runtime.Serialization; using System.IO; using System.Text; namespace WebApplicati

  • C#获取网页源代码的方法

    本文实例讲述了C#获取网页源代码的方法.分享给大家供大家参考.具体如下: public string GetPageHTML(string url) { try { HttpWebRequest wr = WebRequest.Create(url) as HttpWebRequest; wr.Method = "get"; wr.Accept = "*/*"; wr.Headers.Add("Accept-Language: zh-cn");

随机推荐