I was trying to encrypt my hello.txt file but it failed. When I encrypt, this is the exception:
System.UnauthorizedAccessException: Access to the path 'C:\Users\username\Desktop' is denied.
at System.IO.__Error.WinIOError(Int32 errorCode, String maybeFullPath)
at System.IO.FileStream.Init(String path, FileMode mode, FileAccess access, Int32 rights, Boolean useRights, FileShare share, Int32 bufferSize, FileOptions options, SECURITY_ATTRIBUTES secAttrs, String msgPath, Boolean bFromProxy, Boolean useLongPath, Boolean checkHost)
at System.IO.FileStream..ctor(String path, FileMode mode, FileAccess access)
at Encrypt.EncDec.Decrypt(String fileIn, String fileOut, String Password) in C:\Users\username\Documents\My Apps\Encrypt\Encrypt\Form1.cs:line 518
at Encrypt.Form1.proceedEDfe(String input, String output, String key) in C:\Users\username\Documents\My Apps\Encrypt\Encrypt\Form1.cs:line 154
So here is my code (line 154
):
string inputE;
string outputE;
string pwdE;
private void ofd1_Click(object sender, EventArgs e)
{
if (ofd.ShowDialog() == DialogResult.OK)
{
inputE = ofd.FileName;
}
}
private void fbd1_Click(object sender, EventArgs e)
{
if(fbd.ShowDialog() == DialogResult.OK)
{
outputE = fbd.SelectedPath;
}
}
private void encryptF_Click(object sender, EventArgs e)
{
pwdE = keyE.Text;
if (inputE != null && outputE != null && pwdE != null)
{
proceedEDfe(inputE, outputE, pwdE);
}
}
private void proceedEDfe(string input, string output, string key)
{
try
{
EncDec.Decrypt(input, output, key); //line 154
doneStat.Text = "File decryption succeeded";
}
catch (Exception ex)
{
doneStat.Text = "File decryption failed";
MessageBox.Show(Convert.ToString(ex), "Error");
doneStatTb.Text = Convert.ToString(ex);
}
}
I copied this code from Code Project, the EncDec class Decrypt method is this (line 518
):
// Decrypt a file into another file using a password
public static void Decrypt(string fileIn, string fileOut, string Password)
{
FileStream fsIn = new FileStream(fileIn, FileMode.Open, FileAccess.Read);
//line 518
FileStream fsOut = new FileStream(fileOut, FileMode.OpenOrCreate, FileAccess.Write);
PasswordDeriveBytes pdb = new PasswordDeriveBytes(Password,
new byte[] {0x49, 0x76, 0x61, 0x6e, 0x20, 0x4d,
0x65, 0x64, 0x76, 0x65, 0x64, 0x65, 0x76});
Rijndael alg = Rijndael.Create();
alg.Key = pdb.GetBytes(32);
alg.IV = pdb.GetBytes(16);
CryptoStream cs = new CryptoStream(fsOut,
alg.CreateDecryptor(), CryptoStreamMode.Write);
int bufferLen = 4096;
byte[] buffer = new byte[bufferLen];
int bytesRead;
do
{
bytesRead = fsIn.Read(buffer, 0, bufferLen);
cs.Write(buffer, 0, bytesRead);
} while (bytesRead != 0);
cs.Close();
fsIn.Close();
}
How should I fix this? Is there something wrong in the code?