AesCryptoServiceProvider decrypt создает поврежденный файл
Я пишу веб-приложение, которое позволяет пользователям загружать файлы и скачивать файлы. Файлы, такие как doc или jpeg разрешены. Файлы зашифрованы в процессе загрузки и расшифрованы в процессе загрузки.
Я использую AES в качестве алгоритма, с одним ключом для всех файлов, но разной солью для каждого файла. Я также проверяю, чтобы и метод шифрования, и дешифрование использовали один и тот же ключ и метод заполнения.
Однако, когда веб-сайт пытается расшифровать файл, он создает поврежденный файл, который имеет больший размер, чем исходный файл.
Так что я не уверен, что процесс шифрования или дешифрования испортит файл.
Вот исходный код:
//Encryption method
private bool SaveEnryptFile(FileUpload fileUp)
{
try
{
string fName = fileUp.PostedFile.FileName;
string outputDir = Path.Combine(ConfigurationManager.AppSettings["clientDocFolder"] + CurrentUser.Name);
DirectoryInfo di = new DirectoryInfo(outputDir);
di.Create();
string outputFile = Path.Combine(outputDir, fName);
if (File.Exists(outputFile))
{
throw new Exception("File already exists");
}
else
{
byte[] file = new byte[fileUp.PostedFile.ContentLength];
fileUp.PostedFile.InputStream.Read(file, 0, fileUp.PostedFile.ContentLength);
//get the key string from web.config
var key = ConfigurationManager.AppSettings["keyFile"];
//randomly create a salt
byte[] salt = new byte[8];
var rng = new RNGCryptoServiceProvider();
rng.GetBytes(salt);
var derivedBytes = new Rfc2898DeriveBytes(key, salt);
using (AesCryptoServiceProvider alg = new AesCryptoServiceProvider())
{
alg.Key = derivedBytes.GetBytes(alg.KeySize / 8);
alg.IV = derivedBytes.GetBytes(alg.BlockSize / 8);
alg.Padding = PaddingMode.Zeros;
// Create a decrytor to perform the stream transform.
using (ICryptoTransform encryptor = alg.CreateEncryptor())
{
using (var fs = File.Create(outputFile))
{
//store the salt in the encrypted file
fs.Write(salt, 0, 8);
//write encrypted bytes to encrypted file
using (CryptoStream cs = new CryptoStream(fs, encryptor, CryptoStreamMode.Write))
{
cs.Write(file, 0, file.Length);
cs.FlushFinalBlock();
}
}
}
}
return true;
}
}
catch (Exception ex)
{
throw new Exception(ex.Message);
}
}
// Метод расшифровки:
var path = Path.Combine(ConfigurationManager.AppSettings["clientDocFolder"] + CurrentUser.Name + "\\" + ((WebControl)sender).Attributes["DocumentID"]);
if (File.Exists(path))
{
using (FileStream fs = new FileStream(path, FileMode.Open, FileAccess.Read))
{
//Get the salt from the encrypted file
byte[] salt = new byte[8];
fs.Read(salt, 0, salt.Length);
//get key string from web.config file
string key = ConfigurationManager.AppSettings["keyFile"];
var derivedBytes = new Rfc2898DeriveBytes(key, salt);
AesCryptoServiceProvider alg = new AesCryptoServiceProvider();
alg.Key = derivedBytes.GetBytes(alg.KeySize / 8);
alg.IV = derivedBytes.GetBytes(alg.BlockSize / 8);
alg.Padding = PaddingMode.Zeros;
using (ICryptoTransform decryptor = alg.CreateDecryptor())
{
//byte array to store encrypted bytes.
//I use fs.Length-8 because first 8 bytes were used to store salt
byte[] encryptedBytes = new byte[fs.Length - 8];
int encryptedByteCnt = fs.Read(encryptedBytes, 0, encryptedBytes.Length);
using (MemoryStream ms = new MemoryStream(encryptedBytes))
{
byte[] plainBytes = new byte[encryptedByteCnt];
using (CryptoStream cs = new CryptoStream(ms, decryptor, CryptoStreamMode.Read))
{
//decrypt encrypted bytes into a byte array
int decryptedByteCnt = cs.Read(plainBytes, 0, plainBytes.Length);
}
//Write decrypted bytes in response stream
Response.ContentType = "application/octet-stream";
Response.AddHeader("content-disposition", "attachment; filename=" + Path.GetFileName(path));
Response.OutputStream.Write(plainBytes, 0, plainBytes.Length);
Response.Flush();
}
}
}
}
else
{
ScriptManager.RegisterStartupScript(this, this.GetType(), "DownloadDocument", "alert('" + String.Format("There is no file such as {0} exists. Please contact us if you face this problem.);", ((WebControl)sender).Attributes["DocumentID"]) + "'", true);
return;
}
1 ответ
Оказалось, проблема в размещенном файле http. Это приводит к тому, что входные байты не читаются в массив. В итоге мне нужно было установить позицию потока, прежде чем он будет читать 0.
Поэтому я немного изменил код в методе шифрования, как показано ниже:
От
byte[] file = new byte[fileUp.PostedFile.ContentLength];
fileUp.PostedFile.InputStream.Read(file, 0, fileUp.PostedFile.ContentLength);
Для того, чтобы:
byte[] file = new byte[fileUp.PostedFile.ContentLength];
Stream st = fileUp.FileContent;
st.Position = 0;
st.Read(file, 0, file.Length);
st.Close();
Однако я столкнулся с проблемой расшифровки. Это добавит дополнительные байты в расшифрованный массив байтов. Большинство из них 0.
Обновлено: я изменил расшифровку записи, чтобы она не записывала конечные нули. Но теперь загруженный файл, отправленный с сервера, будет содержать html самой страницы.