Encrypt Text Using TripleDESCryptoServiceProvider In C#

This snippet uses the TripleDESCryptoServiceProvider Class to encrypt a string and save it to a text file. The key to decrypt the file is also saved into a seperate text file.


  1. using System;
  2. using System.IO;
  3. using System.Security.Cryptography;
  4. public class Encrypt
  5. {
  6.     public static void Main()
  7.     {
  8.         FileStream fStream = File.Create(@"C:\text.txt");
  9.         TripleDESCryptoServiceProvider tdes = new TripleDESCryptoServiceProvider();
  10.         CryptoStream cStream = new CryptoStream(fStream, tdes.CreateEncryptor(), CryptoStreamMode.Write);
  11.         StreamWriter sWriter = new StreamWriter(cStream);
  12.         sWriter.WriteLine("Please encrypt me.");
  13.         sWriter.Flush();
  14.         sWriter.Close();
  15.         FileStream fStreamKey = File.Create(@"C:\key.key");
  16.        
  17.         BinaryWriter bWriter = new BinaryWriter(fStreamKey);
  18.         bWriter.Write( tdes.Key );
  19.         bWriter.Write( tdes.IV );
  20.         bWriter.Flush();
  21.         bWriter.Close();
  22.     }
  23. }

No comments:

Post a Comment