Csharp/CSharp Tutorial/File Directory Stream/Encrypt Decrypt File — различия между версиями

Материал из .Net Framework эксперт
Перейти к: навигация, поиск
м (1 версия)
 
м (1 версия)
 
(нет различий)

Текущая версия на 12:20, 26 мая 2010

Decrypting a file

using System;
using System.IO;
using System.Security.Cryptography;
class MainClass
{
  public static void Main() 
  {
    TripleDESCryptoServiceProvider tdes = new TripleDESCryptoServiceProvider();
    FileStream fsKeyIn = File.OpenRead(@"c:\encrypted.key");
    
    BinaryReader br = new BinaryReader(fsKeyIn);
    tdes.Key = br.ReadBytes(24);
    tdes.IV = br.ReadBytes(8);
    FileStream fsIn = File.OpenRead(@"c:\encrypted.txt");
    CryptoStream cs = new CryptoStream(fsIn, tdes.CreateDecryptor(),CryptoStreamMode.Read);
    StreamReader sr = new StreamReader(cs);
    Console.WriteLine(sr.ReadToEnd());
    sr.Close();
  }
}
str

Encrypting a file

using System;
using System.IO;
using System.Security.Cryptography;
class MainClass
{
  public static void Main() 
  {
    FileStream fsOut = File.Create(@"c:\encrypted.txt");
    TripleDESCryptoServiceProvider tdes = new TripleDESCryptoServiceProvider();
    CryptoStream cs = new CryptoStream(fsOut, tdes.CreateEncryptor(), CryptoStreamMode.Write);
    StreamWriter sw = new StreamWriter(cs);
    sw.WriteLine("str");
    sw.Flush();
    sw.Close();
    FileStream fsKeyOut = File.Create(@"c:\encrypted.key");
    
    BinaryWriter bw = new BinaryWriter(fsKeyOut);
    bw.Write( tdes.Key );
    bw.Write( tdes.IV );
    bw.Flush();
    bw.Close();
  }
}