欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

C#实现对文件进行加密解密的方法

程序员文章站 2023-11-21 15:38:28
本文实例讲述了c#实现对文件进行加密解密的方法。分享给大家供大家参考。具体如下: using system; using system.io; using s...

本文实例讲述了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();
 }
}

希望本文所述对大家的c#程序设计有所帮助。