Decrypting a resource at runtime
Hi every one, there will be a time where you want to embed an encrypted resource. Here is how you will decrypt that resource and pass a normal stream to your app. What you must do is encrypt your resource (take a look at Symmetric Key Encryption using Rijndael and C# ) and then and it to your application as an embedded resource. Then all what you must do next is call “DecryptEmbedded“ to get the decrypted stream which you can then use in your app.
private
Stream DecryptEmbedded(string sResource, string sPwd)
{
Stream streamIn = null;
Stream streamOut = new MemoryStream();
Assembly asm = Assembly.GetExecutingAssembly();
streamIn = asm.GetManifestResourceStream(sResource);
RijndaelManaged RijndaelCipher = new RijndaelManaged();
byte[] Salt = Encoding.ASCII.GetBytes(sPwd.Length.ToString());
PasswordDeriveBytes SecretKey = new PasswordDeriveBytes(sPwd, Salt);
ICryptoTransform Decryptor = RijndaelCipher.CreateDecryptor(SecretKey.GetBytes(32), SecretKey.GetBytes(16));
CryptoStream cryptoStream = new CryptoStream(streamIn, Decryptor, CryptoStreamMode.Read);
int ByteData;
while ((ByteData=cryptoStream.ReadByte()) != -1)
{
streamOut.WriteByte((byte)ByteData);
}
streamIn.Close();
cryptoStream.Close();
return streamOut;
}