Saturday, 21 April 2012

Data Protection API

System.Security.Cryptography.ProtectedData

Namespace: System.Security.Cryptography
Assembly: System.Security (in System.Security.dll)

using System;
using System.Collections;
using System.Security.Cryptography;
using System.Text;

public class DataProtectionSample
{
// Create byte array for additional entropy when using Protect method
static byte[] _additionalEntropy = { 9, 8, 7, 6, 5 };

public static void Main()
{
//Original data
string secret = "Magic";
PrintValues("The original data is:", secret);

//Convert to bytes
byte[] secretInBytes = Encoding.UTF8.GetBytes(secret);
PrintValues("The original data in bytes is:", secretInBytes);

//Encrypt the bytes
byte[] encryptedSecret = Protect(secretInBytes);
PrintValues("The encrypted byte array is:", encryptedSecret);

// Decrypt the bytes
byte[] originalDataInBytes = Unprotect(encryptedSecret);
PrintValues("The original data in bytes is:", originalDataInBytes);

//Convert to string
string originalData = Encoding.UTF8.GetString(originalDataInBytes);
PrintValues("The original data is:", originalData);
}

public static byte[] Protect(byte[] data)
{
// Encrypt the data using DataProtectionScope.CurrentUser.
// The result can be decrypted only by the same current user.
return ProtectedData.Protect(data, _additionalEntropy, DataProtectionScope.CurrentUser);
}

public static byte[] Unprotect(byte[] data)
{
//Decrypt the data using DataProtectionScope.CurrentUser.
return ProtectedData.Unprotect(data, _additionalEntropy, DataProtectionScope.CurrentUser);
}

public static void PrintValues(string header, IEnumerable detail)
{
Console.WriteLine(header);
foreach (var item in detail) { Console.Write("\t{0}", item); }
Console.WriteLine();
}
}
image

Source:  http://stevenhollidge.com/blog-source-code/DataProtectionSample.zip

1 comment:

  1. good example but
    there are any way tool to protect files and folder

    ReplyDelete