Security is a big issue in computing these days. One way you can protect user's data is by using the DPAPI (Data Protection Application Programming Interface) available on Windows.
The article Managed DPAPI Part I: ProtectedData provides a very good explanation of what this is, so I won't bore you with the details here, but I will provide you with a code sample that you can use. To use this code sample, simply create a C# console application in VS.Net 2005 and paste this into the main file (I believe it will be called Program.cs).
One thing that should be mentioned, this does not protect the data in memory. It can be used to protect data that is written out to disk, but an industrious hacker can get the sensitive information out of memory. Check out Managed DPAPI Part II: ProtectedMemory for more information on protecting data while it is in memory.
using System;
using System.Security.Cryptography; // reference assembly System.Security.dll
using System.Text;
namespace DPAPIExample
{
class Program
{
static void Main(string[] args)
{
string test = "hello world";
string encryptedValue;
string decryptedValue;
Console.WriteLine(test);
encryptedValue = Encrypt(test);
Console.WriteLine(encryptedValue);
decryptedValue = Decrypt(encryptedValue);
Console.WriteLine(decryptedValue);
Console.ReadKey();
}
// This is an article on using the ProtectedData API (a wrapper around DPAPI)
// http://blogs.msdn.com/shawnfa/archive/2004/05/05/126825.aspx
private static byte[] sEntropy = System.Text.Encoding.Unicode.GetBytes("put whatever you want here");
public static string Encrypt(string text)
{
Byte[] data = Encoding.Unicode.GetBytes(text);
Byte[] protectedData = ProtectedData.Protect(data, sEntropy, DataProtectionScope.CurrentUser);
return Convert.ToBase64String(protectedData);
}
public static string Decrypt(string encryptedText)
{
Byte[] protectedData = Convert.FromBase64String(encryptedText);
Byte[] data = ProtectedData.Unprotect(protectedData, sEntropy, DataProtectionScope.CurrentUser);
string text = Encoding.Unicode.GetString(data);
return text;
}
}
}
No comments:
Post a Comment