//文件加密解密
//窗体
Func<string[]> OpenFiles = () =>
{
string[] FileNames = null;
OpenFileDialog OFD = new OpenFileDialog();
OFD.Multiselect = true;//允许多选
OFD.Filter = "JPG图像|*.jpg|Png图像|*.png|BMP图像|*.bmp|All files|*.*";
if (OFD.ShowDialog() == DialogResult.OK && OFD.FileNames != null)
{
FileNames = OFD.FileNames;
}
else { FileNames = null; }
return FileNames;
};
private void button1_Click(object sender, EventArgs e)
{
string[] files=OpenFiles();
if (files == null) { return; }
foreach (string s in files.ToArray()) //遍历选择文件并加密
{
string File =s;
EncryptFiles.EncryptFile(File, textBox1.Text);
}
}
private void button2_Click(object sender, EventArgs e)
{
string[] files = OpenFiles();
if (files == null) { return; }
foreach (string s in files.ToArray()) //遍历选择文件并解密
{
string File =s;
EncryptFiles.DecryptFile(File, textBox1.Text);
}
}
//实现功能类
static class EncryptFiles
{
public static void EncryptFile(string inputFile,string password) //加密
{
try
{
string outputFile = inputFile + "N";
UnicodeEncoding UE = new UnicodeEncoding();
byte[] key = UE.GetBytes(password);
string cryptFile = outputFile;
FileStream fsCrypt = new FileStream(cryptFile, FileMode.Create);
RijndaelManaged RMCrypto = new RijndaelManaged();
CryptoStream cs = new CryptoStream(fsCrypt,
RMCrypto.CreateEncryptor(key, key),
CryptoStreamMode.Write);
FileStream fsIn = new FileStream(inputFile, FileMode.Open);
int data;
while ((data = fsIn.ReadByte()) != -1)
cs.WriteByte((byte)data);
fsIn.Close();
cs.Close();
fsCrypt.Close();
File.Delete(inputFile);
File.Move(outputFile, inputFile);
File.Delete(outputFile);
MessageBox.Show("Encrypt Source file succeed!", "Msg :");
}
catch(Exception ex)
{
MessageBox.Show("Source file error!", "Error :");
}
}
public static void DecryptFile(string inputFile, string password) //解密
{
try
{
string outputFile = inputFile + "N";
UnicodeEncoding UE = new UnicodeEncoding();
byte[] key = UE.GetBytes(password);
FileStream fsCrypt = new FileStream(inputFile, FileMode.Open);
RijndaelManaged RMCrypto = new RijndaelManaged();
CryptoStream cs = new CryptoStream(fsCrypt,
RMCrypto.CreateDecryptor(key, key),
CryptoStreamMode.Read);
FileStream fsOut = new FileStream(outputFile, FileMode.Create);
int data;
while ((data = cs.ReadByte()) != -1)
fsOut.WriteByte((byte)data);
fsOut.Close();
cs.Close();
fsCrypt.Close();
File.Delete(inputFile);
File.Move(outputFile, inputFile);
File.Delete(outputFile);
MessageBox.Show("Decrypt Source file succeed!", "Msg :");
}
catch (Exception ex)
{
MessageBox.Show("Source file error", "Error :");
}
}
}