I found this script on http://www.codeproject.com/Articles/26085/File-Encryption-and-Decryption-in-C. It works fine when I use the static key // string password = @"myKey1234"; // Your Key Here
. when I pass in a different key, it doesn't work string password = @keyPwd;
. You can see in my code I'm passing key to function it is not working.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Security.Cryptography;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace CSVEncrypts
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
string inputFile = "";
string outputFilePath = "";
string oFilePathName = "";
// EncryptFile
private void EncryptFile(string inputFile, string outputFile,string keyPwd )
{
try
{
// string password = @"myKey123"; // Your Key Here
string password = @keyPwd;
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();
}
catch
{
MessageBox.Show("Encryption failed!", "Error");
}
}
// Decrypt
private void DecryptFile(string inputFile, string outputFile, string keyPwd)
{
{
//string password = @"myKey123"; // Your Key Here
string password = @keyPwd; // Your Key Here
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();
}
}
private void button1_Click(object sender, EventArgs e)
{
if (inputFile != "")
{
oFilePathName = outputFilePath + "\\" + textBox1.Text;
EncryptFile(inputFile, oFilePathName,keytextBox.Text);
}
}
private void button2_Click(object sender, EventArgs e)
{
if (inputFile != "") ;
{
oFilePathName = outputFilePath + "\\" + textBox1.Text;
DecryptFile(inputFile, oFilePathName, keytextBox.Text);
}
}
private void button3_Click(object sender, EventArgs e)
{
OpenFileDialog InputOpenFileDialog1 = new OpenFileDialog();
if (InputOpenFileDialog1.ShowDialog() == System.Windows.Forms.DialogResult.OK)
{
string strInfilename = InputOpenFileDialog1.FileName;
button3.Text = strInfilename;
inputFile = strInfilename;
outputFilePath = Path.GetDirectoryName(inputFile);
}
}
}
}