Skip to content

Instantly share code, notes, and snippets.

@clod81
Created January 21, 2024 21:44
Show Gist options
  • Save clod81/f608f63f93cbc379d31090fe9d1298e5 to your computer and use it in GitHub Desktop.
Save clod81/f608f63f93cbc379d31090fe9d1298e5 to your computer and use it in GitHub Desktop.
C# DPAPI Example Usage
using System;
using System.Security.Cryptography;
using System.Text;
namespace Encrypt1
{
internal class Program
{
readonly static byte[] entropy = {}; //the entropy
private static string Encrypt(string text)
{
// first, convert the text to byte array
byte[] originalText = Encoding.Unicode.GetBytes(text);
// then use Protect() to encrypt your data
byte[] encryptedText = ProtectedData.Protect(originalText, entropy, DataProtectionScope.CurrentUser);
//and return the encrypted message
return Convert.ToBase64String(encryptedText);
}
private static string Decrypt(string text)
{
// the encrypted text, converted to byte array
byte[] encryptedText = Convert.FromBase64String(text);
// calling Unprotect() that returns the original text
byte[] originalText = ProtectedData.Unprotect(encryptedText, entropy, DataProtectionScope.CurrentUser);
// finally, returning the result
return Encoding.Unicode.GetString(originalText);
}
static void Main(string[] args)
{
String toEncrypt = "SuperSoooooSecret";
Console.WriteLine("Value to encrypt: {0}", toEncrypt);
String encrypted = Encrypt(toEncrypt);
Console.WriteLine("Encrypted: {0}", encrypted);
Console.WriteLine("Decrypted: {0}", Decrypt(encrypted));
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment