Skip to content

Instantly share code, notes, and snippets.

@cmorgado
Created September 26, 2014 22:36
Show Gist options
  • Save cmorgado/55b6796fff534ec35a18 to your computer and use it in GitHub Desktop.
Save cmorgado/55b6796fff534ec35a18 to your computer and use it in GitHub Desktop.
Universal Apps : protect all data you store on settings, etc etc
using System;
using System.Threading.Tasks;
using Windows.Security.Cryptography;
using Windows.Security.Cryptography.DataProtection;
namespace CMM.Extensions
{
public static class DataProtectionExtensions
{
public static async Task<string> ProtectAsync(this string clearText, string scope = "LOCAL=user")
{
if (clearText == null)
throw new ArgumentNullException("clearText");
if (scope == null)
throw new ArgumentNullException("scope");
var clearBuffer = CryptographicBuffer.ConvertStringToBinary(clearText, BinaryStringEncoding.Utf8);
var provider = new DataProtectionProvider(scope);
var encryptedBuffer = await provider.ProtectAsync(clearBuffer);
return CryptographicBuffer.EncodeToBase64String(encryptedBuffer);
}
public static async Task<string> UnprotectAsync(this string encryptedText)
{
if (encryptedText == null)
throw new ArgumentNullException("encryptedText");
var encryptedBuffer = CryptographicBuffer.DecodeFromBase64String(encryptedText);
var provider = new DataProtectionProvider();
var clearBuffer = await provider.UnprotectAsync(encryptedBuffer);
return CryptographicBuffer.ConvertBinaryToString(BinaryStringEncoding.Utf8, clearBuffer);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment