在 C# 中将 Zip 文件保存到 Access 数据库并进行文件加密






4.39/5 (8投票s)
在Access数据库中保存zip文件,在文件保存到Access数据库时加密字节,在从数据库提取文件时解密字节。。。
引言
您可以将各种类型的文件保存在Access数据库中。您应该将文件转换为字节,然后将字节保存在Microsoft Access数据库表中的OLE Object类型字段中。在本文中,我们将zip文件保存在Access数据库中。但在使用一个方法将文件保存到数据库之前,我会对文件进行加密以提高安全性,并在将文件保存到硬盘时,使用另一个方法解密文件以便使用。
如果在发布时文件未解码,则用户无法获取文件的原始内容。此方法是保护文档的推荐方式。如果黑客访问了数据库,他们将无法直接使用数据。
要求
在使用该类之前,您需要以下工具,这些工具是开发所必需的
- Visual Studio .NET 2008 或更高版本
- .NET framework 3.0 或更高版本
Using the Code
首先,您应该创建一个Microsoft Access数据库2000或2003。您的数据库应包含一个具有以下字段的表(参见图1)
ZipFIleID 自动编号
ZipFileName 文本
ZipFileContent OLE 对象
然后,我们需要创建一个Visual Studio 2008 Windows应用程序项目。下一步,我们应该向项目中添加数据集和数据源。数据集是我们在其中创建的Microsoft Access文件(参见图2)。
此数据集有一个获取记录的方法。此方法的输入参数是记录ID。您可以看到查询如下
SELECT ZipFIleID, ZipFileName, ZipFileContent
FROM tblZipFles
WHERE (ZipFIleID = ?)
ORDER BY ZipFIleID DESC>
接下来,我们创建一个窗体,然后将以下对象放入窗体中(参见图3)
- 两个
Button
(用于将文件插入数据库和从数据库检索文件) - 一个
ComboBox
(显示驱动器列表供用户选择) TextBox
(供用户输入文件ID)ListBox
(显示数据库中的文件列表)
当用户单击“插入”键时,将显示文件选择窗口。代码如下所示
private void Btn_AddFileToDB_Click(object sender, EventArgs e)
{
OpenFileDialog openFileDialog1 = new OpenFileDialog();
openFileDialog1.Filter = "ZIP Files (.zip)|*.zip";
openFileDialog1.FilterIndex = 1;
openFileDialog1.ShowDialog();
if (openFileDialog1.FileName.Trim() != "")
{
Byte[] Byt_ZipFile = null;
Byt_ZipFile = UDF_ZipToByte(openFileDialog1.FileName.Trim());
Class_ByteEncryption BytEnc = new Class_ByteEncryption(Byt_ZipFile);// Encrypt Bytes . . .
BytEnc.UDF_EncryptBytes();
Byt_ZipFile = BytEnc.Byt_CryptedBytes;
UDF_SaveFileToDB(openFileDialog1.SafeFileName.Trim()/*Get Just FileName with Extention*/, Byt_ZipFile);
}
}
通过以下方法,选定的文件将被转换为字节(在前一个方法中调用此方法)
public static byte[] UDF_ZipToByte(String filePath)
{
byte[] buffer;
FileStream fileStream = new FileStream(filePath, FileMode.Open, FileAccess.Read);
try
{
int length = (int)fileStream.Length; // get file length
buffer = new byte[length]; // create buffer
int count; // actual number of bytes read
int sum = 0; // total number of bytes read
// read until Read method returns 0 (end of the stream has been reached)
while ((count = fileStream.Read(buffer, sum, length - sum)) > 0)
sum += count; // sum is a buffer offset for next reading
}
finally
{
fileStream.Close();
}
return buffer;
}
在将文件存储到数据库之前,我们应该对字节进行编码。为此,我们在Class_ByteEncryption
类中使用UDF_EncryptBytes
方法。
using System;
using System.Data;
using System.Configuration;
using System.Linq;
using System.Security.Cryptography;
using System.Xml.Linq;
public class Class_ByteEncryption
{
Byte[] Byt_InputBytes = null;
public Class_ByteEncryption(Byte[] Byt_InpBytes)
{
Byt_InputBytes = Byt_InpBytes;
}
// ???????
public void UDF_EncryptBytes()
{
byte[] IV = new byte[8] { 10, 11, 85, 7, 14, 76, 10, 22 };
string cryptokey = "lar ltc";
byte[] mystring = Byt_InputBytes;
byte[] my_buffer = mystring;
TripleDESCryptoServiceProvider des = new TripleDESCryptoServiceProvider();
MD5CryptoServiceProvider md5 = new MD5CryptoServiceProvider();
des.Key = md5.ComputeHash(System.Text.ASCIIEncoding.ASCII.GetBytes(cryptokey));
des.IV = IV;
byte[] codebuffer = des.CreateEncryptor().TransformFinalBlock(my_buffer, 0, my_buffer.Length);
Byt_InputBytes = codebuffer;
}
public Byte[] Byt_CryptedBytes
{
get
{
return Byt_InputBytes;
}
}
}
转换为字节后,可以通过以下方法和数据集将其存储在数据库中
private void UDF_SaveFileToDB(String Str_FileName , Byte[] Byt_ZipFile1)
{
DataSetTableAdapters.tblZipFlesTableAdapter db = new EncodeDecodeZipInDb.DataSetTableAdapters.tblZipFlesTableAdapter();
db.Insert(Str_FileName.Trim(), Byt_ZipFile1);
UDF_GetFilesList();
MessageBox.Show("File Saved In DB . . .");
}
使用以下方法,您可以将驱动器列表设置为ListBox
private void UDF_GetHardDriveList()
{
String[] DriveList = System.IO.Directory.GetLogicalDrives();
foreach (string str in DriveList)
{
comboBox1.Items.Add(str);
try
{
comboBox1.SelectedIndex = 0;
}
catch { }
}
}
通过以下方法,显示插入数据库的数据记录
private void UDF_GetFilesList()
{
DataSetTableAdapters.tblZipFlesTableAdapter db = new EncodeDecodeZipInDb.DataSetTableAdapters.tblZipFlesTableAdapter();
DataSet.tblZipFlesDataTable dt = new DataSet.tblZipFlesDataTable();
db.Fill(dt);
listBox1.Items.Clear();
foreach (DataRow Row in dt.Rows)
{
listBox1.Items.Add("Code = " + Row[0].ToString() + " - Name = " + Row[1]);
}
}
要发布文件并将其保存到选定的驱动器,您应该单击“导出Zip”按钮。另外,在单击之前,您必须在一个文本字段中输入文件ID(从列表框中选择)并选择一个驱动器(参见图4)。
单击后,将运行以下方法
private void Btn_SaveToFile_Click(object sender, EventArgs e)
{
if (textBox1.Text.Trim() == "")
{
MessageBox.Show("Please Enter Zip File Code From List");
}
else
{
try
{
DataSetTableAdapters.tblZipFlesTableAdapter db = new EncodeDecodeZipInDb.DataSetTableAdapters.tblZipFlesTableAdapter();
DataSet.tblZipFlesDataTable dt = new DataSet.tblZipFlesDataTable();
db.FillBy(dt, int.Parse(textBox1.Text.Trim()));
Class_ByteDecryption DecBytes = new Class_ByteDecryption((Byte[])dt[0][2]);
DecBytes.UDF_DencryptBytes();
UDF_SaveBinaryDateToFile(dt[0][1].ToString(), DecBytes.Byt_DcryptedBytes);//Saving file to db
MessageBox.Show("File Saved . . . ");
}
catch { MessageBox.Show("Please Enter Valid Code From List. . ."); }
}
}
调用以下方法将文件保存到磁盘
/// <summary>
/// Save Record To Database
/// </summary>
/// <param name="Str_FileName"></param>
/// <param name="Byt_ZipFile1"></param>
private void UDF_SaveFileToDB(String Str_FileName , Byte[] Byt_ZipFile1)
{
DataSetTableAdapters.tblZipFlesTableAdapter db = new EncodeDecodeZipInDb.DataSetTableAdapters.tblZipFlesTableAdapter();
db.Insert(Str_FileName.Trim(), Byt_ZipFile1);
UDF_GetFilesList();
MessageBox.Show("File Saved In DB . . .");
}
在文件保存到驱动器之前,字节应解码为用户可以使用在保存的文件中。代码解码通过Class_ByteDecryption
类中的UDF_DencryptBytes
方法执行。
public class Class_ByteDecryption
{
Byte[] Byt_InputBytes = null;
public Class_ByteDecryption(Byte[] Byt_InpBytes)
{
Byt_InputBytes = Byt_InpBytes;
}
public void UDF_DencryptBytes()
{
byte[] IV = new byte[8] { 10, 11, 85, 7, 14, 76, 10, 22 };
string cryptokey = "lar ltc";
byte[] codedstring;
codedstring = Byt_InputBytes;
byte[] my_buffer = codedstring;
TripleDESCryptoServiceProvider des = new TripleDESCryptoServiceProvider();
MD5CryptoServiceProvider md5 = new MD5CryptoServiceProvider();
des.Key = md5.ComputeHash(System.Text.ASCIIEncoding.ASCII.GetBytes(cryptokey));
des.IV = IV;
byte[] codedbuffer = des.CreateDecryptor().TransformFinalBlock(my_buffer, 0, my_buffer.Length);
Byt_InputBytes = codedbuffer;
}
public Byte[] Byt_DcryptedBytes
{
get
{
return Byt_InputBytes;
}
}
}
如果您在编译时看到错误,在64位Windows上,请进行以下更改(参见图5)
App.config设置
应用程序配置文件包含特定于应用程序的设置。此文件包含通用语言运行时读取的配置设置(例如程序集绑定策略、远程对象等)以及应用程序可以读取的设置。
您的项目连接字符串应放在app.config文件中。此文件采用XML格式。通过此文件,您可以更改连接字符串。您可以使用Visual Studio自动创建此文件。您可以将其内部存储您可能想要更改而无需更改代码的连接字符串。
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<configSections>
</configSections>
<connectionStrings>
<add name="EncodeDecodeZipInDb.Properties.Settings.ZipFileDBConnectionString"
connectionString="Provider=Microsoft.Jet.OLEDB.4.0;
Data Source=|DataDirectory|\ZipFileDB.mdb" providerName="System.Data.OleDb" />
</connectionStrings>
</configuration>
同时,您可以定义一个静态路由以连接到数据库
<add name="EncodeDecodeZipInDb.Properties.Settings.ZipFileDBConnectionString"
connectionString="Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\ZipFileDB.mdb"
providerName="System.Data.OleDb" />
结论
现在您可以安全地将您的文档保存在Access数据库中了。最后,我注意到这只是一个建议。另外,为了更高的安全性,您可以更改编码算法。改变的关键是其中一种方式。