C#對文件進(jìn)行加密解密代碼
更新時間:2015年07月08日 11:05:08 投稿:hebedich
本文給大家分享的是使用C#對文件進(jìn)行加密解密的代碼,十分的簡單實(shí)用,有需要的小伙伴可以參考下。
加密代碼
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();
}
}
以上所述就是本文的全部內(nèi)容了,希望大家能夠喜歡。
您可能感興趣的文章:
- C#實(shí)現(xiàn)老板鍵功能的代碼
- C#生成Word文檔代碼示例
- C#實(shí)現(xiàn)關(guān)閉其他程序窗口或進(jìn)程代碼分享
- C#判斷某個軟件是否已安裝實(shí)現(xiàn)代碼分享
- C#實(shí)現(xiàn)的json序列化和反序列化代碼實(shí)例
- C#代碼性能測試類(簡單實(shí)用)
- C#對稱加密(AES加密)每次生成的結(jié)果都不同的實(shí)現(xiàn)思路和代碼實(shí)例
- C#實(shí)現(xiàn)開機(jī)自動啟動設(shè)置代碼分享
- C#之IO讀寫文件方法封裝代碼
- C#一個簡單的定時小程序?qū)崿F(xiàn)代碼
- C#獲取網(wǎng)頁源代碼的方法
- 10個C#程序員經(jīng)常用到的實(shí)用代碼片段
相關(guān)文章
WinForm使用正則表達(dá)式提取內(nèi)容的方法示例
這篇文章主要介紹了WinForm使用正則表達(dá)式提取內(nèi)容的方法,結(jié)合實(shí)例形式分析了WinForm基于正則匹配獲取指定內(nèi)容的相關(guān)操作技巧,需要的朋友可以參考下2017-05-05
C#8.0默認(rèn)接口實(shí)現(xiàn)的詳細(xì)實(shí)例
Microsoft使用C#8.0發(fā)布了許多新功能,他們引入的主要功能之一是默認(rèn)接口方法。這篇文章主要給大家介紹了關(guān)于C#8.0默認(rèn)接口實(shí)現(xiàn)的相關(guān)資料,需要的朋友可以參考下2021-05-05
UnityRTS實(shí)現(xiàn)相機(jī)移動縮放功能
這篇文章主要為大家詳細(xì)介紹了UnityRTS實(shí)現(xiàn)相機(jī)的移動縮放功能,文中示例代碼介紹的非常詳細(xì),具有一定的參考價值,感興趣的小伙伴們可以參考一下2021-03-03

