locked
function to generate random password RRS feed

  • Question

  • User-1487768462 posted
    Private Function RandomPassword() As String Dim arrPossibleChars As Char() = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789".ToCharArray() Dim intPasswordLength As Integer = 10 Dim stringPassword As String = Nothing Dim rand As System.Random = New Random Dim i As Integer = 0 For i = 0 To intPasswordLength Dim intRandom As Integer = rand.Next(arrPossibleChars.Length) stringPassword = stringPassword & arrPossibleChars(intRandom).ToString() Next RandomPassword = stringPassword End Function
    Wednesday, September 15, 2004 10:45 AM

All replies

  • User-967169866 posted
    System.Guid.NewGuid().ToString() :)
    Wednesday, September 15, 2004 10:10 PM
  • User-1827453801 posted
    string MakePassword(int length){ Random ran = new Random(DateTime.Now.Second); char[] password = new char[length]; for (int i = 0; i < length; i++){ int[] n = {ran.Next(48, 57), ran.Next(65, 90), ran.Next(97, 122)}; //int[] n = {ran.Next(33, 57), ran.Next(65, 90), ran.Next(97, 122)}; int picker = ran.Next(0, 3); if (picker == 3)//if i make the maxvalue 2 it "never" appears... dunno whats going on there picker = 2; password[i] = (char)n[picker]; } return new string(password); } :D
    Wednesday, September 15, 2004 11:14 PM
  • User-280513258 posted
    I created this function that has worked very well in the past. You call the function by telling it the length of the password you need. It returns a random password of that length made up of letters and numbers with the first character being a letter. If needed, you could add additional characters to the string strDefault. Function GeneratePassword(ByVal iNumChars As Integer) As String 'This function is used to generate a random PASSWORD that can be 'emailed to the user. Const strDefault = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ01234567890" Const strFirstChar = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ" Dim iCount As Integer Dim strReturn As String Dim iNumber As Integer Dim iLength As Integer Randomize() 'Generate first character of PASSWORD which has to be a letter iLength = Len(strFirstChar) iNumber = Int((iLength * Rnd()) + 1) strReturn = Mid(strFirstChar, iNumber, 1) 'Generate the next n characters of the PASSWORD iLength = Len(strDefault) For iCount = 1 To iNumChars - 1 iNumber = Int((iLength * Rnd()) + 1) strReturn += Mid(strDefault, iNumber, 1) Next Return strReturn End Function Jeff
    Thursday, September 16, 2004 8:23 AM
  • User1001789538 posted
    I created this class for random and human readable Passwords: public class RandGen { public DataTable QuadList = null; public RandGen() { } public void LoadQuads( string Filename ) { object[] r = new object[2]; DataSet ds = new DataSet(); DataTable dt = new DataTable(); dt.TableName = "q"; dt.Columns.Add( "v", System.Type.GetType("System.String") ); dt.Columns.Add( "n", System.Type.GetType("System.Int32") ); ds.Tables.Add( dt ); Encoding e = Encoding.GetEncoding( 1252 ); using (StreamReader sr = new StreamReader(Filename + ".txt", e )) { string line; while ((line = sr.ReadLine()) != null ) { r[0] = line.Substring( 0, 4 ); r[1] = int.Parse( line.Substring( 5, 6 ) ); dt.Rows.Add( r ); } } QuadList = dt; } private string GetQuad( DataRow[] rows, int val ) { int sum = 0; foreach ( DataRow row in rows ) { int v = (int)row["n"]; if ( sum + v > val ) return row["v"].ToString(); sum += v; } return ""; } private DataRow[] Select( string s ) { DataRow[] rows = QuadList.Select( "v LIKE '" + s + "*'" ); return rows; } public string GenerateString( int MaxLen ) { string s = " "; int n; Random random = new Random( (int)DateTime.Now.Ticks ); string rs = ""; int k = 0; do { DataRow[] rows = Select( s ); n = 0; foreach ( DataRow row in rows ) n += (int)row["n"]; if ( n > 0 ) { int r = random.Next( n ); string q = GetQuad( rows, r ); int d = s.Length; s = q.Remove( 0, 1 ); rs += q.Remove( 0, d ); } else if ( s.Length > 0 ) { s = s.Remove( 0, 1 ); n = 1; } k++; } while ( n > 0 && rs.Length < MaxLen && k < 100 ); return rs; } } You can call it as follows: rg = (RandGen)Session["RANDGEN"]; if ( rg == null ) { rg = new RandGen(); rg.LoadQuads( Server.MapPath( "quad" ) ); Session["RANDGEN"] = rg; } string pass = rg.GenerateString( 12 ); You need a textfile quad.txt which is sorted list of groups of 4 letters+space from your dictionary. The number after group is says how often you found this group in the disctionary. For german language: ... zum:000206 zun:000034 zn:000002 zur:000288 zus:000169 zut:000013 zuv:000011 Zuw:000015 zuz:000009 zwa:000048 zw:000004 zwe:000296 zwi:000094 zw:000009 Zyl:000002 Zyp:000003 aage:000001 aale:000001 aare:000014 aari:000001 aarm:000003 aars:000004 aarw:000001 aate:000001 aats:000002 abae:000001 abak:000001 abn:000004 abas:000003 abat:000001 abba:000001 Abbi:000009 abbl:000001 abei:000023 ... This class returns for german such passwords as: dereszügeleg, nochtschlige, Fabenschafte, Mariegenausü
    Wednesday, September 22, 2004 2:15 AM
  • User743145481 posted
    worldspawn[], you may be interested in this bit of documentation for Rand.Next(int, int): Return Value A 32-bit signed integer greater than or equal to minValue and less than maxValue.
    Thursday, December 23, 2004 3:13 PM
  • User-1827453801 posted

    Revisiting password generation.

    Here's my revised password generating method:

    public static class SecurityUtil
        {
            //ASCII character set ranges
            static int[][] characterSets = new int[][]{
                new int[] {48, 57},
                new int[] {65, 90},
                new int[] {97, 122}
            };

            //Prevents swear words (or any words) from being generated
            static Regex vowelRemover = new Regex("[AEIOUaeiou]");

            public static string CreatePassword(int passwordLength)
            {
                return CreatePassword(passwordLength, true);
            }

            public static string CreatePassword(int passwordLength, bool removeVowels)
            {
                RNGCryptoServiceProvider seedGenerator = new RNGCryptoServiceProvider();
                char[] password = new char[passwordLength];

                for (int i = 0; i < passwordLength; i++)
                {
                    byte[] charSetByte = new byte[1], characterByte = new byte[1];
                    int charSet, character;
                    char passwordChar;

                chargen :
                    seedGenerator.GetBytes(charSetByte);
                    seedGenerator.GetBytes(characterByte);

                    charSet = Convert.ToInt32(charSetByte[0]);
                    character = Convert.ToInt32(characterByte[0]);

                    charSet = charSet % characterSets.Length;
                    character = (character % (characterSets[charSet][1] - characterSets[charSet][0])) + characterSets[charSet][0];

                    passwordChar = (char)character;

                    if (removeVowels && vowelRemover.IsMatch(passwordChar.ToString()))
                    {
                        goto chargen;
                    }

                    password[i] = passwordChar;
                }

                return new string(password, 0, password.Length);
            }
        }
     

    Thursday, July 19, 2007 9:49 PM
  • User743145481 posted

    It's not bad (did not test it), but the only change I might make would be to convert the goto loop into a do-while loop:

    do
    {
    
        // ... everything before the if statement and after "chargen:"
    
    } while ( removeVowels && vowelRemover.IsMatch(passwordChar.ToString()) )

    The usage of goto here isn't bad, obviously, but it's not necessary.

    Friday, July 27, 2007 1:38 PM
  • User-1827453801 posted

     Thanks Picky, the main thing I was trying to achieve with this was to get rid of using the Random class. The requirement for a seed (i was using the current Second) just sucked.

    Good call on the do while loop, but i do love legitmate uses for goto :) I always forget about do while. It's a gem. 

    Saturday, August 18, 2007 4:37 AM
  • User-1827453801 posted

     In my quest for perfect password generation I've come up with this latest iteration... this password creation method incorporates a word from a word list and surrounds it with random characters.

      

    public static string GeneratePasswordWithWord(int passwordLength){
    if (passwordLength < 5)
    throw new InvalidOperationException("Stupid password requested... and denied!");

    string word = GetRandomWord(passwordLength - 3);
    RNGCryptoServiceProvider seedGenerator = new RNGCryptoServiceProvider();
    int characterRandSeed;
    byte[] seedByte = new byte[1];

    seedGenerator.GetBytes(seedByte);
    characterRandSeed = DateTime.Now.Millisecond + (int)seedByte[0];
    Random capitalRand = new Random(characterRandSeed);

    int capitals = 2;
    for (int i = 0; i < capitals; i++)
    {
    int index = capitalRand.Next(0, word.Length);
    char[] wordArray = word.ToCharArray();
    wordArray[index] = char.ToUpper(wordArray[index]);
    word = new string(wordArray);
    }

    string garbage;
    if (word.Length < passwordLength)
    garbage = GeneratePassword(passwordLength - word.Length);
    else
    {
    word = word.Substring(0, passwordLength);
    return word;
    }

    return garbage.Substring(0, garbage.Length / 2) + word + garbage.Substring((garbage.Length / 2), garbage.Length - (garbage.Length / 2));
    }

    public static string GetRandomWord(int maxLength)
    {
    string[] words = Resource.WordList.Split('\n');
    words = (from c in words where c.Length <= maxLength select c).ToArray();
    RNGCryptoServiceProvider seedGenerator = new RNGCryptoServiceProvider();
    int characterRandSeed;
    byte[] seedByte = new byte[1];

    seedGenerator.GetBytes(seedByte);
    characterRandSeed = DateTime.Now.Millisecond + (int)seedByte[0];
    Random characterRand = new Random(characterRandSeed);

    string word = null;
    do
    {
    int index = characterRand.Next(0, words.Length);
    word = words[index];
    } while (word.Length < 5);

    return word.Trim();
    }
     
    Resource.WordList is a list of words that, in my class library is stored as a resource. It's just a newline delimited list of words, if you google word list you should be able to finding something like it (or even the same list). Heres a sample anyway:
    abbreviation
    abbreviations
    abettor
    abettors
    abilities
    ability
    abrasion
    abrasions
    abrasive
    abrasives
    absence
    absences
    abuse
    abuser
    abusers
    abuses
    acceleration
    accelerations
    acceptance
    acceptances
    acceptor
    acceptors
    access
    accesses
    accessories
     
    ...and so on 
    Wednesday, November 12, 2008 1:44 AM
  • User487807879 posted

    I wouldn't want to underrate your effort, but are you sure that all of that code is neccessery for such a trivial task as a random password when you can create it as simple as this:
    string password = Guid.NewGuid().ToString().Replace("-", "").Substring(0, 10);

    Wednesday, November 12, 2008 6:01 AM
  • User-1827453801 posted

    kipo this approach creates password that people (should) be able to remember. If all I wanted was 10 characters of gibberish I would have used the guid approach.

    Also I'm quite sure guid's don't have any letters past "f" futhermore the letters are always lowercase (you could call .ToUpper but then they'd just all upper case). So basically you've reduced the number of possible chars from 10+26+26 down to 10+6... that's quite a drop in password quality.

    Wednesday, November 12, 2008 7:14 PM
  • User487807879 posted

    Why do you think anyone would want to keep the random password as the one he will use? I'm pretty sure that anyone (at least anyone who knows how to do it) will change the random password in the "change password" part of the site first time he logins. I'll repeat again - my intention is not to underrate your effort and I really think you did a great job, but from my point of view random password is exactlly what the name says - random and I don't see why would you create it in such a complicated way. If I'm missing the reason, please enlighten me.

    Thursday, November 13, 2008 2:45 AM
  • User-1827453801 posted

    Yeah mate i get your not making a personal attack. np [8-|]

    If our users get a random, secure yet memorable password they might be less tempted to use "pizza" as their password.

    It's complexity is only driven by meeting the following reqs:
    *Secure

    *Memorable

    *Doesn't generate swearwords as passwords

    And while this thread may have been originally about making random passwords (and my first code post did just that), it's very old and is now just a spot for me to upload any revisions/additions of my code purely for fame and glory [cool] Coz i get that a all time you know, at bars, i'm like "Hey I'm Sam" and the chicks go "Oh wow! You're that guy who wrote that amazing password generating code! Take me home!"

     ...Plus it was fun too write.

    Thursday, November 13, 2008 2:58 AM
  • User487807879 posted

    "]And while this thread may have been originally about making random passwords (and my first code post did just that), it's very old and is now just a spot for me to upload any revisions/additions of my code purely for fame and glory Cool Coz i get that a all time you know, at bars, i'm like "Hey I'm Sam" and the chicks go "Oh wow! You're that guy who wrote that amazing password generating code! Take me home!"
    If that's the case, I'll have to write my version too! [:D]

    Friday, November 14, 2008 8:36 AM
  • User-319574463 posted

     This looks to be an interesting approach to a long-standing problem. It is definitely worthy of further study.

    I would appreciate

    • Your confirmation of the release of the code to the Community under the terms of LGPL and/or any form of freedom to copy recognised by the Open Source community. In the CommonData project at http://www.codeplex.com/CommonData, I have used LGPL.
    • How you would like the attribution to your original work to be done? I would normally use a "Derived from open source work by .... at http://forums.asp.net/p/693032/2754975.aspx" as I will optimise the code with the help of ReSharper.
    Wednesday, November 19, 2008 7:30 AM
  • User-1827453801 posted

    Hi Tatworth. I appreciate your interest... you can go nuts do whatever with it, for credits you can link to this thread or my profile page (http://forums.asp.net/members/worldspawn_5B005D00_.aspx). I formally confirm LGPL status on the below chunk of code [:)]

     

    I was thinking of setting up a webservice/single website that ppl could use... prolly already been done though.

    Full source:

    using System;
    using System.Linq;
    using System.Security.Cryptography;
    using System.Text.RegularExpressions;
    
    namespace Shivam.Web.Security
    {
        public static class SecurityUtil
        {
            //ASCII character set ranges
            static int[][] characterSets = new int[][]{
                new int[] {48, 57},
                new int[] {65, 90},
                new int[] {97, 122}
            };
    
            //Prevents swear words (or any words) from being generated
            static Regex vowelRemover = new Regex("[AEIOUaeiou]");
    
            public static string GeneratePassword(int passwordLength)
            {
                //Generate strong random seeds for the Random class to use as a seed
                RNGCryptoServiceProvider seedGenerator = new RNGCryptoServiceProvider();
                int characterRandSeed, charsetRandSeed;
                byte[] seedByte = new byte[1];
    
                /*
                 * Add the generated seed number to the current millisecond otherwise to increase (greatly increase) 
                 * the number of possible generated passwords
                 */
                seedGenerator.GetBytes(seedByte);
                characterRandSeed = DateTime.Now.Millisecond + (int)seedByte[0];
    
                seedGenerator.GetBytes(seedByte);
                charsetRandSeed = DateTime.Now.Millisecond + (int)seedByte[0];
    
                Random characterRand = new Random(characterRandSeed),
                    charsetRand = new Random(charsetRandSeed);
                char[] password = new char[passwordLength];
    
                for (int i = 0; i < passwordLength; i++)
                {
                    int charset = charsetRand.Next(0, 3);//Rand will never? return the maximum value in range.
                    if (charset == 3) charset--;//But just in case...
                    char? passwordChar = null;
    
                    //Check for vowels, this avoids having undesirable words appearing in your passwords
                    while (passwordChar == null || vowelRemover.IsMatch(passwordChar.Value.ToString()))
                    {
                        passwordChar = (char)characterRand.Next(characterSets[charset][0], characterSets[charset][1]);
                    }
    
                    password[i] = passwordChar.Value;
                }
    
                return new string(password);
            }
    
            public static string GeneratePasswordWithWord(int passwordLength){
                if (passwordLength < 5)
                    throw new InvalidOperationException("Stupid password requested... and denied!");
    
                string word = GetRandomWord(passwordLength - 3);
                RNGCryptoServiceProvider seedGenerator = new RNGCryptoServiceProvider();
                int characterRandSeed;
                byte[] seedByte = new byte[1];
    
                seedGenerator.GetBytes(seedByte);
                characterRandSeed = DateTime.Now.Millisecond + (int)seedByte[0];
                Random capitalRand = new Random(characterRandSeed);
    
                int capitals = 2;
                for (int i = 0; i < capitals; i++)
                {
                    int index = capitalRand.Next(0, word.Length);
                    char[] wordArray = word.ToCharArray();
                    wordArray[index] = char.ToUpper(wordArray[index]);
                    word = new string(wordArray);
                }
    
                string garbage;
                if (word.Length < passwordLength)
                    garbage = GeneratePassword(passwordLength - word.Length);
                else
                {
                    word = word.Substring(0, passwordLength);
                    return word;
                }
    
                return garbage.Substring(0, garbage.Length / 2) + word + garbage.Substring((garbage.Length / 2), garbage.Length - (garbage.Length / 2));
            }
    
            public static string GetRandomWord(int maxLength)
            {
                string[] words = Resource.WordList.Split('\n');
                words = (from c in words where c.Length <= maxLength select c).ToArray();
                RNGCryptoServiceProvider seedGenerator = new RNGCryptoServiceProvider();
                int characterRandSeed;
                byte[] seedByte = new byte[1];
    
                seedGenerator.GetBytes(seedByte);
                characterRandSeed = DateTime.Now.Millisecond + (int)seedByte[0];
                Random characterRand = new Random(characterRandSeed);
    
                string word = null;
                do
                {
                    int index = characterRand.Next(0, words.Length);
                    word = words[index];
                } while (word.Length < 5);
    
                return word.Trim();
            }
        }
    }
      
    Wednesday, November 19, 2008 9:57 PM
  • User-319574463 posted

     Thank you Worldspawn. Next step for me is to get a word list that is freely redistributable.

    Thursday, November 20, 2008 3:14 AM
  • User-209105085 posted

    If i generate password using GeneratePassword() method why asp.net membership API throws exception saying Invalid password?

    Friday, February 20, 2009 5:59 PM
  • User-319574463 posted

    If i generate password using GeneratePassword() method why asp.net membership API throws exception saying Invalid password?

     

    The asp.net membership has its own rules for what constitutes a valid password. The exception was probably thrown because the complexity rules were broken. Please post the exact text of the message.

    Friday, February 20, 2009 7:06 PM
  • User-1159791214 posted

    code below generates an alphanumeric pass..

    public string GetRandomString(Random rnd, int length)
        {
            string charPool
            = "ABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890";
            StringBuilder rs = new StringBuilder();

            while (length-- > 0)
                rs.Append(charPool[(int)(rnd.NextDouble() * charPool.Length)]);

            return rs.ToString();
        }

     plz tune up according to your need.

    bye...

    Monday, February 23, 2009 3:12 AM
  • User-209105085 posted

    Got it...by default ASP.NET membership expect at least 1 non alphanumeric character and the password generator only generates alphanumeric characters.

    Tuesday, February 24, 2009 12:33 PM
  • User-1827453801 posted

    Add the charset range to the characterSets array. And modify the first two lines of the for loop. Its actually very sloppy of me to have hard coded the 3 in there. Replace the 3 with characterSets.length.

    However this doesn't guarantee a non alphanumeric character will be generated. You'd need to force a character to be chosen from that range. Easy enough to do. I might post an update that accepts some kind of instructions to control the number of characters drawn from a particular character range.

    Saturday, February 28, 2009 6:19 AM