Monday, March 14, 2005

Generating a Random Password - C#

public static string GenerateRandomPassword(int PasswordLength) { string _allowedChars = "abcdefghijkmnpqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ23456789!@$?"; Byte[] randomBytes = new Byte[PasswordLength]; char[] chars = new char[PasswordLength]; int allowedCharCount = _allowedChars.Length; Random randomObj = new Random(); for(int i = 0;i < PasswordLength; i++) { randomObj.NextBytes(randomBytes); chars[i] = _allowedChars[(int)randomBytes[i] % allowedCharCount]; } return new string(chars); }

No comments: