Home > database >  C# Algorithm / Class to generate a secure password with expiry
C# Algorithm / Class to generate a secure password with expiry

Time:08-25

Since I do not want to reinvent the wheel I'm pretty sure there is a solution already out there: I want to generate a password (based on a different one, byte[] or whatever) that has an expiry. The idea is that a client-generated password is only valid for a specific time on the server. So as long as their clocks aren't too different they can communicate with alternating password. Sounds pretty much like certificates so there sure already is a solution out there.

CodePudding user response:

As it seems to me you are looking for a token approach. You can check JWT it has expiry date and can be easily validated at server side.

Here is a small example:

string GenerateToken()
{
    var mySecret = "mySecretmySecretmySecret";
    var mySecurityKey = new SymmetricSecurityKey(Encoding.ASCII.GetBytes(mySecret));

    var tokenHandler = new JwtSecurityTokenHandler();
    var tokenDescriptor = new SecurityTokenDescriptor
    {
        NotBefore = DateTime.UtcNow.AddSeconds(-2),
        Expires = DateTime.UtcNow.AddSeconds(2),
        SigningCredentials = new SigningCredentials(mySecurityKey, SecurityAlgorithms.HmacSha256Signature)
    };

    var token = tokenHandler.CreateToken(tokenDescriptor);
    return tokenHandler.WriteToken(token);
}

bool ValidateCurrentToken(string token)
{
    var mySecret = "mySecretmySecretmySecret";
    var mySecurityKey = new SymmetricSecurityKey(Encoding.ASCII.GetBytes(mySecret));

    var tokenHandler = new JwtSecurityTokenHandler();
    try
    {
        tokenHandler.ValidateToken(token, new TokenValidationParameters
        {
            ClockSkew = TimeSpan.Zero,
            ValidateIssuerSigningKey = true,
            ValidateIssuer = false,
            ValidateAudience = false,
            IssuerSigningKey = mySecurityKey
        }, out SecurityToken validatedToken);
    }
    catch
    {
        return false;
    }
    return true;
}

Notice the ClockSkew = TimeSpan.Zero here. By default MS allows the tokens to differ up to 5 minutes. We only want to use the absolute token's expiry.

  • Related