danyolgiax danyolgiax - 17 days ago 5
C# Question

Encrypt and decrypt a MemoryStream

I need to crypt and later decrypt a MemoryStream (original large PDF file). I tried the following code:

public static string GenerateKey()
{
var desCrypto = (DESCryptoServiceProvider)DES.Create();

return Encoding.ASCII.GetString(desCrypto.Key);
}

public static MemoryStream Encrypt(Stream fsInput,string sKey)
{
var fsEncrypted=new MemoryStream();

var des = new DESCryptoServiceProvider
{
Key = Encoding.ASCII.GetBytes(sKey),
IV = Encoding.ASCII.GetBytes(sKey)
};
var desencrypt = des.CreateEncryptor();
var cryptostream = new CryptoStream(fsEncrypted,desencrypt,CryptoStreamMode.Write);

var bytearrayinput = new byte[fsInput.Length];
fsInput.Read(bytearrayinput, 0, bytearrayinput.Length);
cryptostream.Write(bytearrayinput, 0, bytearrayinput.Length);
fsInput.Close();

fsEncrypted.Flush();
fsEncrypted.Position = 0;
return fsEncrypted;
}

public static MemoryStream Decrypt(Stream fsread,string sKey)
{
var des = new DESCryptoServiceProvider
{
Key = Encoding.ASCII.GetBytes(sKey),
IV = Encoding.ASCII.GetBytes(sKey)
};

var sOutputFilename = new MemoryStream();
var desdecrypt = des.CreateDecryptor();
var cryptostreamDecr = new CryptoStream(fsread,desdecrypt,CryptoStreamMode.Read);

var fsDecrypted = new StreamWriter(sOutputFilename);
fsDecrypted.Write(new StreamReader(cryptostreamDecr).ReadToEnd());
fsDecrypted.Flush();
fsDecrypted.Close();
sOutputFilename.Position = 0;

return sOutputFilename;
}


Call example:

var sSecretKey = FileHelper.GenerateKey();
var encyptedPdfContent = FileHelper.Encrypt(httpPostedFile.InputStream, sSecretKey);

var decryptedPdfContent = FileHelper.Decrypt(encyptedPdfContent, sSecretKey);


Encrypt seems to work as expected but when I try to decrypt

fsDecrypted.Write(new StreamReader(cryptostreamDecr).ReadToEnd());


returns me
Bad Data
Exception.

What's wrong in my code?

I saw other posts and all of them are related to the string encoding (Encoding.Unicode). I don't have a string. I have a memorystream that is not encoded at all!

Answer

Please add following code in decrypt method

des.Padding = PaddingMode.Zeros;
Comments