Go Back   TechArena Community > Software > Software Development
Become a Member!
Forgot your username/password?
Tags Active Topics RSS Search Mark Forums Read

Reply
 
Thread Tools Search this Thread
  #1  
Old 01-07-2009
Member
 
Join Date: Nov 2008
Posts: 97
Need to learn decryption of files in c#

Hi,

Need to learn decryption of files in c#

Please help me or guide me to right direction.
Reply With Quote
  #2  
Old 01-07-2009
Member
 
Join Date: Oct 2008
Posts: 101
Re: Need to learn decryption of files in c#

There are two methods: encryptFile and decryptFile. They both require that you pass in the filenames and paths of the source and destination files as strings. It is important that the user has the necessary files rights to create the encrypted file.

Code:
 ///<summary>
        /// Steve Lydford - 12/05/2008.
        ///
        /// Encrypts a file using Rijndael algorithm.
        ///</summary>
        ///<param name="inputFile"></param>
        ///<param name="outputFile"></param>
        private void EncryptFile(string inputFile, string outputFile)
        {
 
            try
            {
                string password = @"myKey123"; // Your Key Here
                UnicodeEncoding UE = new UnicodeEncoding();
                byte[] key = UE.GetBytes(password);
 
                string cryptFile = outputFile;
                FileStream fsCrypt = new FileStream(cryptFile, FileMode.Create);
 
                RijndaelManaged RMCrypto = new RijndaelManaged();
 
                CryptoStream cs = new CryptoStream(fsCrypt,
                    RMCrypto.CreateEncryptor(key, key),
                    CryptoStreamMode.Write);
 
                FileStream fsIn = new FileStream(inputFile, FileMode.Open);
 
                int data;
                while ((data = fsIn.ReadByte()) != -1)
                    cs.WriteByte((byte)data);
 
                
                fsIn.Close();
                cs.Close();
                fsCrypt.Close();
            }
            catch
            {
                MessageBox.Show("Encryption failed!", "Error");
            }
        }
        ///<summary>
        /// Steve Lydford - 12/05/2008.
        ///
        /// Decrypts a file using Rijndael algorithm.
        ///</summary>
        ///<param name="inputFile"></param>
        ///<param name="outputFile"></param>
        private void DecryptFile(string inputFile, string outputFile)
        {
 
            {
                string password = @"myKey123"; // Your Key Here
 
                UnicodeEncoding UE = new UnicodeEncoding();
                byte[] key = UE.GetBytes(password);
 
                FileStream fsCrypt = new FileStream(inputFile, FileMode.Open);
 
                RijndaelManaged RMCrypto = new RijndaelManaged();
 
                CryptoStream cs = new CryptoStream(fsCrypt,
                    RMCrypto.CreateDecryptor(key, key),
                    CryptoStreamMode.Read);
 
                FileStream fsOut = new FileStream(outputFile, FileMode.Create);
 
                int data;
                while ((data = cs.ReadByte()) != -1)
                    fsOut.WriteByte((byte)data);
 
                fsOut.Close();
                cs.Close();
                fsCrypt.Close();
 
            }
        }
Reply With Quote
  #3  
Old 01-07-2009
Member
 
Join Date: May 2008
Posts: 255
Re: Need to learn decryption of files in c#

encrypt and decrypt a file by using Visual C#

Requirements
* Microsoft Windows 2000 Professional, Windows 2000 Server, Windows 2000 Advanced Server, Windows NT 4.0 Server or Microsoft Windows XP Professional
* Microsoft Visual Studio 2005 or Microsoft Visual Studio .NET

Encryption and decryption


The System.Security.Cryptographic namespace in the Microsoft .NET Framework provides a variety of tools to help you with encryption and with decryption. The CryptoStream class is one of the many classes that is provided. The CryptoStream class is designed to encrypt or to decrypt content as it is streamed out to a file.

Encrypt a file


1 Start Visual Studio 2005 or Visual Studio .NET.
2 Click Visual C# under Projects, and then click Console Application under Templates. Visual C# .NET creates a Static class for you, together with an empty Main() procedure.
3 Use the using statement (as indicated in the sample code that follows) on the following namespaces:

* System
* System.Security
* System.Security.Cryptography
* System.Text
* System.IO

so that you do not have to qualify declarations from these namespaces later in your code. You must use these statements before any other declarations.

Code:
using System;
using System.IO;
using System.Security;
using System.Security.Cryptography;
using System.Runtime.InteropServices;
using System.Text;
4 Generate a secret key to encrypt and to decrypt the data. The DESCryptoServiceProvider is based on a symmetric encryption algorithm. The symmetric encryption requires a key and an initialization vector (IV) to encrypt the data. To decrypt the data, you must have the same key and the same IV. You must also use the same encryption algorithm. You can generate the keys by using either of the following methods:

* Method 1 You can prompt the user for a password. Then, use the password as the key and the IV.
* Method 2 When you create a new instance of the symmetric cryptographic classes, a new key and IV are automatically created for the session. Use the key and IV that are generated by the managed symmetric cryptographic classes to encrypt and to decrypt the file.

For more information about how to generate and distribute keys, see the Microsoft .NET Framework SDK Documentation, or see the following Microsoft Developer Network (MSDN) Web site:
Generating keys for encryption and decryption
http://msdn.microsoft.com/library/de...decryption.asp (http://msdn.microsoft.com/library/de...decryption.asp)

5 Add the following function to generate a new key for a session (as noted in Method 2 of step 4):

Code:
//  Call this function to remove the key from memory after use for security.
[System.Runtime.InteropServices.DllImport("KERNEL32.DLL", EntryPoint="RtlZeroMemory")]
public static extern bool ZeroMemory(ref string Destination, int Length);
		
// Function to Generate a 64 bits Key.
static string GenerateKey() 
{
	// Create an instance of Symetric Algorithm. Key and IV is generated automatically.
	DESCryptoServiceProvider desCrypto =(DESCryptoServiceProvider)DESCryptoServiceProvider.Create();

	// Use the Automatically generated key for Encryption. 
	return ASCIIEncoding.ASCII.GetString(desCrypto.Key);
}
6. Create a method in your class that is named EncryptFile. The EncryptFile class must have the following three parameters:

* sInputFilename
* sOutputFilename
* sKey (The secret key that is used to encrypt and decrypt the file.)

Code:
static void EncryptFile(string sInputFilename,
		string sOutputFilename,
		string sKey)
7 In the EncryptFile procedure, create an input FileStream object and an output FileStream object. These objects can be read from and written to the target files.

Code:
FileStream fsInput = new FileStream(sInputFilename, 
				FileMode.Open, 
				FileAccess.Read);

FileStream fsEncrypted = new FileStream(sOutputFilename, 
				FileMode.Create, 
				FileAccess.Write);
8 Declare an instance of the DESCryptoServiceProvider class. This represents the actual encryption and the actual decryption technology that is used on the files. At this point, you can create a different provider if you prefer to use RSAsecutiry or another cryptographic technique.

Code:
DESCryptoServiceProvider DES = new DESCryptoServiceProvider();
9. The cryptographic provider must be provided with your secret key as an array of bytes. The System.Text namespace provides a function that is named GetBytes(). As part of its encoding features, the GetBytes() function takes a string, and then returns an array of bytes. The size of the key is different for each cryptographic technique. For example, Data Encryption Standard (DES) takes a 64-bit key that is equal to 8 bytes or to 8 characters.

If you do not provide a key, the provider randomly generates one. This successfully encrypts the file, but there is no way to decrypt the file. Note that you must also provide the initialization vector (IV). This value is used as part of the encryption. Like the key, the IV is randomly generated if you do not provide the value. Because the values must be the same for the encryption and the decryption, you must not permit random generation of these values.

Code:
DES.Key = ASCIIEncoding.ASCII.GetBytes(sKey);
DES.IV = ASCIIEncoding.ASCII.GetBytes(sKey);
10. Create an instance of the CryptoStream class by using the cryptographic provider to obtain an encrypting object (CreateEncryptor) and the existing output FileStream object as a part of the constructor.
Code:
ICryptoTransform desencrypt = DES.CreateEncryptor();
CryptoStream cryptostream = new CryptoStream(fsEncrypted, 
					desencrypt, 
					CryptoStreamMode.Write);
11. Read in the input file, and then write out to the output file. Pass through the CryptoStream object where the file is encrypted by using the key that you provided.
Code:
byte[] bytearrayinput = new byte[fsInput.Length - 1];
fsInput.Read(bytearrayinput, 0, bytearrayinput.Length);
cryptostream.Write(bytearrayinput, 0, bytearrayinput.Length);
Reply With Quote
Reply

  TechArena Community > Software > Software Development
Tags:



Thread Tools Search this Thread
Search this Thread:

Advanced Search


Similar Threads for: "Need to learn decryption of files in c#"
Thread Thread Starter Forum Replies Last Post
DES encryption and decryption using C or Java sayanmaji Software Development 5 26-11-2010 03:20 AM
Asymmetric Decryption Problem DarrenYoung Software Development 1 20-09-2010 05:46 PM
XML encryption and decryption Anirvinya Software Development 5 03-03-2010 03:31 AM
RSA decryption problem in C# taher Software Development 5 21-01-2010 09:30 PM


All times are GMT +5.5. The time now is 12:19 PM.