Hi all,
I want to create an encryption program and started thinking about not
storing sensitive information in the memory since I guess someone
might steal my computer an scan my memory.
So I wrote this method for getting a password from the console and
converting it to an array of bytes for later use in the encryption
algorithm.
The weak point as I see it is the storage of the password - it will be
stored in the memory as an array of chars/bytes. I fill it with junk
but still: what worries me is what List.ToArray() does - is a new
instance created and then lost somewhere? (see sample below)
* Is there a better way to do this?
* Is the textbox with stars instead of plain text safe (for GUI use
instead of console use)?
Thanks,
Per Erik Strandberg
Linear or Nonlinear optimization in .NET?
see http://tomopt.com/tomnet/
-----
/// <summary>
/// Generate hash value (key) from the console (from the password).
/// </summary>
/// <param name="Message"> Message to prompt</param>
/// <param name="one">True if it is the first key, false if second.</
param>
/// <returns>The key: a byte array of length 16 or 32.</returns>
public static byte[] GetKeyFromConso le(string Message, bool one)
{
// we use bytes/chars here - pretty bad since ĺäö will get lost
List<bytepass = new List<byte>();
// prompt
Console.Write(" {0}>", Message);
// read one key and store in list
char c = Console.ReadKey (true).KeyChar;
while (!(c == Environment.New Line[0] || c == '\n'))
{
Console.Write(' *');
pass.Add((byte) c);
c = Console.ReadKey (true).KeyChar;
}
Console.WriteLi ne();
byte[] b;
// get hash value of the keypunches
if (one)
{
// first key using sha
// or some secret native hash function
SHA256Managed sha = new SHA256Managed() ;
b = sha.ComputeHash (pass.ToArray() );
sha.Clear();
}
else
{
// second key using md5
// or some secret native hash function
MD5CryptoServic eProvider md = new MD5CryptoServic eProvider();
b = md.ComputeHash( pass.ToArray()) ;
md.Clear();
}
// clear temp char and chararr
c = '*';
for (int i = 0; i < pass.Count; i++)
pass[i] = (byte)'*';
// return hashvalue
return b;
}