Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Encrypt & Decrypt Local Images in Windows Store App

I'm building a Windows Store App including a local folder of Images.

I want to protect all the Images so they can't be accessed from:

C:\Users[username]\AppData\Local\Packages\LocalState\Settings\settings.dat

I know I should encrypt and decrypt the Images using the DataProtectionProvider class, but the documentation only shows how to encrypt/decrypt strings...

How should I convert a Bitmap image into a byte array? or should I encode it with Base64? Is there any tutorial or sample using this process?

like image 342
yalematta Avatar asked Nov 09 '22 15:11

yalematta


1 Answers

It's easiest if the images you want to encrypt are loaded from files and written back out to files. Then you can do:

async void EncryptFile(IStorageFile fileToEncrypt, IStorageFile encryptedFile)
{
    IBuffer buffer = await FileIO.ReadBufferAsync(fileToEncrypt);

    DataProtectionProvider dataProtectionProvider = 
        new DataProtectionProvider(ENCRYPTION_DESCRIPTOR);

    IBuffer encryptedBuffer = 
        await dataProtectionProvider.ProtectAsync(buffer);

    await FileIO.WriteBufferAsync(encryptedFile, encryptedBuffer);
}

DataProtectionProvider.ProtectStreamAsync is another alternative if you can get stream instances from your inputs and outputs. For example, if you have a byte[] containing your image data then you can create an in-memory input stream from it:

byte[] imageData = ...
using (var inputMemoryStream = new MemoryStream(imageData).AsInputStream())
{
    ...
}

Edit: Then for example to decrypt the file and display it in an Image control you could do:

var encryptedBuffer = await FileIO.ReadBufferAsync(encryptedFile);

var dataProtectionProvider = new DataProtectionProvider();

var buffer = await dataProtectionProvider.UnprotectAsync(encryptedBuffer);

var bmp = new BitmapImage();
await bmp.SetSourceAsync(buffer.AsStream().AsRandomAccessStream());
imageControl.Source = bmp;
like image 104
peterdn Avatar answered Nov 14 '22 23:11

peterdn