So im making a encryption/decryption windows forms project for fun, but my decryption app shows me a error: An unhandled exception of type 'System.Security.Cryptography.CryptographicException' occurred in mscorlib.dll
Additional information: Bad Data.
I can't find any fixes in the internet and in not that good in c#, so maybe you can help me.
Encryption:
static void EncryptFile(string sInputFile,
string sOutputFile,
string sKey)
{
FileStream fsInput = new FileStream(sInputFile, FileMode.Open, FileAccess.Read);
FileStream fsEncrypted = new FileStream(sOutputFile, FileMode.Create, FileAccess.Write);
DESCryptoServiceProvider DES = new DESCryptoServiceProvider();
DES.Key = ASCIIEncoding.ASCII.GetBytes(sKey);
DES.IV = ASCIIEncoding.ASCII.GetBytes(sKey);
ICryptoTransform desencrypt = DES.CreateEncryptor();
CryptoStream cryptoStream = new CryptoStream(fsEncrypted, desencrypt, CryptoStreamMode.Write);
byte[] bytearrayinput = new byte[fsInput.Length - 1];
fsInput.Read(bytearrayinput, 0, bytearrayinput.Length);
cryptoStream.Write(bytearrayinput, 0, bytearrayinput.Length);
}
Decryption:
static void DecryptFile(string sInputFilename,
string sOutputFilename,
string sKey)
{
DESCryptoServiceProvider DES = new DESCryptoServiceProvider();
DES.Key = ASCIIEncoding.ASCII.GetBytes(sKey);
DES.IV = ASCIIEncoding.ASCII.GetBytes(sKey);
FileStream fsread = new FileStream(sInputFilename, FileMode.Open, FileAccess.Read);
ICryptoTransform desdecrypt = DES.CreateDecryptor();
CryptoStream cryptostreamDecr = new CryptoStream(fsread, desdecrypt, CryptoStreamMode.Read);
StreamWriter fsDecrypted = new StreamWriter(sOutputFilename);
fsDecrypted.Write(new StreamReader(cryptostreamDecr).ReadToEnd());
fsDecrypted.Flush();
fsDecrypted.Close();
}
How i use them:
EncryptFile(fileBox.Text, fileOutFolder+"/encrypted.txt", sSecretKey);
DecryptFile(fileBox.Text, saveFileDialog1.FileName, keyBox.Text)