I assume you want to store encrypted XAML in your project and then decrypt and compile it on the fly. First write a command-line utility to encrypt your files i.e. something like this:
private static byte[] Key = { 123, 217, 19, 11, 24, 26, 85, 45, 114, 184, 27, 162, 37, 112, 222, 209, 241, 24, 175, 144, 173, 53, 196, 29, 24, 26, 17, 218, 131, 236, 53, 209 };
private static byte[] Vector = { 146, 64, 191, 111, 23, 3, 113, 119, 231, 121, 252, 112, 79, 32, 114, 156 };
static void Main(string[] args)
{
var xaml = File.ReadAllBytes(args[0]);
using (var outputFile = new FileStream(args[1], FileMode.Create))
{
RijndaelManaged rm = new RijndaelManaged();
var transform = rm.CreateEncryptor(Key, Vector);
CryptoStream cs = new CryptoStream(outputFile, transform, CryptoStreamMode.Write);
cs.Write(xaml, 0, xaml.Length);
cs.FlushFinalBlock();
}
}
Now back in your main main application set your XAML Build Actions to "None" and add Pre-build commands in your project settings to encrypt each of your files (I'll pretend here you're just keeping them as encrypted files in the same folder as your exe, in reality you'd made them embedded resources or something). Then it's simply a matter of loading them, decrypting them and compiling them:
private void LoadEncryptedXaml(string filename)
{
RijndaelManaged rm = new RijndaelManaged();
var transform = rm.CreateDecryptor(Key, Vector);
var bytes = File.ReadAllBytes(filename);
using (var stream = new MemoryStream(bytes))
using (var cs = new CryptoStream(stream, transform, CryptoStreamMode.Read))
{
var decrypted = ReadFully(cs);
using (var memstream = new MemoryStream(decrypted))
{
var xaml_object = XamlReader.Load(memstream);
// do something with it here, e.g. if you know it's a resource dictionary then merge it with the other app resources
Application.Current.Resources.MergedDictionaries.Add(xaml_object as ResourceDictionary);
}
}
}
The ReadFully function just reads until the end of the stream, you can get the source code here.