Jon Skeet [C# MVP] <sk***@pobox.co m> wrote in
news:MP******** *************** *@msnews.micros oft.com:
Federico Bari <fe********@tis cali.it> wrote: I have to read and encrypted file (with DESCryptoServic eProvider
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(str ing cryptString)
{
try
{
SymmetricAlgori thm mCSP;
mCSP = (SymmetricAlgor ithm)(new DESCryptoServic eProvider
());
mCSP.GenerateKe y();
mCSP.GenerateIV ();
ICryptoTransfor m ct = mCSP.CreateDecr yptor
(mCSP.Key,mCSP. IV);
MemoryStream ms = new MemoryStream();
byte[] bytArr = Convert.FromBas e64String(crypt String);
CryptoStream cs = new CryptoStream
(ms,ct,CryptoSt reamMode.Write) ;
//write to cryptostream in memory
cs.Write(bytArr ,0,bytArr.Lengt h);
cs.Flush();
cs.Close();
return System.Text.Enc oding.UTF8.GetS tring(ms.ToArra y
());
}
catch(Exception e)
{
MessageBox.Show (e.Message);
}
return "";
}
This should work as needed.
aacool