A Simple Encryption Function

1:40 AM
First Add This Namespaces
using System;
using System.Collections.Generic;
using System.Text;
using System.Security;
using System.Security.Cryptography;
using System.Runtime.InteropServices;
using System.Text.RegularExpressions;
using System.IO;
using System.Windows.Forms;

Now The Function:
 public void Encrypt(string inputfile,string outputfile,string passPhrase,string saltValue,string hashAlgorithm,int passwordIterations,string initVector,int keySize)
       {
           byte[] initVectorBytes = Encoding.ASCII.GetBytes(initVector);
           byte[] saltValueBytes = Encoding.ASCII.GetBytes(saltValue);

           byte[] plainTextBytes = ReadByteArrayFromFile(inputfile);

           PasswordDeriveBytes password = new PasswordDeriveBytes(passPhrase,saltValueBytes,hashAlgorithm,passwordIterations);

           byte[] keyBytes = password.GetBytes(keySize / 8);
           RijndaelManaged symmetricKey = new RijndaelManaged();
           symmetricKey.Mode = CipherMode.CBC;

           ICryptoTransform encryptor = symmetricKey.CreateEncryptor(keyBytes,initVectorBytes);
           MemoryStream memoryStream = new MemoryStream();
           CryptoStream cryptoStream = new CryptoStream(memoryStream,encryptor,CryptoStreamMode.Write);

           cryptoStream.Write(plainTextBytes, 0, plainTextBytes.Length);


           cryptoStream.FlushFinalBlock();
           byte[] cipherTextBytes = memoryStream.ToArray();

           memoryStream.Close();
           cryptoStream.Close();

           File.WriteAllBytes(outputfile, cipherTextBytes);
       }

0 comments:

Post a Comment