C#怎样对保存文件加密

 时间:2024-10-12 03:46:32

1、本文实例讲述了C#实现对文件进行加密解密的方法。

C#怎样对保存文件加密

2、加密代码:using System; using System.I蚪嬷吃败O; using System.Security.Cryptography; public c造婷用痃lass 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(); } }

C#怎样对保存文件加密

3、解密代码如下: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#怎样对保存文件加密
  • 安装固态盘出错
  • 武林外传怎么取消翅膀
  • 逆水寒虚拟内存怎么设置
  • Win7下查看DirectX版本
  • win11通过注册表禁用控制面板
  • 热门搜索
    孝敬父母手抄报内容 弘扬法治精神手抄报 科普知识手抄报版面 我的成长足迹手抄报 好看的手抄报图片大全 小学生国庆节手抄报 五一英语手抄报 英语手抄报的英文 读书的手抄报图片 儿童手抄报模板