One Time Password Generation

In many applications, it is often required to generate one time passwords.

One time passwords are used in scenarios either for new user registration (assign the new user a random one time password) or for users who forget their password. In the latter case, a temporary one time password is typically generated and emailed to the user and when the user logs on next time using the one time password, he is required to change it.

Many ways exist in generating such one time password. Here I will show a simple way (in C#). In .Net, the Guid class encapsulates methods to generate Guids. By definition, Guids are typically random and thus are suitable for one time password use. The method GenerateOneTimePassword() shown below first generates a Guid and makes it the desired length. To make the password more random, the method randomly changes the letters in the newly generated Guid (typically all capital letters) to lower cases.

private const int OneTimePasswordLength = 10;

public string GenerateOneTimePassword()

{

Guid guid = Guid.Empty;

string s = string.Empty;

string temp = string.Empty;

StringBuilder sb = new StringBuilder();

Random rndGenerator = new Random();

double rnd = 0;

guid = Guid.NewGuid();

s = guid.ToString(“N”);

if (OneTimePasswordLength < s.Length)

s = s.Substring(0, OneTimePasswordLength);

foreach (char ss in s)

{

if (Char.IsLetter(ss))

{

rnd = rndGenerator.NextDouble();

if (rnd > 0.5)

temp = ss.ToString().ToUpper();

else

temp = ss.ToString();

}

else

{

temp = ss.ToString();

}

sb.Append(temp);

}

return sb.ToString();

}

This method is good to generate random passwords up to 32 in length.

Be Sociable, Share!

Leave a Reply