Use RC2 to encrypt and decrypt text file : RC2 « Security « C# / CSharp Tutorial






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

class RC2Sample
{
    static void Main()
    {
        RC2 RC2alg = RC2.Create("RC2");
        string sData = "this is a test";
        string FileName = "Text.txt";

        EncryptTextToFile(sData, FileName, RC2alg.Key, RC2alg.IV);

        string Final = DecryptTextFromFile(FileName, RC2alg.Key, RC2alg.IV);
        Console.WriteLine(Final);
    }

    public static void EncryptTextToFile(String Data, String FileName, byte[] Key, byte[] IV)
    {
        FileStream fStream = File.Open(FileName,FileMode.OpenOrCreate);
        RC2 RC2alg = RC2.Create();
        CryptoStream cStream = new CryptoStream(fStream,RC2alg.CreateEncryptor(Key,IV),CryptoStreamMode.Write); 
        StreamWriter sWriter = new StreamWriter(cStream);
        sWriter.WriteLine(Data);
        sWriter.Close();
        cStream.Close();
        fStream.Close();
    }

    public static string DecryptTextFromFile(String FileName, byte[] Key, byte[] IV)
    {
        FileStream fStream = File.Open(FileName, FileMode.OpenOrCreate);
        RC2 RC2alg = RC2.Create();

        CryptoStream cStream = new CryptoStream(fStream,RC2alg.CreateDecryptor(Key,IV),CryptoStreamMode.Read); 

        StreamReader sReader = new StreamReader(cStream);

        string val = sReader.ReadLine();

        sReader.Close();
        cStream.Close();
        fStream.Close();
        return val;
    }
}








35.22.RC2
35.22.1.Use RC2 to encrypt and decrypt text file