程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> .NET網頁編程 >> C# >> C#入門知識 >> C#完成對文件停止加密解密的辦法

C#完成對文件停止加密解密的辦法

編輯:C#入門知識

C#完成對文件停止加密解密的辦法。本站提示廣大學習愛好者:(C#完成對文件停止加密解密的辦法)文章只能為提供參考,不一定能成為您想要的結果。以下是C#完成對文件停止加密解密的辦法正文


本文實例講述了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#法式設計有所贊助。

  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved