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

2021-06-08 17:06

阅读:322

标签: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

上一篇:Wpf binging(一)

下一篇:C#ThreadPool学习


评论


亲,登录后才可以留言!