Hi all C# experts out there,

I'm currently working on a school project.
When i use the Decrypt method from the Rijndael algorithm,
i would run into a "invalid padding" error when decrypting.
What should i do?

public byte[] Decrypt(byte[] cipherTextBytes)
            {
                // Convert strings defining encryption key characteristics into byte
                // arrays. Let us assume that strings only contain ASCII codes.
                // If strings include Unicode characters, use Unicode, UTF7, or UTF8
                // encoding.
                byte[] initVectorBytes = Encoding.ASCII.GetBytes(initVector);
                byte[] saltValueBytes = Encoding.ASCII.GetBytes(saltValue);

                // Convert our ciphertext into a byte array.


                // First, we must create a password, from which the key will be 
                // derived. This password will be generated from the specified 
                // passphrase and salt value. The password will be created using
                // the specified hash algorithm. Password creation can be done in
                // several iterations.
                PasswordDeriveBytes password = new PasswordDeriveBytes(
                                                                passPhrase,
                                                                saltValueBytes,
                                                                hashAlgorithm,
                                                                passwordIterations);

                // Use the password to generate pseudo-random bytes for the encryption
                // key. Specify the size of the key in bytes (instead of bits).
                byte[] keyBytes = password.GetBytes(keySize / 8);

                // Create uninitialized Rijndael encryption object.
                RijndaelManaged symmetricKey = new RijndaelManaged();

                // It is reasonable to set encryption mode to Cipher Block Chaining
                // (CBC). Use default options for other symmetric key parameters.
                symmetricKey.Mode = CipherMode.CBC;
                symmetricKey.Padding = PaddingMode.PKCS7;
            
                // Generate decryptor from the existing key bytes and initialization 
                // vector. Key size will be defined based on the number of the key 
                // bytes.
                ICryptoTransform decryptor = symmetricKey.CreateDecryptor(
                                                                 keyBytes,
                                                                 initVectorBytes);

                // Define memory stream which will be used to hold encrypted data.
                MemoryStream memoryStream = new MemoryStream(cipherTextBytes);

                // Define cryptographic stream (always use Read mode for encryption).
                CryptoStream cryptoStream = new CryptoStream(memoryStream,
                                                              decryptor,
                                                              CryptoStreamMode.Read);

                // Since at this point we don't know what the size of decrypted data
                // will be, allocate the buffer long enough to hold ciphertext;
                // plaintext is never longer than ciphertext.
                byte[] plainTextBytes = new byte[cipherTextBytes.Length];

                // Start decrypting.
                int decryptedByteCount = cryptoStream.Read(plainTextBytes,
                                                           0,
                                                           plainTextBytes.Length);

                // Close both streams.
                memoryStream.Close();
                cryptoStream.Close();

                // Convert decrypted data into a string. 
                // Let us assume that the original plaintext string was UTF8-encoded.

                // Return decrypted string.   
                return plainTextBytes;
            }
        }


    }

Please use code tags when you post code on daniweb:

[code=c#] ...code here...

[/code]

Can you .zip your project and upload it? You can do this my clicking "Go Advanced" then "Manage Attachments" and uploading the archive. Are you calling symmetricKey.Padding = PaddingMode.PKCS7; in your method that encrypts that data?

> Actually it should be [code=csharp]. "c#" isn't really a language in our code highlighter.[code=c#]
Actually it should be . "c#" isn't really a language in our code highlighter.[code=csharp]. "c#" isn't really a language in our code highlighter.

commented: oops +6

Thanks for the fast response !
Unfortunenately, I couldn't attach the C# form 1.
This is the main form codes
Under Encryption part is where the error is coming from?

using System;
using System.Drawing;
using System.Collections;
using System.ComponentModel;
using System.Windows.Forms;
using System.Data;
using System.Runtime.InteropServices;
using System.Drawing.Imaging;
using System.Net;
using System.Net.Sockets;
using System.Threading;
using System.IO;
using System.Text;
using System.Security.Cryptography;

namespace Video_Conference
{
	public class Form1 : System.Windows.Forms.Form
	{
        private System.Windows.Forms.SaveFileDialog saveFileDialog1;
        internal PictureBox picture_comming;
        private TextBox IP_textBox;
        private Label label1;
        private TextBox device_number_textBox;
        private Label label2;
        private Button btn_start;
        private System.Windows.Forms.Timer timer1;
        private Conversion c = new Conversion();
		
		#region WebCam API
		const short WM_CAP = 1024; 
		const int WM_CAP_DRIVER_CONNECT = WM_CAP + 10; 
		const int WM_CAP_DRIVER_DISCONNECT = WM_CAP + 11; 
		const int WM_CAP_EDIT_COPY = WM_CAP + 30; 
		const int WM_CAP_SET_PREVIEW = WM_CAP + 50; 
		const int WM_CAP_SET_PREVIEWRATE = WM_CAP + 52; 
		const int WM_CAP_SET_SCALE = WM_CAP + 53; 
		const int WS_CHILD = 1073741824; 
		const int WS_VISIBLE = 268435456; 
		const short SWP_NOMOVE = 2; 
		const short SWP_NOSIZE = 1; 
		const short SWP_NOZORDER = 4; 
		const short HWND_BOTTOM = 1; 
		int iDevice = 0;
        private CheckBox ChkBox_Encryption;
        private Button btn_stop;
        int hHwnd; 
		[System.Runtime.InteropServices.DllImport("user32", EntryPoint="SendMessageA")] 
		static extern int SendMessage(int hwnd, int wMsg, int wParam,  [MarshalAs(UnmanagedType.AsAny)] 
			object lParam); 
		[System.Runtime.InteropServices.DllImport("user32", EntryPoint="SetWindowPos")] 
		static extern int SetWindowPos(int hwnd, int hWndInsertAfter, int x, int y, int cx, int cy, int wFlags); 
		[System.Runtime.InteropServices.DllImport("user32")] 
		static extern bool DestroyWindow(int hndw); 
		[System.Runtime.InteropServices.DllImport("avicap32.dll")] 
		static extern int capCreateCaptureWindowA(string lpszWindowName, int dwStyle, int x, int y, int nWidth, short nHeight, int hWndParent, int nID); 
		[System.Runtime.InteropServices.DllImport("avicap32.dll")] 
		static extern bool capGetDriverDescriptionA(short wDriver, string lpszName, int cbName, string lpszVer, int cbVer);
		private void OpenPreviewWindow() 
		{
			//int iHeight = 320;
			//int iWidth = 200;
			// 
			//  Open Preview window in picturebox
			// 
			hHwnd = capCreateCaptureWindowA(iDevice.ToString (), (WS_VISIBLE | WS_CHILD), 0, 0, 640, 480, picCapture.Handle.ToInt32(), 0);
			// 
			//  Connect to device
			// 
			if (SendMessage(hHwnd, WM_CAP_DRIVER_CONNECT, iDevice, 0) == 1) 
			{
				// 
				// Set the preview scale
				// 
				SendMessage(hHwnd, WM_CAP_SET_SCALE, 0, 0);
				// 
				// Set the preview rate in milliseconds
				// 
				SendMessage(hHwnd, WM_CAP_SET_PREVIEWRATE, 66, 0);
				// 
				// Start previewing the image from the camera
				// 
				SendMessage(hHwnd, WM_CAP_SET_PREVIEW, 1, 0);
				// 
				//  Resize window to fit in picturebox
				// 
				//SetWindowPos(hHwnd, HWND_BOTTOM, 0, 0, iWidth,iHeight, (SWP_NOMOVE | SWP_NOZORDER));
			}
			else 
			{
				// 
				//  Error connecting to device close window
				//  
				DestroyWindow(hHwnd);
			}
		}
		private void ClosePreviewWindow() 
		{
			// 
			//  Disconnect from device
			// 
			SendMessage(hHwnd, WM_CAP_DRIVER_DISCONNECT, iDevice, 0);
			// 
			//  close window
			// 
			DestroyWindow(hHwnd);
		}
		#endregion

        internal System.Windows.Forms.Button btnStop;
		internal System.Windows.Forms.Button btnStart;
        internal System.Windows.Forms.PictureBox picCapture;
        private IContainer components;

		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.components = new System.ComponentModel.Container();
            this.btnStop = new System.Windows.Forms.Button();
            this.btnStart = new System.Windows.Forms.Button();
            this.saveFileDialog1 = new System.Windows.Forms.SaveFileDialog();
            this.IP_textBox = new System.Windows.Forms.TextBox();
            this.label1 = new System.Windows.Forms.Label();
            this.device_number_textBox = new System.Windows.Forms.TextBox();
            this.label2 = new System.Windows.Forms.Label();
            this.btn_start = new System.Windows.Forms.Button();
            this.timer1 = new System.Windows.Forms.Timer(this.components);
            this.picture_comming = new System.Windows.Forms.PictureBox();
            this.picCapture = new System.Windows.Forms.PictureBox();
            this.ChkBox_Encryption = new System.Windows.Forms.CheckBox();
            this.btn_stop = new System.Windows.Forms.Button();
            ((System.ComponentModel.ISupportInitialize)(this.picture_comming)).BeginInit();
            ((System.ComponentModel.ISupportInitialize)(this.picCapture)).BeginInit();
            this.SuspendLayout();
            // 
            // btnStop
            // 
            this.btnStop.Anchor = System.Windows.Forms.AnchorStyles.None;
            this.btnStop.FlatStyle = System.Windows.Forms.FlatStyle.System;
            this.btnStop.Location = new System.Drawing.Point(281, 117);
            this.btnStop.Name = "btnStop";
            this.btnStop.Size = new System.Drawing.Size(112, 32);
            this.btnStop.TabIndex = 11;
            this.btnStop.Text = "Stop Capturing";
            this.btnStop.Click += new System.EventHandler(this.btnStop_Click);
            // 
            // btnStart
            // 
            this.btnStart.Anchor = System.Windows.Forms.AnchorStyles.None;
            this.btnStart.FlatStyle = System.Windows.Forms.FlatStyle.System;
            this.btnStart.Location = new System.Drawing.Point(281, 79);
            this.btnStart.Name = "btnStart";
            this.btnStart.Size = new System.Drawing.Size(112, 32);
            this.btnStart.TabIndex = 9;
            this.btnStart.Text = "Start Capturing";
            this.btnStart.Click += new System.EventHandler(this.btnStart_Click);
            // 
            // IP_textBox
            // 
            this.IP_textBox.Location = new System.Drawing.Point(371, 406);
            this.IP_textBox.Name = "IP_textBox";
            this.IP_textBox.Size = new System.Drawing.Size(161, 20);
            this.IP_textBox.TabIndex = 13;
            this.IP_textBox.Text = "127.0.0.1";
            // 
            // label1
            // 
            this.label1.AutoSize = true;
            this.label1.Location = new System.Drawing.Point(300, 409);
            this.label1.Name = "label1";
            this.label1.Size = new System.Drawing.Size(65, 13);
            this.label1.TabIndex = 14;
            this.label1.Text = "Recipient IP";
            // 
            // device_number_textBox
            // 
            this.device_number_textBox.Location = new System.Drawing.Point(336, 25);
            this.device_number_textBox.Name = "device_number_textBox";
            this.device_number_textBox.Size = new System.Drawing.Size(48, 20);
            this.device_number_textBox.TabIndex = 15;
            this.device_number_textBox.Text = "0";
            // 
            // label2
            // 
            this.label2.AutoSize = true;
            this.label2.Location = new System.Drawing.Point(238, 28);
            this.label2.Name = "label2";
            this.label2.Size = new System.Drawing.Size(91, 13);
            this.label2.TabIndex = 16;
            this.label2.Text = "Capture Device #";
            // 
            // btn_start
            // 
            this.btn_start.FlatStyle = System.Windows.Forms.FlatStyle.System;
            this.btn_start.Location = new System.Drawing.Point(541, 404);
            this.btn_start.Name = "btn_start";
            this.btn_start.Size = new System.Drawing.Size(91, 23);
            this.btn_start.TabIndex = 18;
            this.btn_start.Text = "Start";
            this.btn_start.UseVisualStyleBackColor = true;
            this.btn_start.Click += new System.EventHandler(this.button2_Click);
            // 
            // timer1
            // 
            this.timer1.Tick += new System.EventHandler(this.timer1_Tick);
            // 
            // picture_comming
            // 
            this.picture_comming.Anchor = System.Windows.Forms.AnchorStyles.None;
            this.picture_comming.BorderStyle = System.Windows.Forms.BorderStyle.Fixed3D;
            this.picture_comming.Image = global::Video_Conference.Properties.Resources.ip;
            this.picture_comming.Location = new System.Drawing.Point(358, 165);
            this.picture_comming.Name = "picture_comming";
            this.picture_comming.Size = new System.Drawing.Size(246, 189);
            this.picture_comming.SizeMode = System.Windows.Forms.PictureBoxSizeMode.StretchImage;
            this.picture_comming.TabIndex = 12;
            this.picture_comming.TabStop = false;
            this.picture_comming.Click += new System.EventHandler(this.picture_comming_Click);
            // 
            // picCapture
            // 
            this.picCapture.Anchor = System.Windows.Forms.AnchorStyles.None;
            this.picCapture.BorderStyle = System.Windows.Forms.BorderStyle.Fixed3D;
            this.picCapture.Image = global::Video_Conference.Properties.Resources.ip;
            this.picCapture.Location = new System.Drawing.Point(66, 165);
            this.picCapture.Name = "picCapture";
            this.picCapture.Size = new System.Drawing.Size(246, 189);
            this.picCapture.SizeMode = System.Windows.Forms.PictureBoxSizeMode.StretchImage;
            this.picCapture.TabIndex = 6;
            this.picCapture.TabStop = false;
            this.picCapture.Click += new System.EventHandler(this.picCapture_Click);
            // 
            // ChkBox_Encryption
            // 
            this.ChkBox_Encryption.AutoSize = true;
            this.ChkBox_Encryption.Location = new System.Drawing.Point(543, 433);
            this.ChkBox_Encryption.Name = "ChkBox_Encryption";
            this.ChkBox_Encryption.Size = new System.Drawing.Size(112, 17);
            this.ChkBox_Encryption.TabIndex = 19;
            this.ChkBox_Encryption.Text = "Enable Encryption";
            this.ChkBox_Encryption.UseVisualStyleBackColor = true;
            this.ChkBox_Encryption.CheckedChanged += new System.EventHandler(this.ChkBox_Encryption_CheckedChanged);
            // 
            // btn_stop
            // 
            this.btn_stop.Location = new System.Drawing.Point(541, 370);
            this.btn_stop.Name = "btn_stop";
            this.btn_stop.Size = new System.Drawing.Size(75, 23);
            this.btn_stop.TabIndex = 20;
            this.btn_stop.Text = "Stop";
            this.btn_stop.UseVisualStyleBackColor = true;
            // 
            // Form1
            // 
            this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
            this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
            this.ClientSize = new System.Drawing.Size(730, 460);
            this.Controls.Add(this.btn_stop);
            this.Controls.Add(this.ChkBox_Encryption);
            this.Controls.Add(this.btn_start);
            this.Controls.Add(this.label2);
            this.Controls.Add(this.device_number_textBox);
            this.Controls.Add(this.label1);
            this.Controls.Add(this.IP_textBox);
            this.Controls.Add(this.picture_comming);
            this.Controls.Add(this.btnStop);
            this.Controls.Add(this.btnStart);
            this.Controls.Add(this.picCapture);
            this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedSingle;
            this.MaximizeBox = false;
            this.Name = "Form1";
            this.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen;
            this.Text = "Video Conference";
            this.Load += new System.EventHandler(this.Form1_Load);
            this.Closing += new System.ComponentModel.CancelEventHandler(this.Form1_Closing);
            this.FormClosing += new System.Windows.Forms.FormClosingEventHandler(this.Form1_FormClosing);
            ((System.ComponentModel.ISupportInitialize)(this.picture_comming)).EndInit();
            ((System.ComponentModel.ISupportInitialize)(this.picCapture)).EndInit();
            this.ResumeLayout(false);
            this.PerformLayout();

		}
		#endregion

		/// <summary>
		/// The main entry point for the application.
		/// </summary>
		[STAThread]
		static void Main() 
		{
			Application.Run(new Form1());
		}
        TcpClient myclient;
        MemoryStream ms;
        NetworkStream myns;
        BinaryWriter mysw;
        Thread myth;
        TcpListener mytcpl;
        Socket mysocket;
        NetworkStream ns;
   //     Converter cv;
  //    VideoEncryption ve;
        public byte[] ReadFully(Stream input)
        {
            byte[] buffer = new byte[16 * 1024];
            using (MemoryStream ms = new MemoryStream())
            {
                int read;
                while ((read = input.Read(buffer, 0, buffer.Length)) > 0)
                {
                    ms.Write(buffer, 0, read);
                }
                return ms.ToArray();
            }
        }

        private byte[] GetStreamAsByteArray(System.IO.Stream stream)
        {
            int streamLength = Convert.ToInt32(stream.Length);
            byte[] fileData = new byte[streamLength + 1];


            stream.Read(fileData, 0, streamLength);
            stream.Close();


            return fileData;
        }


        public void Start_Receiving_Video_Conference()
        {
            try
            {
                // Open The Port
                mytcpl = new TcpListener(IPAddress.Any, 5000);	
                mytcpl.Start();						 // Start Listening on That Port
                mysocket = mytcpl.AcceptSocket();		 // Accept Any Request From Client and Start a Session
 [B][/B]               VideoEncryption VideoD = new VideoEncryption();
                ns = new NetworkStream(mysocket);	 // Receives The Binary Data From Port

                            if (ChkBox_Encryption.Checked)

                             {
                                Conversion cv = new Conversion();
                               byte[]dpacket = GetStreamAsByteArray(ns);
                                dpacket = VideoD.Decrypt(dpacket);
                                picture_comming.Image = cv.BytesToImage(dpacket);
                                
                          //     byte[] dpacket = cv.ImageToBytes(Image.FromStream(ns));         
                             
                                byte[] tempBuffer = new byte[1024];
                                int readCount = 0;
                                while ((readCount = ns.Read(tempBuffer, 0, tempBuffer.Length)) != 0)
                                {
                                    
                                    // do with tempBuffer
                                    tempBuffer = VideoD.Decrypt(tempBuffer);
                                    picture_comming.Image = cv.BytesToImage(tempBuffer);
                                    
                                }

                                
                         
                      //        byte[] packet = cv.ImageToBytes(Image.FromStream(ns));
                      //         packet = VideoD.Decrypt(packet);
                               
                             }
                             else
                             {
                                 picture_comming.Image = Image.FromStream(ns);
                             }
              
                mytcpl.Stop();							 // Close TCP Session

                if (mysocket.Connected == true)		     // Looping While Connected to Receive Another Message 
                {
                    while (true)
                    {
                        Start_Receiving_Video_Conference();				 // Back to First Method
                    }
                }
                myns.Flush();

            }
            catch (Exception) { myth.Abort(); }
        }
        
        private void Start_Sending_Video_Conference(string remote_IP, int port_number)
        {
            try
            {

                ms = new MemoryStream();// Store it in Binary Array as Stream


                IDataObject data;
                Image bmap;

                //  Copy image to clipboard
                SendMessage(hHwnd, WM_CAP_EDIT_COPY, 0, 0);

                //  Get image from clipboard and convert it to a bitmap
                data = Clipboard.GetDataObject();

                if (data.GetDataPresent(typeof(System.Drawing.Bitmap)))
                {
                    bmap = ((Image)(data.GetData(typeof(System.Drawing.Bitmap))));
                    bmap.Save(ms, ImageFormat.Bmp);
                }

                Image tobesend = picCapture.Image;
                picCapture.Image.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg);


                byte[] arrImage = c.ImageToBytes(tobesend);//ms.GetBuffer();
                myclient = new TcpClient(remote_IP, 5000);//Connecting with server
                myns = myclient.GetStream();
                mysw = new BinaryWriter(myns);
                VideoEncryption VideoE = new VideoEncryption();
                if (ChkBox_Encryption.Checked)
                {
                    mysw.Write(VideoE.Encrypt(arrImage));//send the stream to above address
                }
                else
                {
                    mysw.Write(arrImage);//send the stream to above address
      
                }
                arrImage=null;

                ms.Flush();
                mysw.Flush();
                myns.Flush();
                ms.Close();
                mysw.Close();
                myns.Close();
                myclient.Close();
                
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "Video Conference Error Message", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

		private void btnStart_Click(object sender, System.EventArgs e)
		{
			iDevice = int.Parse (device_number_textBox.Text);
			OpenPreviewWindow();
		}
		private void btnStop_Click(object sender, System.EventArgs e)
		{
			ClosePreviewWindow();

		}
		private void Form1_Closing(object sender, System.ComponentModel.CancelEventArgs e)
		{
			if (btnStop.Enabled) 
			{
				ClosePreviewWindow();
			}

		}

        private void timer1_Tick(object sender, EventArgs e)
        {
            Start_Sending_Video_Conference(IP_textBox.Text,6000);
        }

        private void Form1_Load(object sender, EventArgs e)
        {
 
            myth = new Thread(new System.Threading.ThreadStart(Start_Receiving_Video_Conference)); // Start Thread Session
            myth.Start(); // Start Receiveing Camera
        }

        private void Form1_FormClosing(object sender, FormClosingEventArgs e)
        {
            try
            {
                mytcpl.Stop();
                myth.Abort();
            }
            catch (Exception){}
        }

        private void button2_Click(object sender, EventArgs e)
        {
            timer1.Enabled = true;
        }

        private void picCapture_Click(object sender, EventArgs e)
        {

        }

        private void picture_comming_Click(object sender, EventArgs e)
        {

        }

        private void ChkBox_Encryption_CheckedChanged(object sender, EventArgs e)
        {

        }
	}
}

Did you not listen to anything about zipping the archive and using code tags? Go back and edit your post with code tags and re-paste the code. As you can see it loses the indents when you don't use code tags and makes it very difficult to read.

OK -- I do not see the Decrypt() or Encrypt() methods in the routine you posted. I want the methods where you call Encrypt() and Decrypt() and every variables, field, or identifier that is required to get those methods to compile.

If you encrypt with the same options you use to decrypt then it stands to reason it will work. Something is different between them.

Video Conference.zip

Sorry shnake, this is the attached file of my project

When the ChkBox is checked, this should happen, sorry but the i commented it out in the code that i sent you

This is the decrypting part

if (ChkBox_Encryption.Checked)

                             {
                                Conversion cv = new Conversion();   
                             
                                byte[] tempBuffer = new byte[1024];
                                int readCount = 0;
                                while ((readCount = ns.Read(tempBuffer, 0, tempBuffer.Length)) != 0)
                                {
                                    
                                    // do with tempBuffer
                                    tempBuffer = VideoD.Decrypt(tempBuffer);
                                    picture_comming.Image = cv.BytesToImage(tempBuffer);
                                    
                                }

Two problems.

First your Encrypt() and Decrypt() methods don't call the same. You didn't mention the padding in the Encrypt and you did in the decrypt but it still worked without it. However you should add this to your encrypt():

symmetricKey.Padding = PaddingMode.PKCS7;

Next I didn't get the error message you did.. so I used simulated data and it worked but you had bad padding of \0\0\0. I took a look and here is why:

byte[] plainTextBytes = new byte[cipherTextBytes.Length];

                // Start decrypting.
                int decryptedByteCount = cryptoStream.Read(plainTextBytes,
                                                           0,
                                                           plainTextBytes.Length);

When you create the array it may be, say, 16 bytes. When you call cryptoStream.Read() it returns that it read, say, 6 bytes. So only first 6 bytes contain data and you're returning the entire 16 byte array which gives you all the \0\0's. You could change this over to a buffered read OR change this to use stream. Here is an updated Decrypt:

public static byte[] Decrypt(byte[] cipherTextBytes)
    {
      byte[] initVectorBytes = Encoding.ASCII.GetBytes(initVector);
      byte[] saltValueBytes = Encoding.ASCII.GetBytes(saltValue);

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

      byte[] keyBytes = password.GetBytes(keySize / 8);

      RijndaelManaged symmetricKey = new RijndaelManaged();

      symmetricKey.Mode = CipherMode.CBC;
      symmetricKey.Padding = PaddingMode.PKCS7;

      ICryptoTransform decryptor = symmetricKey.CreateDecryptor(
                                                       keyBytes,
                                                       initVectorBytes);

      //MemoryStream memoryStream = new MemoryStream(cipherTextBytes);
      MemoryStream memoryStream = new MemoryStream();
      CryptoStream cryptoStream = new CryptoStream(memoryStream,
                                                    decryptor,
                                                    CryptoStreamMode.Write); //changed this
      cryptoStream.Write(cipherTextBytes, 0, cipherTextBytes.Length);
      cryptoStream.FlushFinalBlock();
      cryptoStream.Close();
      //byte[] plainTextBytes = new byte[cipherTextBytes.Length];
      
      //int decryptedByteCount = cryptoStream.Read(plainTextBytes,
      //                                           0,
      //                                           plainTextBytes.Length);
      byte[] result = memoryStream.ToArray();
      memoryStream.Close();
      memoryStream.Dispose();
      cryptoStream.Close();
      cryptoStream.Dispose();

      return result; //changed this
    }

The class name is different but here is the code I use to test it:

private void button2_Click(object sender, EventArgs e)
    {
      //const string sOrig = "abc123";
      StringBuilder sb = new StringBuilder();
      for (int i1 = 0; i1 < 100; i1++)
      {
        sb.Append(Guid.NewGuid().ToString());
      }
      string sOrig = sb.ToString();
      byte[] bArray = ASCIIEncoding.ASCII.GetBytes(sOrig);
      byte[] bEncrypted = VideoCrypto.Encrypt(bArray);
      byte[] bDecrypted = VideoCrypto.Decrypt(bEncrypted);
      string s = ASCIIEncoding.ASCII.GetString(bDecrypted);
      if (sOrig.Equals(s))
        MessageBox.Show("OK");
      else
        System.Diagnostics.Debugger.Break();
    }

Another odd thing:

private byte[] GetStreamAsByteArray(System.IO.Stream stream)
        {
            int streamLength = Convert.ToInt32(stream.Length);
            byte[] fileData = new byte[streamLength + 1];


            stream.Read(fileData, 0, streamLength);
            stream.Close();


            return fileData;
        }

Why are you setting the byte length to +1 the stream's length? If you have a stream that has 6 bytes you would access the bytes with (psudo code)stream[0] thru stream[5] BUT stream.Length would return 6. You shouldn't be calling +1 there

i see, sorry i'm not very good with my programming.
Still learning. Thanks for all your help. I'm going to try it now.

One more question
if i were to getbytes from a network stream, is it different if it is getbytes from stream?

No. The NetworkStream just handles the networking resources.

FYI -- You do not call dispose on *anything* in your application. This is very bad practice. Anything that implements IDisposable should call .Dispose() and you can ensure this with the using() clause. All Stream*s implement IDisposable since they have unmanaged file or network I/O resources.

Example:

using (MemoryStream ms = new MemoryStream())
{
  ms.DoStuff();
}

This ensures that .Dispose() is called on the memory stream AND that the variable goes out of scope outside of the using() clause so it becomes a candidate for garbage collection.

I see, thanks again for all your help. I'm overly thankful for your patience with me.

Do you know of a method that is able to call bytes from the network system?

What do you mean? You need to open some kind of connection first with either named pipes, sockets (TCP/UDP), or use remoting. For video streaming you want to use UDP since it does not ensure data integrity. TCP guarantees that all data is transmitted and not corrupt but this is not the case with UDP.

Take for instance phone calls. If the connection slows down the phone quality degrades and you can't understand the other person. Imagine if the phone connection used TCP and the connection caught up with data that happened in the past -- it would sound like alvin & the chipmunks talking. The same holds true with any real time protocol. If the data was lost, oh well, I want the most current data.

Video Conference updated.zip

This is the updated project.

I tried using the try catch and found an exception at the line under the decryption at line 554

byte[] packet = ReadAllBytes(ns);

byte[] packet = ReadAllBytes(ns); is line 540
Line 554 is just a bracket.

Does your project work correctly if you don't use encryption? Please post the exception callstack with code tags on this thread. How can I run your application so I can see this error? Do i start up two instances and what buttons do I press?

if (ChkBox_Encryption.Checked == true)

                 {
                    //yte[] packet = ImageToByte(Image.FromStream(ns));
                     try
                     {
                         byte[] packet = ReadAllBytes(ns);
                         try
                         {
                             byte[] dpacket = ve.Decrypt(packet);
                             try
                             {
                                 picture_comming.Image = cv.BytesToImage(dpacket);
                             }
                             catch (Exception ex)
                             {
                                 MessageBox.Show(ex.StackTrace, "VIDEO 3 ERROR");
                             }
                         }
                         catch (Exception ex)
                         {
                             MessageBox.Show(ex.StackTrace, "VIDEO 2 ERROR");
                         }

                     }
                     catch (Exception ex)
                     {
                         MessageBox.Show(ex.StackTrace, "VIDEO 1 ERROR");
                     }

                  }
                else
                {
                    picture_comming.Image = Image.FromStream(ns);
                }

This is how i catch the exception.

Hi sknake, I'm working on e same project wit gavin, apparently my C# skills is not there as well. I bet u hav looked into our codes, jus wondering if u r able 2 run e exe bcoz we r stuck at e encryption/decryption. The program runs smoothly without the encryption/decryption, the error will come in when e checkbox is checked. We hav 2 convert the networkstream in to byte[] so tat e Decrypt() method can decrypt. I'm not sure if conversion is done correctly coz we took e.g codes from e internet. Tell me if u can run e project

I would be more than happy to help if you would tell me how to run your application. Do I start two instances of it on two computers .. and click what buttons?

Give me the instructions on what I need to click/press to see the error

u call to ur localhost ip, e connection will b made click on Call will do

after u g0t the connection both picture box should b displaying e images, now with e encryption, check on e checkbox 2 enable it

No I don't. Please keep all of the discussion on the thread so others can read and benefit from it.

sry 4 e selfish request, no idea y my connection loads tis site slow as snail, tis is my 4th try 2 reply, always hang at e loadin, is it up n running?

can i actually do tis
byte[] packet = ImageToByte(Image.FromStream(ns));
i read the e ns into image den convert to byte[] and decrypt it, it catch e exception here says Parameter not valid..

can i actually do tis
byte[] packet = ImageToByte(Image.FromStream(ns));
i read the e ns into image den convert to byte[] and decrypt it, it catch e exception here says Parameter not valid..

I keep havin connection errors..irritating..

The following errors occurred when this message was submitted:
This forum requires that you wait 15 seconds between posts. Please try again in 7 seconds.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.