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

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

程序员文章站 2023-11-21 12:32:28
加密代码 using system; using system.io; using system.security.cryptography; pu...

加密代码

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

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