Reputation: 155
is it possible to decrypt file asynchronously and transform it into bytes ? the bytes data will be converted into another object like image or something else.
so, I want to decypt file without having to save it into real file, for example:
I encrypted an image and I want to decrypt it without saving into real file, in this case the decrypted file is an image.
so the best way to do this from my opinion is to read the bytes from the encrypted file asynchronously and convert the bytes into an image.
I need a clue guys, even without code examples, I appreciate it. thanks.
I encrypted the file using this basic code from msdn:
private static void encrypt(string fileInput,
string fileOutput,
string key)
{
FileStream fInput = new FileStream(fileInput, FileMode.Open, FileAccess.Read);
FileStream fOutput = new FileStream(fileOutput, FileMode.Create, FileAccess.Write);
DESCryptoServiceProvider des = new DESCryptoServiceProvider();
des.Key = ASCIIEncoding.ASCII.GetBytes(password);
des.IV = ASCIIEncoding.ASCII.GetBytes(password);
ICryptoTransform encryptor = des.CreateEncryptor();
CryptoStream cryptostream = new CryptoStream(fOutput, encryptor, CryptoStreamMode.Write);
Byte[] byteArrayInput = new byte[fInput.Length];
fInput.ReadAsync(byteArrayInput, 0, byteArrayInput.Length);
cryptostream.WriteAsync(byteArrayInput, 0, byteArrayInput.Length);
cryptostream.Close();
fInput.Close();
fOutput.Close();
des.Dispose();
}
Upvotes: 0
Views: 1684
Reputation: 3497
First of all:
using
instead of manually disposing your streams.DESCryptoServiceProvider
is indeed a disposable.async
method to be able to use await
with async calls.You can use a MemoryStream
:
using (var fInput = new FileStream(fileInput, FileMode.Open, FileAccess.Read))
using (var ms = new MemoryStream())
{
using (var des = new DESCryptoServiceProvider())
{
des.Key = ASCIIEncoding.ASCII.GetBytes(password);
des.IV = ASCIIEncoding.ASCII.GetBytes(password);
ICryptoTransform encryptor = des.CreateEncryptor();
using (var cryptostream = new CryptoStream(ms, encryptor, CryptoStreamMode.Write))
{
// Here, we're writing to the cryptoStream which will write to ms.
await fInput.CopyToAsync(cryptostream);
}
// Do something with ms here.
// If you want a byte array just do: ms.ToArray()
}
}
A lot of apis will ask you for a Stream
. MemoryStream
extends Stream
so you can just hand ms
to them but make sure you're doing that inside the using
block for ms
.
If you just need a byte array from the end result, you can use ms.ToArray()
. This way you're able to use the byte array from outside the using
blocks if you want to.
Upvotes: 1