how to encrypte an image file ?  
Author Message
Zeeshan Ahmed





PostPosted: Visual C# General, how to encrypte an image file ? Top

Hi All

I am saving image files on web server. To secure them i want to encrypt them. How can i achieve this Please give me some solution/suggestion to solve the problem.

Regards




Visual C#6  
 
 
GavH





PostPosted: Visual C# General, how to encrypte an image file ? Top

The basic idea is the same as for any other file, you could just mangle the bytes yourself in some predifned manor, that can be reversed, such as reordering the bytes in the file for example using a method that is available to anyone that wishes to decrypt the image.

.Net has provided the System.Security.Cryptographic namespace for cryptology, and it provides the functionality and methods you would require to encrypt and decrpyt a file by key.

You can read more about encrypting/decrytping a file here : http://support.microsoft.com/kb/307010

Regards


 
 
Zeeshan Ahmed





PostPosted: Visual C# General, how to encrypte an image file ? Top

Dear GavH

I tried code in http://support.microsoft.com/kb/307010, but it does not encrypt an image file. However it encrpt the content of text file successfully.

Is there any other artical/web link

Regards.



 
 
GavH





PostPosted: Visual C# General, how to encrypte an image file ? Top

I presume it is something to do with the way it handles the stream, sorry I have not tried the code example, however another good example of file encryption exists here :

http://www.mastercsharp.com/article.aspx ArticleID=29&&TopicID=6

Regards


 
 
GavH





PostPosted: Visual C# General, how to encrypte an image file ? Top

That article I just posted for you is too outdated to be of any real value, sorry.

Ill see what I can come up


 
 
GavH





PostPosted: Visual C# General, how to encrypte an image file ? Top

I could not find a good example so I made you a bad one based on the previous provided msdn link.

Regards

[Updated due to error in code]

using System;< xml:namespace prefix = o ns = "urn:schemas-microsoft-com:office:office" />

using System.Drawing;

using System.Collections;

using System.ComponentModel;

using System.Windows.Forms;

using System.Data;

using System.IO;

using System.Security;

using System.Security.Cryptography;

using System.Runtime.InteropServices;

using System.Text;

 

namespace CryptoExample

{

      /// <summary>

      /// Summary description for Form1.

      /// </summary>

      public class Form1 : System.Windows.Forms.Form

      {

            private System.Windows.Forms.Button btnBrowse;

            private System.Windows.Forms.TextBox tbKey;

            private System.Windows.Forms.Label label1;

            private System.Windows.Forms.Button btnDecrypt;

            private System.Windows.Forms.Label lblFile;

            /// <summary>

            /// Required designer variable.

            /// </summary>

            private System.ComponentModel.Container components = null;

 

            [DllImport("Kernel32.dll", EntryPoint="RtlZeroMemory", SetLastError=false)]

            static extern void ZeroMemory(IntPtr dest, int size);

 

            public Form1()

            {

                  //

                  // Required for Windows Form Designer support

                  //

                  InitializeComponent();

 

                  //

                  // TODO: Add any constructor code after InitializeComponent call

                  //

            }

 

            /// <summary>

            /// Clean up any resources being used.

            /// </summary>

            protected override void Dispose( bool disposing )

            {

                  if( disposing )

                  {

                        if (components != null)

                        {

                              components.Dispose();

                        }

                  }

                  base.Dispose( disposing );

            }

 

            #region Windows Form Designer generated code

            /// <summary>

            /// Required method for Designer support - do not modify

            /// the contents of this method with the code editor.

            /// </summary>

            private void InitializeComponent()

            {

                  this.btnBrowse = new System.Windows.Forms.Button();

                  this.tbKey = new System.Windows.Forms.TextBox();

                  this.label1 = new System.Windows.Forms.Label();

                  this.btnDecrypt = new System.Windows.Forms.Button();

                  this.lblFile = new System.Windows.Forms.Label();

                  this.SuspendLayout();

                  //

                  // btnBrowse

                  //

                  this.btnBrowse.Location = new System.Drawing.Point(8, 24);

                  this.btnBrowse.Name = "btnBrowse";

                  this.btnBrowse.TabIndex = 0;

                  this.btnBrowse.Text = "Encrypt";

                  this.btnBrowse.Click += new System.EventHandler(this.btnBrowse_Click);

                  //

                  // tbKey

                  //

                  this.tbKey.Location = new System.Drawing.Point(16, 96);

                  this.tbKey.Multiline = true;

                  this.tbKey.Name = "tbKey";

                  this.tbKey.ReadOnly = true;

                  this.tbKey.Size = new System.Drawing.Size(256, 20);

                  this.tbKey.TabIndex = 1;

                  this.tbKey.Text = "";

                  //

                  // label1

                  //

                  this.label1.Location = new System.Drawing.Point(16, 72);

                  this.label1.Name = "label1";

                  this.label1.TabIndex = 2;

                  this.label1.Text = "Key";

                  //

                  // btnDecrypt

                  //

                  this.btnDecrypt.Location = new System.Drawing.Point(16, 168);

                  this.btnDecrypt.Name = "btnDecrypt";

                  this.btnDecrypt.TabIndex = 3;

                  this.btnDecrypt.Text = "Decrypt";

                  this.btnDecrypt.Click += new System.EventHandler(this.btnDecrypt_Click);

                  //

                  // lblFile

                  //

                  this.lblFile.Location = new System.Drawing.Point(16, 48);

                  this.lblFile.Name = "lblFile";

                  this.lblFile.Size = new System.Drawing.Size(280, 23);

                  this.lblFile.TabIndex = 4;

                  //

                  // Form1

                  //

                  this.AutoScaleBaseSize = new System.Drawing.Size(5, 13);

                  this.ClientSize = new System.Drawing.Size(352, 238);

                  this.Controls.Add(this.lblFile);

                  this.Controls.Add(this.btnDecrypt);

                  this.Controls.Add(this.label1);

                  this.Controls.Add(this.tbKey);

                  this.Controls.Add(this.btnBrowse);

                  this.Name = "Form1";

                  this.Text = "Form1";

                  this.ResumeLayout(false);

 

            }

            #endregion

 

            /// <summary>

            /// The main entry point for the application.

            /// </summary>

            [STAThread]

            static void Main()

            {

                  Application.Run(new Form1());

            }

 

            //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);

            }

 

            static void EncryptFile(string sInputFilename,

                  string sOutputFilename,

                  string sKey)

            {

                  FileStream fsInput = new FileStream(sInputFilename,

                        FileMode.Open,

                        FileAccess.Read);

 

                  FileStream fsEncrypted = new FileStream(sOutputFilename,

                        FileMode.Create,

                        FileAccess.Write);

 

                  DESCryptoServiceProvider DES = new DESCryptoServiceProvider();

                  DES.Key = ASCIIEncoding.ASCII.GetBytes(sKey);

                  DES.IV = ASCIIEncoding.ASCII.GetBytes(sKey);

 

                  ICryptoTransform desencrypt = DES.Crea****cryptor();

                  CryptoStream cryptostream = new CryptoStream(fsEncrypted,

                        desencrypt,

                        CryptoStreamMode.Write);

 

                  byte[] bytearrayinput = new byte[fsInput.Length];

                  fsInput.Read(bytearrayinput, 0, bytearrayinput.Length);

                  cryptostream.Write(bytearrayinput, 0, bytearrayinput.Length);

                  cryptostream.Close();

                  fsInput.Close();

                  fsEncrypted.Close();

                             

            }

 

            static void DecryptFile(string sInputFilename,

                  string sOutputFilename,

                  string sKey)

            {

                  DESCryptoServiceProvider DES = new DESCryptoServiceProvider();

                  //A 64 bit key and IV is required for this provider.

                  //Set secret key For DES algorithm.

                  DES.Key = ASCIIEncoding.ASCII.GetBytes(sKey);

                  //Set initialization vector.

                  DES.IV = ASCIIEncoding.ASCII.GetBytes(sKey);

 

 

                  //Create a file stream to read the encrypted file back.

                  FileStream fsread = new FileStream(sInputFilename,

                        FileMode.Open,

                        FileAccess.Read);

 

                  //we also want an output file stream

                  //Create a file stream to read the encrypted file back.

                  FileStream fsout = new FileStream(sOutputFilename,

                        FileMode.Create,

                        FileAccess.Write);

 

                  CryptoStream cs = new CryptoStream(fsout,

                        DES.CreateDecryptor(), CryptoStreamMode.Write);

 

                  /*We had to edit the way the stream was output to be binary friendly*/

 

                  byte[] buffer = new byte[8192];

                  int nRead;

                  do

                  {

                        nRead = fsread.Read(buffer, 0, 8192);

                        cs.Write(buffer, 0, nRead);

                  }while(nRead != 0);

 

                  //clean up

                  cs.Flush();

                  cs.Close();

                  fsread.Close(); 

            }

 

            private void btnBrowse_Click(object sender, System.EventArgs e)

            {

                  using(OpenFileDialog fdlg = new OpenFileDialog())

                  {

                        fdlg.Title = "Select Image File" ;

                        fdlg.InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.Personal);

                        fdlg.Filter = "Image Files(*.jpg; *.jpeg; *.gif; *.bmp; *.png)|*.jpg; *.jpeg; *.gif; *.bmp; *.png";

                        fdlg.RestoreDirectory = true ;

                 

                        if(fdlg.ShowDialog() == DialogResult.OK)

                        {

                              //generate the key

                              string sKey = GenerateKey();

 

                              //you shouldnt really do this as it defies the point of pinning the

                              //key and erasing the memory, however we need a reference to the key

                              //to decrypt

 

                              tbKey.Text = sKey;

 

                              // For additional security Pin the key.

                              GCHandle gch = GCHandle.Alloc(sKey,GCHandleType.Pinned);

 

                              try

                              {                            

                                    lblFile.Text = "";      //blank the filename from previous encryption

                                    //encrypt the file

                                   

                                          tbKey.Text);

                                    lblFile.Text = fdlg.FileName;

                              }

                              catch(Exception ex)

                              {

                                    MessageBox.Show("Opps " + ex.ToString());

                              }

                              finally

                              {

                                    // Remove the Key from memory.

                                    ZeroMemory(gch.AddrOfPinnedObject(), sKey.Length * 2);

                                    gch.Free();

                              }

                        }

                  }

            }

 

            private void btnDecrypt_Click(object sender, System.EventArgs e)

            {

                  if(lblFile.Text != "")

                  {

                        string

                 

                        try

                        {

                             

                                    tbKey.Text);

                        }

                        catch(Exception ex)

                        {

                              MessageBox.Show(ex.ToString());

                        }

                  }

            }          

      }

}

 

 



 
 
Zeeshan Ahmed





PostPosted: Visual C# General, how to encrypte an image file ? Top

I have found the solution from code in following link. Thankyou all of you for your effort and replies.

http://www.codeproject.com/csharp/fileencryptdecrypt.asp

Regards