Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How would you generate repeateable encryption key?

I am looking to encrypt data. I want to generate encryption keys based on a password, and some moving value, like time. The goal is to have the key change, but have anyone that knows the password be able to decrypt. This is happening in C#. I am using the following code to hash the password.

private static string GetPasswordHash(string password)
{
    TimeSpan span = (DateTime.UtcNow - new DateTime(1900, 1, 1));
    string result = Convert.ToInt32(span.TotalHours).ToString();
    result += password;
    result += Convert.ToInt32(span.TotalDays).ToString();
    result = Convert.ToBase64String(SHA256.Create().ComputeHash(Encoding.ASCII.GetBytes(result)));
    return result;
}

I then use that hash, plus a salt to generate a key.

        Rfc2898DeriveBytes rdb = new Rfc2898DeriveBytes(GetPasswordHash(password), salt);
        rdb.IterationCount = 1000;

        RijndaelManaged rm = new RijndaelManaged();
        rm.KeySize = 256;
        rm.Key = rdb.GetBytes(32);
        rm.IV = rdb.GetBytes(16);

There seem to be issues with the way I am doing this. Some of the computers are in different timezones, or if the hour ticks as I send the data, or if the machines times are slightly off. Are there better suggestions?

like image 624
Anthony D Avatar asked Dec 22 '22 09:12

Anthony D


1 Answers

The standard strategy is to just send the value (time, etc.) just be sent with the encryption key. Since the value you are using is public knowledge, it is fine if whoever first creates the password provides the "moving value" publicly. See Salt. What you are doing is not a new technique. You also seem to be using Key Strengthening.

like image 194
Brian Avatar answered Jan 03 '23 22:01

Brian