Created
May 26, 2013 14:40
-
-
Save thomaslevesque/5652991 to your computer and use it in GitHub Desktop.
Simple string encryption using Data Protection API in WinRT
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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