Monday, September 12, 2011

Encryption/Decryption is now working

Encryption/Decryption is now working! You can see how it works here:

public static string Encrypt( string target )
{
byte[] ptextBytes = Encoding.ASCII.GetBytes( target);
byte[] ctextBytes = ProtectedData.Protect( ptextBytes, entropy,
SCOPE );
char[] chars = new char[1024];
Convert.ToBase64CharArray( ctextBytes, 0,
ctextBytes.GetLength(0), chars, 0 );
return ToString( chars );
}

public static string Decrypt( string target )
{
byte[] ctextBytes = Convert.FromBase64String( target );
byte[] ptextBytes = ProtectedData.Unprotect( ctextBytes, entropy,
SCOPE );
return Encoding.ASCII.GetString( ptextBytes );
}

private static string ToString( char[] chars )
{
StringBuilder sb = new StringBuilder();
foreach ( char c in chars )
if( c != (char) 0 )
sb.Append( c );

return sb.ToString();
}

entropy is defined as:

private static byte[] entropy = new byte[] { 9, 8, 7, 6, 5, 4, 3, 2, 1, 0 }; // not the real values used for obvious reasons!

SCOPE is defined as:

private const DataProtectionScope SCOPE = DataProtectionScope.LocalMachine; // this will be using the web servers encryption key.

The 'trick' to getting this code working was to only copy the non-zero characters from the chars array.

No comments:

Post a Comment