Decrypt Files


Code to decrypt a file which was was earlier encrypted (using RFC2898derivebytes and Symmetric Encryption with Rijndael)

In this code I would show how can one Decrypt files from previously encrypted file
(http://dotnetspider.com/resources/ViewResource.aspx?resourceId=40625).
Look for the post on how to encrypt a file with a password.


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


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


namespace Crypto_file_decryption
{
/// This is the exception class that is thrown throughout the Decryption process
///
public class CryptoHelpException : ApplicationException
{
public CryptoHelpException(string msg):base(msg){}
}

public class file_decrypt
{
/// 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;
}

/// Creates a Rijndael SymmetricAlgorithm for use in Decrypt_File /// 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;
}

/// Crypto Random number generator for use in Decrypt_File
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 Decryption Method:

/// takes an input file and decrypts it to the output file
///
/// the file to decrypt
/// the to write the decrypted data to
/// the password used as the key
/// the method to call to notify of progress
public static void DecryptFile(string inFile, string outFile, string password)
{
// NOTE: The encrypting algo was so much easier...
// http://dotnetspider.com/resources/ViewResource.aspx?resourceId=40625

// create and open the file streams
using(FileStream fin = File.OpenRead(inFile),
fout = File.OpenWrite(outFile))
{
int size = (int)fin.Length; // the size of the file for progress notification
byte[] bytes = new byte[BUFFER_SIZE]; // byte buffer
int read = -1; // the amount of bytes read from the stream
int value = 0;
int outValue = 0; // the amount of bytes written out

// read off the IV and Salt
byte[] IV = new byte[16];
fin.Read(IV,0,16);
byte[] salt = new byte[16];
fin.Read(salt,0,16);

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

value = 32; // the value for the progress
long lSize = -1; // the size stored in the input stream

// create the hashing object, so that we can verify the file
HashAlgorithm hasher = SHA256.Create();

// create the cryptostreams that will process the file
using(CryptoStream cin = new CryptoStream(fin,sma.CreateDecryptor(),CryptoStreamMode.Read),
chash = new CryptoStream(Stream.Null,hasher,CryptoStreamMode.Write))
{
// read size from file
BinaryReader br = new BinaryReader(cin);
lSize = br.ReadInt64();
ulong tag = br.ReadUInt64();

if(FC_TAG != tag)
throw new CryptoHelpException("File Corrupted!");

//determine number of reads to process on the file
long numReads = lSize / BUFFER_SIZE;

// determine what is left of the file, after numReads
long slack = (long)lSize % BUFFER_SIZE;

// read the buffer_sized chunks
for(int i = 0; i < numReads; ++i)
{
read = cin.Read(bytes,0,bytes.Length);
fout.Write(bytes,0,read);
chash.Write(bytes,0,read);
value += read;
outValue += read;

}

// now read the slack
if(slack > 0)
{
read = cin.Read(bytes,0,(int)slack);
fout.Write(bytes,0,read);
chash.Write(bytes,0,read);
value += read;
outValue += read;

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

// flush and close the output file
fout.Flush();
fout.Close();

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

// get and compare the current and old hash values
byte[] oldHash = new byte[hasher.HashSize / 8];
read = cin.Read(oldHash,0,oldHash.Length);
if((oldHash.Length != read) || (!CheckByteArrays(oldHash,curHash)))
throw new CryptoHelpException("File Corrupted!");
}

// make sure the written and stored size are equal
if(outValue != lSize)
throw new CryptoHelpException("File Sizes don't match!");
}
}
}


}


How to use this class & its member function?


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

using Crypto_file_decryption ;

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

string Path = "My_file.txt.my";
int index = inFile.LastIndexOf(".my");
string My_encrypted_File = Path;
string Decrypted_File = Path.Substring(0, index);;

file_encrypt.Encrypt_File(My_encrypted_File, Decrypted_File , "p@$$w0Rd");



Cheers
PAUL


Comments

Author: Dotnet Developer-201515 Sep 2010 Member Level: Gold   Points : 0

hi

can u change .vb code

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

Hi JK,

I personally feel that there is not much of difference between languages , except for the syntax.
You can easily convert it into .vb if you understood the concept I have put up here.

If you have any doubts regarding the concepts, reply back, I surely will help.

If you want to know how to implement it go for my another post where I have attached a sample application :
http://dotnetspider.com/resources/40632-Retrive-username-password-with-password-username.aspx

If you really need a code converter, have a look here - http://dotnetspider.com/convert/

P.S. I have never tried the tools mentioned here to convert .vb to .cs. I won't take any responsibility for the output .vb code.

Regards
Paul

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: