Click here to Skip to main content
15,174,232 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
I am trying to make a DES and triple DES file encrypter i cant find any articles or videos on DES file encryption which is why i asked my question. I have tried the following code but i get invalided key error and it doesn't matter if i change the IV from 16 to 8 i still get this error.

The code i tried:

private void TDES_EncryptFile()
           Stream myStream;
           SaveFileDialog saveFileDialog1 = new SaveFileDialog();
           saveFileDialog1.Filter = "Encrypted File (*.enc)|*.enc";
           saveFileDialog1.RestoreDirectory = true;

           if (saveFileDialog1.ShowDialog() == true)
               if ((myStream = saveFileDialog1.OpenFile()) != null)

               string keyText = keys2.Text;
               byte[] keyBytes = ASCIIEncoding.ASCII.GetBytes(keyText);
               byte[] ivBytes = ASCIIEncoding.ASCII.GetBytes(keyText);
               string inputFile = Openfile.Text;
               string encryptedFile = saveFileDialog1.FileName;
               using (FileStream inputFileStream = File.Open(inputFile, FileMode.Open))
               using (FileStream outputFileStream = File.Open(encryptedFile, FileMode.Create))
                   using (TripleDESCryptoServiceProvider tds = new TripleDESCryptoServiceProvider())
                       tds.Key = keyBytes;
                       tds.IV = ivBytes;

                       ICryptoTransform cryptoTransform = tds.CreateEncryptor();

                       using (CryptoStream cryptoStream = new CryptoStream(outputFileStream, cryptoTransform, CryptoStreamMode.Write))
                           byte[] buffer = new byte[inputFileStream.Length];
                           inputFileStream.Read(buffer, 0, buffer.Length);
                           cryptoStream.Write(buffer, 0, buffer.Length);
                           MessageBox.Show("The File Was Successfully Encrypted", "Encrypted!", MessageBoxButton.OK, MessageBoxImage.Information);
F-ES Sitecore 28-Jun-15 8:12am
And the error is....?
Yusuf_20_x 28-Jun-15 8:24am
specified key is not a valid size for this algorithm

1 solution

It turns out i needed to md5-hash my key and then specify 8 character long IV

byte[] keyBytes = md5.ComputeHash(utf.GetBytes(keyText));
byte[] ivBytes = ASCIIEncoding.ASCII.GetBytes(keyText.Substring(0, 8));

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900