I already got my password encrypted and store it in database but now I want to compare the encrypted value to the password that a user type upon loading a page. Consider this code:
string userName = txtusername.Text;
string password = txtpassword.Text;
Encryptor en = new Encryptor(EncryptionAlgorithm.Rc2, CreateRandomPassword(7));
password = en.Encrypt(password);
DataTable dt = uMManager.ValidateUser(userName, password);
CreateRandomPassword Method
private static string CreateRandomPassword(int passwordLength)
{
string allowedChars = "abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNOPQRSTUVWXYZ0123456789!@$?_-";
char[] chars = new char[passwordLength];
Random rd = new Random();
for (int i = 0; i < passwordLength; i++)
{
chars[i] = allowedChars[rd.Next(0, allowedChars.Length)];
}
return new string(chars);
}
Encryptor Class
public class Encryptor
{
EncryptEngine engin;
public byte[] IV;
public Encryptor(EncryptionAlgorithm algID, string key)
{
engin = new EncryptEngine(algID, key);
}
public EncryptEngine EncryptEngine
{
get
{
return engin;
}
set
{
engin = value;
}
}
public string Encrypt(string MainString)
{
MemoryStream memory = new MemoryStream();
CryptoStream stream = new CryptoStream(memory, engin.GetCryptTransform(), CryptoStreamMode.Write);
StreamWriter streamwriter = new StreamWriter(stream);
streamwriter.WriteLine(MainString);
streamwriter.Close();
stream.Close();
IV = engin.Vector;
byte[] buffer = memory.ToArray();
memory.Close();
return Convert.ToBase64String(buffer);
}
}
I made a local method to generate random string for RC2 encryption. EncryptionAlgorithm is a Enums for the types of encryption.
Now how can I compare ‘password’ to the password field in my database to check if the credential is correct
You can’t check if the credential is correct, since you’ve encrypted it with a key you’ve thrown away. If you store the key along with the password, the encryption serves no purpose. If you don’t, you can’t verify.
Instead of trying to create a new way to store passwords, why not use one of the ways that’s known to work?