Friday, August 21, 2009

Encrypting sensitive information

Scenario:
One of the common requirements from client is to encrypt sensitive information.I do it all the time, but never posted anything here.

Solution:
.Net framework has supporting classes for encryption.

Code:

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

string strSSNValueInitial = "000-0-0000-000";

//Here's how you encrypt
byte[] arrSecret = Encoding.Unicode.GetBytes(strSSNValue);
byte[] arrKey = {0, 1, 2};
byte[] arrEncryptedData = ProtectedData.Protect(arrSecret, arrKey,DataProtectionScope.LocalMachine);


//Here's how you decrypt it back
byte[] ssnValueArray = ProtectedData.Unprotect(arrEncryptedData, arrKey,DataProtectionScope.LocalMachine);
string strSSNValueFinal = Encoding.Unicode.GetString(ssnValueArray);

Another option:

You can also use SecureString class , the value of SecureString is automatically encrypted.
using System.Security;
using System.Runtime.InteropServices;

string strSSNValue = "000-000-000";

//Securing data in secure string
SecureString strSecure = new SecureString();
char[] charValue = Encoding.Unicode.GetChars(Encoding.Unicode.GetBytes(strSSNValue));
for (int i = 0; i < charValue.Length; i++)
{
strSecure.AppendChar(charValue[i]);
}

//Reading it back
IntPtr objPointer = Marshal.SecureStringToBSTR(strSecure);
string strSSNValue = Marshal.PtrToStringUni(objPointer);

0 comments: