none
How to encrypt excel files (or non-txt format) RRS feed

  • Pregunta

  • Hello, I want to know which class(es) do I have to use to encrypt an excel file or a non-txt extension format file?

    Every link I've looked for encrypting and decrypting information have examples but only for text format file. When I apply code and use it for a text file it works perfectly but if I use it for excel (xls, xlsx) files or any other format, it doesn´t works and generates the following exception:

    System.Security.Cryptography.CryptographicException
    Length of the data to decrypt is invalid.

    I haven't managed file encryption before, and I don't know if there migth be errors in the code I'm using, so I also add my code next:

    using System;
    using System.Collections.Generic;
    using System.ComponentModel;
    using System.Data;
    using System.Drawing;
    using System.IO;
    using System.Runtime.InteropServices;
    using System.Security;
    using System.Security.AccessControl;
    using System.Security.Cryptography;
    using System.Security.Permissions;
    using System.Text;
    using System.Windows.Forms;

    public partial class Form2 : Form
        {
            static string pathSource =   "F:\\Varios\\Proyectos IDS en Desarrollo\\KPI Balance Scorecard\\FileEncryption\\files\\source.xlsx";
            static string pathDestiny = "F:\\Varios\\Proyectos IDS en Desarrollo\\KPI Balance Scorecard\\FileEncryption\\files\\destiny.xlsx";
            static string pathDestiny2 = "F:\\Varios\\Proyectos IDS en Desarrollo\\KPI Balance Scorecard\\FileEncryption\\files\\destiny2.xlsx";
            static string key = "";
        
             public Form2()
            {
                InitializeComponent();
            }

            private static void EncryptFile(string sInputFilename, string sOutputFilename)
            {
                FileStream fsInput = new FileStream(sInputFilename, FileMode.OpenOrCreate, FileAccess.Read);
                FileStream fsEncrypted = new FileStream(sOutputFilename, FileMode.Create, FileAccess.Write);

                // Internet code:
                DESCryptoServiceProvider DES = new DESCryptoServiceProvider();
                DES.IV = ASCIIEncoding.ASCII.GetBytes(key);
                DES.Key = ASCIIEncoding.ASCII.GetBytes(key);

                // Comment:
                //          I think that may be possible to use another class instead of ASCIIEncoding.
                //          For example, exist the classes called UTF32Encoding, UTF16Encoding, or UTF8Encoding.
                //          I think that any of these classes might be useful for the process, but I didn't found
                //          examples of how to use it.

                //          Also, I found that instead of ASCII class used above, you can use the UTF32Encoding,
                //          UTF16Encoding, UTF8Encoding or thye Unicode class, but I don't know how to apply it.

                ICryptoTransform desencrypt = DES.CreateEncryptor();
                CryptoStream cryptoStream = new CryptoStream(fsEncrypted, desencrypt, CryptoStreamMode.Write);
                byte[] byteArrayInput = new byte[fsInput.Length - 1];

                fsInput.Read(byteArrayInput, 0, byteArrayInput.Length);
                cryptoStream.Write(byteArrayInput, 0, byteArrayInput.Length);

                cryptoStream.Close();
                fsInput.Close();
                fsEncrypted.Close();
            }

            /// <summary>
            /// Decrypts a file to its normal format.
            /// </summary>
            /// <param name="sInputFilename">Encrypted file to be read and decrypted.</param>
            /// <param name="sOutputFilename">Destination file for storing the data on its normal format again.</param>
            /// <param name="sKey"></param>
            private static void DecryptFile(string sInputFilename, string sOutputFilename, string sKey)
            {
                // Internet code:
                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);

                // Create a DES decryptor from the DES instance:
                ICryptoTransform desdecrypt = DES.CreateDecryptor();

                // Create crypto stream set to read and do a DES decryption transform on incoming bytes:
                CryptoStream cryptostreamDecr = new CryptoStream(fsread, desdecrypt, CryptoStreamMode.Read);

                // Print the contents of the decrypted file:
                StreamWriter fsDecrypted = new StreamWriter(sOutputFilename);

                // Comment: I looked that you can use for non text files, the BinaryReader and/or
                // BinaryWriter instead of the StreamReader and/or StreamWriter, but I tried to apply it and I
                // didn't obtain results, again, I didn't know if I used it in a wrong way.
                try
                {
                    StreamReader str = new StreamReader(cryptostreamDecr);
                    string line = String.Empty;
                    while (!str.EndOfStream)
                    {
                        line = str.ReadLine();
                        fsDecrypted.Write(line);
                        //fsDecrypted.Write(str.ReadToEnd());
                        line = String.Empty;
                    }
                }
                catch (Exception ex)
                {
                    // Comment:
                    // An CryptographicException happens. The Message is: Length of the data to decrypt is invalid.
                    MessageBox.Show("An error has happened: " + ex.Message);
                }
                finally
                {
                    cryptostreamDecr.FlushFinalBlock();
                    cryptostreamDecr.Close();
                    fsDecrypted.Flush();
                    fsDecrypted.Close();
                }
            }
           
            /// <summary>
            /// Encryption button was pressed.
            /// </summary>
            /// <param name="sender"></param>
            /// <param name="e"></param>
            protected void btnENCRYPT_Click(object sender, EventArgs e)
            {
                gch = GCHandle.Alloc(key, GCHandleType.Pinned);
                startEncryption();
            }

            /// <summary>
            /// Decryption button was pressed.
            /// </summary>
            /// <param name="sender"></param>
            /// <param name="e"></param>
            protected void btnDECRYPT_Click(object sender, EventArgs e)
            {
                startDecryption();
            }
    }

    Danielmr44
    martes, 5 de mayo de 2009 13:36