Reputation: 543
I'm looking for a code to generate the same password for the string presented. Like a challenge and response.
I want to do a very simple winform based on c# in which I will enter a name and get a random string that represent the password for this name.
For example: I will enter "Bob", click on "Generate password" and get for example "hakdn11jhfh32" (something random), then for the name "David" I'll get another password, but when I'll enter "Bob" again I will get the same password for Bob before ("hakdn11jhfh32").
Is there an easy way?
I actually thought of just giving some characters for one character (like: a=8j2, 5=j1mm.....) and then just do a replace for every name given. But I'm hoping that there is something easier and more automatic.
Upvotes: 0
Views: 103
Reputation: 10497
What you are describing is hashing. Here's an official article:
http://msdn.microsoft.com/en-us/library/aa545602%28v=cs.70%29.aspx
Also, this article provides a small piece of code:
http://www.techpowerup.com/forums/threads/c-hash-encryption-example.62293/
public string GeneratePasswordHash(string thisPassword)
{
MD5CryptoServiceProvider md5 = new MD5CryptoServiceProvider();
byte[] tmpSource;
byte[] tmpHash
tmpSource = ASCIIEncoding.ASCII.GetBytes(thisPassword); // Turn password into byte array
tmpHash = md5.ComputeHash(tmpSource);
StringBuilder sOuput = new StringBuilder(tmpHash.Length);
for (int i = 0; i < tmpHash.Lenth; i++)
{
sOutput.Append(tmpHash[i].ToString(“X2”)); // X2 formats to hexadecimal
}
return sOutput.ToString();
}
Upvotes: 3
Reputation: 726529
You can use the property of pseudo-random number generator that lets you seed its sequence. Make a random number generator like this:
String name = "Bob";
Random rnd = new Random(name.hashCode());
Now you can generate a string of random character codes using the rnd.nextInt(numChars)
, where numChars
is the number of characters that can appear in the password:
StringBuilder pwd = new StringBuilder();
int numCharInPassword = 8;
String legalChars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789!@#$%^&*/{}[]\|";:<>()+=";
for (int i = 0 ; i != numCharInPassword ; i++) {
pwd.append(legalChars.charAt(rnd.nextInt(legalChars.length())));
}
This guarantees that starting with the same name and using the same pre-set password will produce the same password. Sometimes, a different name could produce the same password, too, but that is unlikely.
Upvotes: 1