码迷,mamicode.com
首页 > Windows程序 > 详细

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

时间:2019-04-10 16:28:15      阅读:160      评论:0      收藏:0      [点我收藏+]

标签:ide   security   close   小伙伴   was   bytes   files   lin   代码段   

如下的代码段是关于C#对文件进行加密解密的代码,应该是对小伙伴们有些帮助。

using System;
using System.IO;
using System.Security.Cryptography;

public class Example19_9
{
public static void Main()
{

    FileStream fsOut = File.Create(@"c:tempencrypted.txt");

    TripleDESCryptoServiceProvider tdes =
        new TripleDESCryptoServiceProvider();

    CryptoStream cs = new CryptoStream(fsOut, tdes.CreateEncryptor(),
        CryptoStreamMode.Write);

    StreamWriter sw = new StreamWriter(cs);

    sw.WriteLine("‘Twas brillig, and the slithy toves");
    sw.WriteLine("Did gyre and gimble in the wabe.");
    sw.Flush();
    sw.Close();

    FileStream fsKeyOut = File.Create(@"c:\tempencrypted.key");

    BinaryWriter bw = new BinaryWriter(fsKeyOut);

    bw.Write( tdes.Key );
    bw.Write( tdes.IV );

    bw.Flush();
    bw.Close();

}

}

解密代码如下

using System;
using System.IO;
using System.Security.Cryptography;

public class Example19_10
{
public static void Main()
{

    TripleDESCryptoServiceProvider tdes =
        new TripleDESCryptoServiceProvider();

    FileStream fsKeyIn = File.OpenRead(@"c:tempencrypted.key");

    BinaryReader br = new BinaryReader(fsKeyIn);

    tdes.Key = br.ReadBytes(24);
    tdes.IV = br.ReadBytes(8);

    FileStream fsIn = File.OpenRead(@"c:\temp\encrypted.txt");

    CryptoStream cs = new CryptoStream(fsIn, tdes.CreateDecryptor(),
        CryptoStreamMode.Read);

    StreamReader sr = new StreamReader(cs);

    Console.WriteLine(sr.ReadToEnd());
    sr.Close();

}

}

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

标签:ide   security   close   小伙伴   was   bytes   files   lin   代码段   

原文地址:https://blog.51cto.com/14129393/2376628

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!