Reading and writing encrypted files (C# / netframework)
Note
This demo is available in your FlexCel installation at <FlexCel Install Folder>\samples\csharp\VS2022\netframework\10.API\25.Encrypted Files and also at https://github.com/tmssoftware/TMS-FlexCel.NET-demos/tree/master/csharp/VS2022/netframework/Modules/10.API/25.Encrypted Files
Overview
How to read and write Encrypted Excel files using FlexCel.
Concepts
Concepts on this demo are similar to the ones shown in Encryption And Subtotals example, but are repeated here so you can see them even if you are not using reports.
There are 4 ways to protect data in Excel:
A password to open. This is the only way that will actually encrypt the file. All other methods just will add a record telling Excel not to modify the file. On Excel, this option is on ->Tools->Options... Security tab.
A password to modify. Also on ->Tools->Options->Security tab, this password will allow you to open the file, but not to save it. The file will not be encrypted, and you can always use Save As to save the file.
Protecting the workbook. This will cause a pseudo-encryption of the file, but the password used to encrypt will be always the same, no matter what password you enter. On Excel, this option is at ->Tools->Protection->Protect Workbook.
Protecting the sheet. This option will protect the cells, objects, etc on a particular sheet. ->Tools->Protection->Protect Sheet.
When the file is encrypted (using a password to open) FlexCel supports four different encryption modes: Excel 95, Standard Excel97/2000 encryption, Excel 2007 xlsx encryption and Excel 2010 "agile" xlsx encryption.
To open an encrypted file, you can set the OpenPassword property or the OnPassword event. Use the OnPassword event when you want to interactively ask for a password if the file is encrypted.
Files
AssemblyInfo.cs
using System.Reflection;
using System.Runtime.CompilerServices;
//
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
//
[assembly: AssemblyTitle("")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("")]
[assembly: AssemblyCopyright("(c) 2002 - 2025 TMS Software")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
//
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Revision and Build Numbers
// by using the '*' as shown below:
[assembly: AssemblyVersion("7.24.0.0")]
//
// In order to sign your assembly you must specify a key to use. Refer to the
// Microsoft .NET Framework documentation for more information on assembly signing.
//
// Use the attributes below to control which key is used for signing.
//
// Notes:
// (*) If no key is specified, the assembly is not signed.
// (*) KeyName refers to a key that has been installed in the Crypto Service
// Provider (CSP) on your machine. KeyFile refers to a file which contains
// a key.
// (*) If the KeyFile and the KeyName values are both specified, the
// following processing occurs:
// (1) If the KeyName can be found in the CSP, that key is used.
// (2) If the KeyName does not exist and the KeyFile does exist, the key
// in the KeyFile is installed into the CSP and used.
// (*) In order to create a KeyFile, you can use the sn.exe (Strong Name) utility.
// When specifying the KeyFile, the location of the KeyFile should be
// relative to the project output directory which is
// %Project Directory%\obj\<configuration>. For example, if your KeyFile is
// located in the project directory, you would specify the AssemblyKeyFile
// attribute as [assembly: AssemblyKeyFile("..\\..\\mykey.snk")]
// (*) Delay Signing is an advanced option - see the Microsoft .NET Framework
// documentation for more information on this.
//
[assembly: AssemblyDelaySign(false)]
[assembly: AssemblyKeyFile("")]
[assembly: AssemblyKeyName("")]
Form1.cs
using System;
using System.Drawing;
using System.Collections;
using System.ComponentModel;
using System.Windows.Forms;
using System.Data;
using System.IO;
using System.Diagnostics;
using System.Reflection;
using FlexCel.Core;
using FlexCel.XlsAdapter;
namespace EncryptedFiles
{
/// <summary>
/// Shows how to deal with Encrypted files.
/// </summary>
public partial class mainForm: System.Windows.Forms.Form
{
public mainForm()
{
InitializeComponent();
}
private void btnExit_Click(object sender, System.EventArgs e)
{
Close();
}
//The event that will actually provide the password to open the empty form.
private void GetPassword(OnPasswordEventArgs e)
{
PasswordDialog Pwd = new PasswordDialog();
e.Password = string.Empty;
if (Pwd.ShowDialog() != DialogResult.OK) return;
e.Password = Pwd.Password;
}
private void btnGo_Click(object sender, System.EventArgs e)
{
// On this demo we will fill data on an existing file with the api, starting with an encrypted file holding the starting formats.
// Declare some data for the chart.
string[] Names = { "Dog", "Cat", "Cow", "Horse", "Fish" };
int[] Quantities = { 123, 200, 150, 0, 180 };
// Use two folders up to where the exe is to store the data. (Exe is stored at bin\debug)
string DataPath = Path.Combine(Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location), ".."), "..") + Path.DirectorySeparatorChar;
XlsFile xls = new XlsFile(true);
// We will use the OnPassword event here to show how to
// open a file if you don't know a priory if it is encrypted or not.
// If you already knew the file was encrypted, (as in this case)you could use:
// xls.Protection.OpenPassword = "42";
xls.Protection.OnPassword += new OnPasswordEventHandler(GetPassword);
xls.Open(Path.Combine(DataPath, "EmptyForm.xls"));
// Insert rows so the chart range grows. On this case we assume the data is at least 2 rows long. If not, we should handle
// the case and do a xls.DeleteRange.
xls.InsertAndCopyRange(new TXlsCellRange(1, 1, 1, 2), 5, 1, Names.Length - 2, TFlxInsertMode.ShiftRangeDown, TRangeCopyMode.None);
// Fill the data.
for (int i = 0; i < Names.Length; i++)
{
xls.SetCellValue(4 + i, 1, Names[i]);
xls.SetCellValue(4 + i, 2, Quantities[i]);
}
// Set a new password for opening.
xls.Protection.OpenPassword = "43";
xls.Protection.SetModifyPassword("43", false, "Ford Prefect");
if (saveFileDialog1.ShowDialog() == DialogResult.OK)
{
xls.Save(saveFileDialog1.FileName);
if (MessageBox.Show("Do you want to open the generated file? (Remember password is 43)", "Confirm", MessageBoxButtons.YesNo) == DialogResult.Yes)
{
using (Process p = new Process())
{
p.StartInfo.FileName = saveFileDialog1.FileName;
p.StartInfo.UseShellExecute = true;
p.Start();
}
}
}
}
}
}
Form1.Designer.cs
using System;
using System.Drawing;
using System.Collections;
using System.ComponentModel;
using System.Windows.Forms;
using System.Data;
using System.IO;
using System.Diagnostics;
using System.Reflection;
using FlexCel.Core;
using FlexCel.XlsAdapter;
namespace EncryptedFiles
{
public partial class mainForm: System.Windows.Forms.Form
{
private System.Windows.Forms.Panel panel2;
private System.Windows.Forms.Button btnExit;
private System.Windows.Forms.Button btnGo;
private System.Windows.Forms.SaveFileDialog saveFileDialog1;
private System.ComponentModel.IContainer components = null;
/// <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.panel2 = new System.Windows.Forms.Panel();
this.btnExit = new System.Windows.Forms.Button();
this.saveFileDialog1 = new System.Windows.Forms.SaveFileDialog();
this.btnGo = new System.Windows.Forms.Button();
this.panel2.SuspendLayout();
this.SuspendLayout();
//
// panel2
//
this.panel2.BorderStyle = System.Windows.Forms.BorderStyle.Fixed3D;
this.panel2.Controls.Add(this.btnExit);
this.panel2.Dock = System.Windows.Forms.DockStyle.Top;
this.panel2.Location = new System.Drawing.Point(0, 0);
this.panel2.Name = "panel2";
this.panel2.Size = new System.Drawing.Size(336, 35);
this.panel2.TabIndex = 4;
//
// btnExit
//
this.btnExit.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right)));
this.btnExit.BackColor = System.Drawing.SystemColors.Control;
this.btnExit.Image = global::EncryptedFiles.Properties.Resources._4close;
this.btnExit.ImageAlign = System.Drawing.ContentAlignment.MiddleLeft;
this.btnExit.Location = new System.Drawing.Point(272, 2);
this.btnExit.Name = "btnExit";
this.btnExit.Size = new System.Drawing.Size(56, 26);
this.btnExit.TabIndex = 2;
this.btnExit.Text = "Exit";
this.btnExit.TextAlign = System.Drawing.ContentAlignment.MiddleRight;
this.btnExit.UseVisualStyleBackColor = false;
this.btnExit.Click += new System.EventHandler(this.btnExit_Click);
//
// saveFileDialog1
//
this.saveFileDialog1.Filter = "Excel Files|*.xls;*.xlsx;*.xlsm|Excel 97/2003|*.xls|Excel 2007|*.xlsx;*.xlsm|All " +
"files|*.*";
this.saveFileDialog1.RestoreDirectory = true;
//
// btnGo
//
this.btnGo.BackColor = System.Drawing.SystemColors.Control;
this.btnGo.Image = global::EncryptedFiles.Properties.Resources._4gears;
this.btnGo.ImageAlign = System.Drawing.ContentAlignment.MiddleLeft;
this.btnGo.Location = new System.Drawing.Point(96, 72);
this.btnGo.Name = "btnGo";
this.btnGo.Size = new System.Drawing.Size(152, 30);
this.btnGo.TabIndex = 5;
this.btnGo.Text = "Create Encrypted File";
this.btnGo.TextAlign = System.Drawing.ContentAlignment.MiddleRight;
this.btnGo.UseVisualStyleBackColor = false;
this.btnGo.Click += new System.EventHandler(this.btnGo_Click);
//
// mainForm
//
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(336, 122);
this.Controls.Add(this.btnGo);
this.Controls.Add(this.panel2);
this.Name = "mainForm";
this.Text = "Encrypted Excel Files";
this.panel2.ResumeLayout(false);
this.ResumeLayout(false);
}
#endregion
}
}
PasswordDialog.cs
using System;
using System.Drawing;
using System.Collections;
using System.ComponentModel;
using System.Windows.Forms;
namespace EncryptedFiles
{
/// <summary>
/// Summary description for PasswordDialog.
/// </summary>
public partial class PasswordDialog: System.Windows.Forms.Form
{
public PasswordDialog()
{
//
// Required for Windows Form Designer support
//
InitializeComponent();
//
// TODO: Add any constructor code after InitializeComponent call
//
}
public string Password
{
get
{
return PasswordEdit.Text;
}
}
}
}
PasswordDialog.Designer.cs
using System;
using System.Drawing;
using System.Collections;
using System.ComponentModel;
using System.Windows.Forms;
namespace EncryptedFiles
{
public partial class PasswordDialog: System.Windows.Forms.Form
{
private System.Windows.Forms.Label label1;
private System.Windows.Forms.Label label2;
private System.Windows.Forms.TextBox PasswordEdit;
private System.Windows.Forms.Label label3;
private System.Windows.Forms.Button btnOk;
public System.Windows.Forms.Button btnCancel;
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.Container components = null;
/// <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.label1 = new System.Windows.Forms.Label();
this.label2 = new System.Windows.Forms.Label();
this.PasswordEdit = new System.Windows.Forms.TextBox();
this.label3 = new System.Windows.Forms.Label();
this.btnOk = new System.Windows.Forms.Button();
this.btnCancel = new System.Windows.Forms.Button();
this.SuspendLayout();
//
// label1
//
this.label1.Location = new System.Drawing.Point(16, 8);
this.label1.Name = "label1";
this.label1.Size = new System.Drawing.Size(280, 23);
this.label1.TabIndex = 0;
this.label1.Text = "Please enter the password to open the template.";
//
// label2
//
this.label2.Font = new System.Drawing.Font("Microsoft Sans Serif", 8.25F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((System.Byte)(0)));
this.label2.Location = new System.Drawing.Point(16, 32);
this.label2.Name = "label2";
this.label2.Size = new System.Drawing.Size(176, 23);
this.label2.TabIndex = 1;
this.label2.Text = "HINT: The password is 42";
//
// PasswordEdit
//
this.PasswordEdit.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right)));
this.PasswordEdit.Location = new System.Drawing.Point(128, 64);
this.PasswordEdit.Name = "PasswordEdit";
this.PasswordEdit.PasswordChar = '*';
this.PasswordEdit.Size = new System.Drawing.Size(360, 20);
this.PasswordEdit.TabIndex = 0;
this.PasswordEdit.Text = "";
//
// label3
//
this.label3.Location = new System.Drawing.Point(56, 64);
this.label3.Name = "label3";
this.label3.Size = new System.Drawing.Size(64, 23);
this.label3.TabIndex = 3;
this.label3.Text = "Password:";
//
// btnOk
//
this.btnOk.DialogResult = System.Windows.Forms.DialogResult.OK;
this.btnOk.Location = new System.Drawing.Point(128, 112);
this.btnOk.Name = "btnOk";
this.btnOk.TabIndex = 1;
this.btnOk.Text = "Ok";
//
// btnCancel
//
this.btnCancel.DialogResult = System.Windows.Forms.DialogResult.Cancel;
this.btnCancel.Location = new System.Drawing.Point(216, 112);
this.btnCancel.Name = "btnCancel";
this.btnCancel.TabIndex = 2;
this.btnCancel.Text = "Cancel";
//
// PasswordDialog
//
this.AcceptButton = this.btnOk;
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(520, 154);
this.Controls.Add(this.btnCancel);
this.Controls.Add(this.btnOk);
this.Controls.Add(this.label3);
this.Controls.Add(this.PasswordEdit);
this.Controls.Add(this.label2);
this.Controls.Add(this.label1);
this.Name = "PasswordDialog";
this.ShowInTaskbar = false;
this.Text = "Information";
this.ResumeLayout(false);
}
#endregion
}
}
Program.cs
using System;
using System.Windows.Forms;
namespace EncryptedFiles
{
static class Program
{
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new mainForm());
}
}
}