C#实现对文件进行加密解密的方法
发布时间:2020-12-15 03:49:53 所属栏目:百科 来源:网络整理
导读:本篇章节讲解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 FileStre
本篇章节讲解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:tempencrypted.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:tempencrypted.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:tempencrypted.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:tempencrypted.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#程序设计有所帮助。 (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |