none
Encrypting and Decrypting Office 2007 documents RRS feed

  • Question

  • Hi ,

     I am trying to encrypt and decrypt 2007 office documents. I am  using System.Security.Cryptographic  namespace

    I am using the following code

    class Class1
        {
            //  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(IntPtr 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 Main()
            {
                // Must be 64 bits, 8 bytes.
                // Distribute this key to the user who will decrypt this file.
                string sSecretKey;
    
                // Get the Key for the file to Encrypt.
                sSecretKey = GenerateKey();
    
                // For additional security Pin the key.
                GCHandle gch = GCHandle.Alloc(sSecretKey, GCHandleType.Pinned);
    
                // Encrypt the file.        
                EncryptionHelper.EncryptFile(@"Book1.xls",
                   @"Encrypted.txt",
                   sSecretKey);
    
                // Decrypt the file.
                EncryptionHelper.DecryptFile(@"Encrypted.txt",
                   @"OUTPUT\Book1.xls",
                   sSecretKey);
    
                // Remove the Key from memory. 
                ZeroMemory(gch.AddrOfPinnedObject(), sSecretKey.Length * 2);
                gch.Free();
            }
       }
    public class EncryptionHelper
        {
           public static void EncryptFile(string sInputFilename, string sOutputFilename, string sKey)
            {
            
                GCHandle gch = GCHandle.Alloc(sKey, GCHandleType.Pinned);
                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.CreateEncryptor();
                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.Flush();
                cryptostream.Close();
                fsInput.Flush();
                fsInput.Close();
                fsEncrypted.Close();
            
            }
    
           public 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);
               FileStream fsEncrypted = new FileStream(sOutputFilename,
                FileMode.Create,
                FileAccess.Write);
               //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);
               byte[] fileData = new byte[fsread.Length];
               cryptostreamDecr.Read(fileData, 0, (int)fsread.Length);
               fsEncrypted.Write(fileData, 0, fileData.Length);
               fsread.Flush();
               fsread.Close();
               fsEncrypted.Flush();
               fsEncrypted.Close();
               cryptostreamDecr.Flush();
               cryptostreamDecr.Close();
           }
        }



    The above code is works fine for doc,xls,ppt,txt files but it currupts .xlsx,pptx and docx files . When i try to open the file it prompts a repair window saying the file is currupted . after repair the doc file appears fine . Any idea ?



    Wednesday, October 12, 2011 5:04 AM

Answers

  • Hi Keen

    I suspect the issue has to do with the fact that the Open XML file format documents are all ZIP Packages (System.IO.Packaging) rather than single files, like the other file formats you mention. I think you'd need to use packaging encryption (I believe there is such a thing?), instead.


    Cindy Meister, VSTO/Word MVP
    Wednesday, October 12, 2011 11:55 AM
    Moderator
  • Hi Keen,

    Office 2007 and 2010  has its own way to encrypt an Office document.

    For Office 2007, click Office button -> Prepare -> Encrypt document

    For Office 2010, click File -> Info -> Protect Workbook -> Encrypt with Password

    Good day,


    Best Regards, Calvin Gao [MSFT]
    MSDN Community Support | Feedback to us
    Get or Request Code Sample from Microsoft
    Please remember to mark the replies as answers if they help and unmark them if they provide no help.

    Friday, October 21, 2011 12:03 PM
    Moderator

All replies

  • Hi Keen

    I suspect the issue has to do with the fact that the Open XML file format documents are all ZIP Packages (System.IO.Packaging) rather than single files, like the other file formats you mention. I think you'd need to use packaging encryption (I believe there is such a thing?), instead.


    Cindy Meister, VSTO/Word MVP
    Wednesday, October 12, 2011 11:55 AM
    Moderator
  • Hi Keen,

    Office 2007 and 2010  has its own way to encrypt an Office document.

    For Office 2007, click Office button -> Prepare -> Encrypt document

    For Office 2010, click File -> Info -> Protect Workbook -> Encrypt with Password

    Good day,


    Best Regards, Calvin Gao [MSFT]
    MSDN Community Support | Feedback to us
    Get or Request Code Sample from Microsoft
    Please remember to mark the replies as answers if they help and unmark them if they provide no help.

    Friday, October 21, 2011 12:03 PM
    Moderator