using Microsoft.AspNetCore.Http;
using System.IO;
using System.Security.Cryptography;
using System.Threading.Tasks;
public class FilesHelper
{
public static void Encrypt(string inputFilePath, string outputfilePath)
{
using (Aes encryptor = Aes.Create())
{
Rfc2898DeriveBytes pdb = new Rfc2898DeriveBytes(Constants.EncryptKey.ToString(), new byte[16]);
encryptor.Key = pdb.GetBytes(16);
encryptor.IV = pdb.GetBytes(16);
using (FileStream fileOutput = new FileStream(outputfilePath, FileMode.Create))
{
using (CryptoStream cs = new CryptoStream(fileOutput, encryptor.CreateEncryptor(), CryptoStreamMode.Write))
{
using (FileStream fileInput = new FileStream(inputFilePath, FileMode.Open))
{
int data;
while ((data = fileInput.ReadByte()) != -1)
{
cs.WriteByte((byte)data);
}
}
cs.FlushFinalBlock();
}
}
}
}
public static async Task Encrypt(IFormFile inputFile, string outputfilePath)
{
using (Aes encryptor = Aes.Create())
{
Rfc2898DeriveBytes pdb = new Rfc2898DeriveBytes(Constants.EncryptKey.ToString(), new byte[16]);
encryptor.Key = pdb.GetBytes(16);
encryptor.IV = pdb.GetBytes(16);
using (FileStream fileOutput = new FileStream(outputfilePath, FileMode.Create))
{
using (CryptoStream cs = new CryptoStream(fileOutput, encryptor.CreateEncryptor(), CryptoStreamMode.Write))
{
using (MemoryStream fileInput = new MemoryStream())
{
await inputFile.CopyToAsync(fileInput);
fileInput.Seek(0, SeekOrigin.Begin);
int data;
while ((data = fileInput.ReadByte()) != -1)
{
cs.WriteByte((byte)data);
}
}
cs.FlushFinalBlock();
}
}
}
}
public static async Task<MemoryStream> Decrypt(string inputFilePath)
{
using (Aes encryptor = Aes.Create())
{
Rfc2898DeriveBytes pdb = new Rfc2898DeriveBytes(Constants.EncryptKey.ToString(), new byte[16]);
encryptor.Key = pdb.GetBytes(16);
encryptor.IV = pdb.GetBytes(16);
using (FileStream fsInput = new FileStream(inputFilePath, FileMode.Open))
{
using (CryptoStream cs = new CryptoStream(fsInput, encryptor.CreateDecryptor(), CryptoStreamMode.Read))
{
var outcsput = new MemoryStream();
await cs.CopyToAsync(outcsput).ConfigureAwait(false);
return outcsput;
}
}
}
}
public static async Task<string> DecryptFileToBase64(string inputFilePath)
{
using (Aes encryptor = Aes.Create())
{
Rfc2898DeriveBytes pdb = new Rfc2898DeriveBytes(Constants.EncryptKey.ToString(), new byte[16]);
encryptor.Key = pdb.GetBytes(16);
encryptor.IV = pdb.GetBytes(16);
using (FileStream fsInput = new FileStream(inputFilePath, FileMode.Open))
{
using (CryptoStream cs = new CryptoStream(fsInput, encryptor.CreateDecryptor(), CryptoStreamMode.Read))
{
using (var outcsput = new MemoryStream())
{
await cs.CopyToAsync(outcsput).ConfigureAwait(false);
return Helper.ConvertToBase64(outcsput);
}
}
}
}
}
}