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.

Saturday, September 10, 2011

Working on Encryption/Decryption for the site

I already have a better hash working for passwords on the site that use a unique salt value and repeat the hash 10,000 times:

public static byte[] Encode( string password, out byte[] salt )
{
Rfc2898DeriveBytes rdb = new Rfc2898DeriveBytes( password,
32, 10000 );
salt = rdb.Salt;
return rdb.GetBytes( 256 );
}

public static bool ValidatePassword( string password,
byte[] storedSalt,
byte[] encPassword )
{
Rfc2898DeriveBytes rdb = new Rfc2898DeriveBytes( password,
storedSalt,
10000 );
byte[] passwordEnc = rdb.GetBytes( 256 );
return Equals( encPassword, passwordEnc );
}

At the moment, I'm having some difficulty getting a Base64 string in the correct format, but once I get that issue solved (over the next two or three days), I'll post those two methods here just like I did for the two that are working as designed.