国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 編程 > C# > 正文

C#對文件進行加密解密代碼

2019-10-29 21:41:44
字體:
來源:轉載
供稿:網友

本文給大家分享的是使用C#對文件進行加密解密的代碼,十分的簡單實用,有需要的小伙伴可以參考下。

加密代碼

 

 
  1. using System; 
  2. using System.IO; 
  3. using System.Security.Cryptography; 
  4.  
  5. public class Example19_9 
  6. public static void Main() 
  7.  
  8. // Create a new file to work with 
  9. FileStream fsOut = File.Create(@"c:/temp/encrypted.txt"); 
  10.  
  11. // Create a new crypto provider 
  12. TripleDESCryptoServiceProvider tdes = 
  13. new TripleDESCryptoServiceProvider(); 
  14.  
  15. // Create a cryptostream to encrypt to the filestream 
  16. CryptoStream cs = new CryptoStream(fsOut, tdes.CreateEncryptor(), 
  17. CryptoStreamMode.Write); 
  18.  
  19. // Create a StreamWriter to format the output 
  20. StreamWriter sw = new StreamWriter(cs); 
  21.  
  22. // And write some data 
  23. sw.WriteLine("'Twas brillig, and the slithy toves"); 
  24. sw.WriteLine("Did gyre and gimble in the wabe."); 
  25. sw.Flush(); 
  26. sw.Close(); 
  27.  
  28. // save the key and IV for future use 
  29. FileStream fsKeyOut = File.Create(@"c://temp/encrypted.key"); 
  30.  
  31. // use a BinaryWriter to write formatted data to the file 
  32. BinaryWriter bw = new BinaryWriter(fsKeyOut); 
  33.  
  34. // write data to the file 
  35. bw.Write( tdes.Key ); 
  36. bw.Write( tdes.IV ); 
  37.  
  38. // flush and close 
  39. bw.Flush(); 
  40. bw.Close(); 
  41.  
  42.  

解密代碼如下

 

 
  1. using System; 
  2. using System.IO; 
  3. using System.Security.Cryptography; 
  4.  
  5. public class Example19_10 
  6. public static void Main() 
  7.  
  8. // Create a new crypto provider 
  9. TripleDESCryptoServiceProvider tdes = 
  10. new TripleDESCryptoServiceProvider(); 
  11.  
  12. // open the file containing the key and IV 
  13. FileStream fsKeyIn = File.OpenRead(@"c:/temp/encrypted.key"); 
  14.  
  15. // use a BinaryReader to read formatted data from the file 
  16. BinaryReader br = new BinaryReader(fsKeyIn); 
  17.  
  18. // read data from the file and close it 
  19. tdes.Key = br.ReadBytes(24); 
  20. tdes.IV = br.ReadBytes(8); 
  21.  
  22. // Open the encrypted file 
  23. FileStream fsIn = File.OpenRead(@"c://temp//encrypted.txt"); 
  24.  
  25. // Create a cryptostream to decrypt from the filestream 
  26. CryptoStream cs = new CryptoStream(fsIn, tdes.CreateDecryptor(), 
  27. CryptoStreamMode.Read); 
  28.  
  29. // Create a StreamReader to format the input 
  30. StreamReader sr = new StreamReader(cs); 
  31.  
  32. // And decrypt the data 
  33. Console.WriteLine(sr.ReadToEnd()); 
  34. sr.Close(); 
  35.  
  36.  

以上所述就是本文的全部內容了,希望大家能夠喜歡。

發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 通江县| 厦门市| 黄石市| 江孜县| 弥渡县| 仁寿县| 诏安县| 古丈县| 凤庆县| 西宁市| 高邮市| 南京市| 南平市| 来安县| 上饶县| 定结县| 宁津县| 恩施市| 察雅县| 石渠县| 阿坝县| 汝南县| 罗江县| 潮州市| 建瓯市| 平塘县| 渝北区| 福建省| 托克逊县| 全南县| 苍梧县| 板桥市| 武强县| 富民县| 霍邱县| 柳州市| 手机| 溆浦县| 新密市| 呼和浩特市| 旌德县|