File encryption Using RFC2898 & Rijndael Symmetric algorithm


Code to encrypt a file using RFC2898derivebytes and Symmetric Encryption with Rijndael

In this following code I would show how can one Encrypt files.
At some point of time one would require to have thier sensitive/personal information to themselves stored in a file,
and again also want to keep it in a way that no one else can read the data,

In the following code I am showing how to encrypt your text(.txt) files, and not decryption
For decryption code watch my other post.
http://dotnetspider.com/resources/40626-Decrypt-Files.aspx


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


System.Security.Cryptography : for encryption
System.IO : for file handling


namespace Crypto_file_encryption
{


public class file_encrypt
{
/// Tag to make sure this file is readable by this class
private const ulong FC_TAG = 0xFC010203040506CF;

/// The amount of bytes to read from the file
private const int BUFFER_SIZE = 128*1024;

/// Checks to see if two byte array are equal
/// the first byte array
/// the second byte array
/// true if b1.Length == b2.Length and each byte in b1 is
/// equal to the corresponding byte in b2

private static bool CheckByteArrays(byte[] b1, byte[] b2)
{
if(b1.Length == b2.Length)
{
for(int i = 0; i < b1.Length; ++i)
{
if(b1[i] != b2[i])
return false;
}
return true;
}
return false;
}


Let us now create Rijndael SymmetricAlgorithm Which uses RFC2898(PBKDF2) to encrypt the contents of the file

/// Creates a Rijndael SymmetricAlgorithm for use in EncryptFile /// the string to use as the password
/// the salt to use with the password
/// A SymmetricAlgorithm for encrypting with Rijndael
private static SymmetricAlgorithm CreateRijndael(string password, byte[] salt)
{
Rfc2898DeriveBytes pdb = new Rfc2898DeriveBytes(password,salt,1000);

SymmetricAlgorithm sma = Rijndael.Create();
sma.KeySize = 256;
sma.Key = pdb.GetBytes(32);
sma.Padding = PaddingMode.PKCS7;
return sma;
}


Now here we create RandomBytes for the Salt that will be later used by the Rijndael SymmetricAlgorithm
what is salt ? Go here :http://dotnetspider.com/resources/40614-PBKDF-Rfc-DeriveBytes-Encryption.aspx

/// Crypto Random number generator for use in EncryptFile
private static RandomNumberGenerator rand = new RNGCryptoServiceProvider();

/// Generates a specified amount of random bytes
/// the number of bytes to return
/// a byte array of count size filled with random bytes
private static byte[] GenerateRandomBytes(int count)
{
byte[] bytes = new byte[count];
rand.GetBytes(bytes);
return bytes;
}




Now the Encryption function:
I have explained the process in each steps, read through the code, any doubt reply back.

/// This takes an input file and encrypts it into the output file
/// the file to encrypt
/// the file to write the encrypted data to
/// the password for use as the key
/// the method to call to notify of progress

public static void Encrypt_File(string inFile, string outFile, string password)
{
using(FileStream fin = File.OpenRead(inFile),
fout = File.OpenWrite(outFile))
{
long lSize = fin.Length; // the size of the input file for storing
int size = (int)lSize; // the size of the input file for progress
byte[] bytes = new byte[BUFFER_SIZE]; // the buffer
int read = -1; // the amount of bytes read from the input file
int value = 0; // the amount overall read from the input file for progress

// generate IV and Salt
byte[] IV = GenerateRandomBytes(16);
byte[] salt = GenerateRandomBytes(16);

// create the crypting object
SymmetricAlgorithm sma = file_encrypt.CreateRijndael(password, salt);
sma.IV = IV;

// write the IV and salt to the beginning of the file
fout.Write(IV,0,IV.Length);
fout.Write(salt,0,salt.Length);

// create the hashing and crypto streams
HashAlgorithm hasher = SHA256.Create();
using(CryptoStream cout = new CryptoStream(fout,sma.CreateEncryptor(),CryptoStreamMode.Write),
chash = new CryptoStream(Stream.Null,hasher,CryptoStreamMode.Write))
{
// write the size of the file to the output file
BinaryWriter bw = new BinaryWriter(cout);
bw.Write(lSize);

// write the file cryptor tag to the file
bw.Write(FC_TAG);

// read and the write the bytes to the crypto stream in BUFFER_SIZEd chunks
while( (read = fin.Read(bytes,0,bytes.Length)) != 0 )
{
cout.Write(bytes,0,read);
chash.Write(bytes,0,read);
value += read;

}
// flush and close the hashing object
chash.Flush();
chash.Close();

// read the hash
byte[] hash = hasher.Hash;

// write the hash to the end of the file
cout.Write(hash,0,hash.Length);

// flush and close the cryptostream
cout.Flush();
cout.Close();
}
}
}
}
}


How to use this class & its member function?


/////////////

using Crypto_file_encryption;

/////////////

string Path = "My_file.txt";
string My_File = Path;
string Encrypted_File = Path + ".my";

file_encrypt.Encrypt_File(My_File, Encrypted_File, "p@$$w0Rd");



For Decryption Algorithm Look for my other post on decryption.
http://dotnetspider.com/resources/ViewResource.aspx?resourceId=40626

How to implement it Look for my other post on Implementation.
http://dotnetspider.com/resources/40632-Retrive-username-password-with-password-username.aspx


Hope that you enjoy the code.
One suggestion : Play with this piece of code, and let us know what all have you discovered.
Like how can other file formats can be encrypted, but remember before you start, make a
backup of the file in which you are going to implement the encryption/decryption, you definitely
don't want to lose your important documents

Cheers
PAUL


Comments

Author: Mrinmay Paul16 Sep 2010 Member Level: Gold   Points : 1

A question !!!!
Go here:
http://dotnetspider.com/forum/264667-A-flaw-my-application.aspx



  • Do not include your name, "with regards" etc in the comment. Write detailed comment, relevant to the topic.
  • No HTML formatting and links to other web sites are allowed.
  • This is a strictly moderated site. Absolutely no spam allowed.
  • Name:
    Email: