Skip to content

Instantly share code, notes, and snippets.

@thomaslevesque
Created May 26, 2013 14:40
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save thomaslevesque/5652991 to your computer and use it in GitHub Desktop.
Save thomaslevesque/5652991 to your computer and use it in GitHub Desktop.
Simple string encryption using Data Protection API in WinRT
using System;
using System.Threading.Tasks;
using Windows.Security.Cryptography;
using Windows.Security.Cryptography.DataProtection;
namespace App1
{
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