Jon Skeet [C# MVP] <sk***@pobox.com> wrote in
news:MP************************@msnews.microsoft.c om:
Federico Bari <fe********@tiscali.it> wrote: I have to read and encrypted file (with DESCryptoServiceProvider
class) and decrypt it without save the clear file in the disk!!! ie
i'd like to have the decryption in a string variable because for safe
reasons i cannot save the decription in the disk even if for a short
time. The CryptoStream seem to work only with in and out files; do
somebody know how i can do? Thank you very much.
No, CryptoStreams work with *streams*, not files. You can use a memory
stream, for instance. If you *really* want the result in a string
variable rather than a byte array, I suggest Base64 encoding the
binary data.
Please consider the following code, where cryptString is the filetext:
private string DecryptText(string cryptString)
{
try
{
SymmetricAlgorithm mCSP;
mCSP = (SymmetricAlgorithm)(new DESCryptoServiceProvider
());
mCSP.GenerateKey();
mCSP.GenerateIV();
ICryptoTransform ct = mCSP.CreateDecryptor
(mCSP.Key,mCSP.IV);
MemoryStream ms = new MemoryStream();
byte[] bytArr = Convert.FromBase64String(cryptString);
CryptoStream cs = new CryptoStream
(ms,ct,CryptoStreamMode.Write);
//write to cryptostream in memory
cs.Write(bytArr,0,bytArr.Length);
cs.Flush();
cs.Close();
return System.Text.Encoding.UTF8.GetString(ms.ToArray
());
}
catch(Exception e)
{
MessageBox.Show(e.Message);
}
return "";
}
This should work as needed.
aacool