<p>When a user on our site loses his password and heads off to the Lost Password page we need to give him a new temporary password. I don't really mind how random this is, or if it matches all the "needed" strong password rules, all I want to do is give them a password that they can change later.</p>

<p>The application is a Web application written in C#. so I was thinking of being mean and going for the easy route of using part of a Guid. i.e.</p>

<pre><code>Guid.NewGuid().ToString("d").Substring(1,8)
</code></pre>

<p>Suggesstions? thoughts?</p>

[{'answer_id': 54994, 'author': 'GEOCHET', 'author_id': 5640, 'author_profile': 'https://Stackoverflow.com/users/5640', 'pm_score': 5, 'selected': False, 'text': '<p>This is a lot larger, but I think it looks a little more comprehensive:\n<a href="http://www.obviex.com/Samples/Password.aspx" rel="noreferrer">http://www.obviex.com/Samples/Password.aspx</a></p>\n\n<pre><code>///////////////////////////////////////////////////////////////////////////////\n// SAMPLE: Generates random password, which complies with the strong password\n//         rules and does not contain ambiguous characters.\n//\n// To run this sample, create a new Visual C# project using the Console\n// Application template and replace the contents of the Class1.cs file with\n// the code below.\n//\n// THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY OF ANY KIND,\n// EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE IMPLIED\n// WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A PARTICULAR PURPOSE.\n// \n// Copyright (C) 2004 Obviex(TM). All rights reserved.\n// \nusing System;\nusing System.Security.Cryptography;\n\n/// &lt;summary&gt;\n/// This class can generate random passwords, which do not include ambiguous \n/// characters, such as I, l, and 1. The generated password will be made of\n/// 7-bit ASCII symbols. Every four characters will include one lower case\n/// character, one upper case character, one number, and one special symbol\n/// (such as \'%\') in a random order. The password will always start with an\n/// alpha-numeric character; it will not start with a special symbol (we do\n/// this because some back-end systems do not like certain special\n/// characters in the first position).\n/// &lt;/summary&gt;\npublic class RandomPassword\n{\n    // Define default min and max password lengths.\n    private static int DEFAULT_MIN_PASSWORD_LENGTH  = 8;\n    private static int DEFAULT_MAX_PASSWORD_LENGTH  = 10;\n\n    // Define supported password characters divided into groups.\n    // You can add (or remove) characters to (from) these groups.\n    private static string PASSWORD_CHARS_LCASE  = "abcdefgijkmnopqrstwxyz";\n    private static string PASSWORD_CHARS_UCASE  = "ABCDEFGHJKLMNPQRSTWXYZ";\n    private static string PASSWORD_CHARS_NUMERIC= "23456789";\n    private static string PASSWORD_CHARS_SPECIAL= "*$-+?_&amp;=!%{}/";\n\n    /// &lt;summary&gt;\n    /// Generates a random password.\n    /// &lt;/summary&gt;\n    /// &lt;returns&gt;\n    /// Randomly generated password.\n    /// &lt;/returns&gt;\n    /// &lt;remarks&gt;\n    /// The length of the generated password will be determined at\n    /// random. It will be no shorter than the minimum default and\n    /// no longer than maximum default.\n    /// &lt;/remarks&gt;\n    public static string Generate()\n    {\n        return Generate(DEFAULT_MIN_PASSWORD_LENGTH, \n                        DEFAULT_MAX_PASSWORD_LENGTH);\n    }\n\n    /// &lt;summary&gt;\n    /// Generates a random password of the exact length.\n    /// &lt;/summary&gt;\n    /// &lt;param name="length"&gt;\n    /// Exact password length.\n    /// &lt;/param&gt;\n    /// &lt;returns&gt;\n    /// Randomly generated password.\n    /// &lt;/returns&gt;\n    public static string Generate(int length)\n    {\n        return Generate(length, length);\n    }\n\n    /// &lt;summary&gt;\n    /// Generates a random password.\n    /// &lt;/summary&gt;\n    /// &lt;param name="minLength"&gt;\n    /// Minimum password length.\n    /// &lt;/param&gt;\n    /// &lt;param name="maxLength"&gt;\n    /// Maximum password length.\n    /// &lt;/param&gt;\n    /// &lt;returns&gt;\n    /// Randomly generated password.\n    /// &lt;/returns&gt;\n    /// &lt;remarks&gt;\n    /// The length of the generated password will be determined at\n    /// random and it will fall with the range determined by the\n    /// function parameters.\n    /// &lt;/remarks&gt;\n    public static string Generate(int   minLength,\n                                  int   maxLength)\n    {\n        // Make sure that input parameters are valid.\n        if (minLength &lt;= 0 || maxLength &lt;= 0 || minLength &gt; maxLength)\n            return null;\n\n        // Create a local array containing supported password characters\n        // grouped by types. You can remove character groups from this\n        // array, but doing so will weaken the password strength.\n        char[][] charGroups = new char[][] \n        {\n            PASSWORD_CHARS_LCASE.ToCharArray(),\n            PASSWORD_CHARS_UCASE.ToCharArray(),\n            PASSWORD_CHARS_NUMERIC.ToCharArray(),\n            PASSWORD_CHARS_SPECIAL.ToCharArray()\n        };\n\n        // Use this array to track the number of unused characters in each\n        // character group.\n        int[] charsLeftInGroup = new int[charGroups.Length];\n\n        // Initially, all characters in each group are not used.\n        for (int i=0; i&lt;charsLeftInGroup.Length; i++)\n            charsLeftInGroup[i] = charGroups[i].Length;\n\n        // Use this array to track (iterate through) unused character groups.\n        int[] leftGroupsOrder = new int[charGroups.Length];\n\n        // Initially, all character groups are not used.\n        for (int i=0; i&lt;leftGroupsOrder.Length; i++)\n            leftGroupsOrder[i] = i;\n\n        // Because we cannot use the default randomizer, which is based on the\n        // current time (it will produce the same "random" number within a\n        // second), we will use a random number generator to seed the\n        // randomizer.\n\n        // Use a 4-byte array to fill it with random bytes and convert it then\n        // to an integer value.\n        byte[] randomBytes = new byte[4];\n\n        // Generate 4 random bytes.\n        RNGCryptoServiceProvider rng = new RNGCryptoServiceProvider();\n        rng.GetBytes(randomBytes);\n\n        // Convert 4 bytes into a 32-bit integer value.\n        int seed = BitConverter.ToInt32(randomBytes, 0);\n\n        // Now, this is real randomization.\n        Random  random  = new Random(seed);\n\n        // This array will hold password characters.\n        char[] password = null;\n\n        // Allocate appropriate memory for the password.\n        if (minLength &lt; maxLength)\n            password = new char[random.Next(minLength, maxLength+1)];\n        else\n            password = new char[minLength];\n\n        // Index of the next character to be added to password.\n        int nextCharIdx;\n\n        // Index of the next character group to be processed.\n        int nextGroupIdx;\n\n        // Index which will be used to track not processed character groups.\n        int nextLeftGroupsOrderIdx;\n\n        // Index of the last non-processed character in a group.\n        int lastCharIdx;\n\n        // Index of the last non-processed group.\n        int lastLeftGroupsOrderIdx = leftGroupsOrder.Length - 1;\n\n        // Generate password characters one at a time.\n        for (int i=0; i&lt;password.Length; i++)\n        {\n            // If only one character group remained unprocessed, process it;\n            // otherwise, pick a random character group from the unprocessed\n            // group list. To allow a special character to appear in the\n            // first position, increment the second parameter of the Next\n            // function call by one, i.e. lastLeftGroupsOrderIdx + 1.\n            if (lastLeftGroupsOrderIdx == 0)\n                nextLeftGroupsOrderIdx = 0;\n            else\n                nextLeftGroupsOrderIdx = random.Next(0, \n                                                     lastLeftGroupsOrderIdx);\n\n            // Get the actual index of the character group, from which we will\n            // pick the next character.\n            nextGroupIdx = leftGroupsOrder[nextLeftGroupsOrderIdx];\n\n            // Get the index of the last unprocessed characters in this group.\n            lastCharIdx = charsLeftInGroup[nextGroupIdx] - 1;\n\n            // If only one unprocessed character is left, pick it; otherwise,\n            // get a random character from the unused character list.\n            if (lastCharIdx == 0)\n                nextCharIdx = 0;\n            else\n                nextCharIdx = random.Next(0, lastCharIdx+1);\n\n            // Add this character to the password.\n            password[i] = charGroups[nextGroupIdx][nextCharIdx];\n\n            // If we processed the last character in this group, start over.\n            if (lastCharIdx == 0)\n                charsLeftInGroup[nextGroupIdx] = \n                                          charGroups[nextGroupIdx].Length;\n            // There are more unprocessed characters left.\n            else\n            {\n                // Swap processed character with the last unprocessed character\n                // so that we don\'t pick it until we process all characters in\n                // this group.\n                if (lastCharIdx != nextCharIdx)\n                {\n                    char temp = charGroups[nextGroupIdx][lastCharIdx];\n                    charGroups[nextGroupIdx][lastCharIdx] = \n                                charGroups[nextGroupIdx][nextCharIdx];\n                    charGroups[nextGroupIdx][nextCharIdx] = temp;\n                }\n                // Decrement the number of unprocessed characters in\n                // this group.\n                charsLeftInGroup[nextGroupIdx]--;\n            }\n\n            // If we processed the last group, start all over.\n            if (lastLeftGroupsOrderIdx == 0)\n                lastLeftGroupsOrderIdx = leftGroupsOrder.Length - 1;\n            // There are more unprocessed groups left.\n            else\n            {\n                // Swap processed group with the last unprocessed group\n                // so that we don\'t pick it until we process all groups.\n                if (lastLeftGroupsOrderIdx != nextLeftGroupsOrderIdx)\n                {\n                    int temp = leftGroupsOrder[lastLeftGroupsOrderIdx];\n                    leftGroupsOrder[lastLeftGroupsOrderIdx] = \n                                leftGroupsOrder[nextLeftGroupsOrderIdx];\n                    leftGroupsOrder[nextLeftGroupsOrderIdx] = temp;\n                }\n                // Decrement the number of unprocessed groups.\n                lastLeftGroupsOrderIdx--;\n            }\n        }\n\n        // Convert password characters into a string and return the result.\n        return new string(password);\n     }\n}\n\n/// &lt;summary&gt;\n/// Illustrates the use of the RandomPassword class.\n/// &lt;/summary&gt;\npublic class RandomPasswordTest\n{\n    /// &lt;summary&gt;\n    /// The main entry point for the application.\n    /// &lt;/summary&gt;\n    [STAThread]\n    static void Main(string[] args)\n    {\n        // Print 100 randomly generated passwords (8-to-10 char long).\n        for (int i=0; i&lt;100; i++)\n            Console.WriteLine(RandomPassword.Generate(8, 10));\n    }\n}\n//\n// END OF FILE\n///////////////////////////////////////////////////////////////////////////////\n</code></pre>\n'}, {'answer_id': 54997, 'author': 'Radu094', 'author_id': 3263, 'author_profile': 'https://Stackoverflow.com/users/3263', 'pm_score': 7, 'selected': False, 'text': '<pre><code>public string CreatePassword(int length)\n{\n        const string valid = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890";\n        StringBuilder res = new StringBuilder();\n        Random rnd = new Random();\n        while (0 &lt; length--)\n        {\n            res.Append(valid[rnd.Next(valid.Length)]);\n        }\n        return res.ToString();\n}\n</code></pre>\n\n<p>This has a good benefit of being able to choose from a list of available characters for the generated password (e.g. digits only, only uppercase or only lowercase etc.)</p>\n'}, {'answer_id': 55023, 'author': 'Adam Wright', 'author_id': 1200, 'author_profile': 'https://Stackoverflow.com/users/1200', 'pm_score': 3, 'selected': False, 'text': '<p>For this sort of password, I tend to use a system that\'s likely to generate more easily "used" passwords. Short, often made up of pronouncable fragments and a few numbers, and with no intercharacter ambiguity (is that a 0 or an O? A 1 or an I?). Something like</p>\n\n<pre><code>string[] words = { \'bur\', \'ler\', \'meh\', \'ree\' };\nstring word = "";\n\nRandom rnd = new Random();\nfor (i = 0; i &lt; 3; i++)\n   word += words[rnd.Next(words.length)]\n\nint numbCount = rnd.Next(4);\nfor (i = 0; i &lt; numbCount; i++)\n  word += (2 + rnd.Next(7)).ToString();\n\nreturn word;\n</code></pre>\n\n<p>(Typed right into the browser, so use only as guidelines. Also, add more words).</p>\n'}, {'answer_id': 55028, 'author': 'Dale Ragan', 'author_id': 1117, 'author_profile': 'https://Stackoverflow.com/users/1117', 'pm_score': 1, 'selected': False, 'text': '<p>I like to look at generating passwords, just like generating software keys.  You should choose from an array of characters that follow a good practice.  Take what <a href="https://stackoverflow.com/questions/54991/generating-random-passwords#54997">@Radu094 answered</a> with and modify it to follow good practice.  Don\'t put every single letter in the character array.  Some letters are harder to say or understand over the phone.</p>\n\n<p>You should also consider using a checksum on the password that was generated to make sure that it was generated by you.  A good way of accomplishing this is to use the <a href="http://en.wikipedia.org/wiki/Luhn_algorithm" rel="nofollow noreferrer">LUHN algorithm</a>.</p>\n'}, {'answer_id': 55447, 'author': 'Rik', 'author_id': 5409, 'author_profile': 'https://Stackoverflow.com/users/5409', 'pm_score': 10, 'selected': True, 'text': '<p>There\'s always <a href="http://msdn.microsoft.com/en-us/library/system.web.security.membership.generatepassword.aspx" rel="noreferrer"><code>System.Web.Security.Membership.GeneratePassword(int length, int numberOfNonAlphanumericCharacters</code>)</a>.</p>\n'}, {'answer_id': 4757527, 'author': 'Matt Frear', 'author_id': 32598, 'author_profile': 'https://Stackoverflow.com/users/32598', 'pm_score': 3, 'selected': False, 'text': "<p>I don't like the passwords that Membership.GeneratePassword() creates, as they're too ugly and have too many special characters.</p>\n<p>This code generates a 10 digit not-too-ugly password.</p>\n<pre><code>string password = Guid.NewGuid().ToString(&quot;N&quot;).ToLower()\n                      .Replace(&quot;1&quot;, &quot;&quot;).Replace(&quot;o&quot;, &quot;&quot;).Replace(&quot;0&quot;,&quot;&quot;)\n                      .Substring(0,10);\n</code></pre>\n<p>Sure, I could use a Regex to do all the replaces but this is more readable and maintainable IMO.</p>\n"}, {'answer_id': 10600220, 'author': 'Hugo', 'author_id': 1396093, 'author_profile': 'https://Stackoverflow.com/users/1396093', 'pm_score': 2, 'selected': False, 'text': '<p>I created this method similar to the available in the membership provider. This is usefull if you don\'t want to add the web reference in some applications.</p>\n\n<p>It works great.</p>\n\n<pre><code>public static string GeneratePassword(int Length, int NonAlphaNumericChars)\n    {\n        string allowedChars = "abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNOPQRSTUVWXYZ0123456789";\n        string allowedNonAlphaNum = "!@#$%^&amp;*()_-+=[{]};:&lt;&gt;|./?";\n        Random rd = new Random();\n\n        if (NonAlphaNumericChars &gt; Length || Length &lt;= 0 || NonAlphaNumericChars &lt; 0)\n            throw new ArgumentOutOfRangeException();\n\n            char[] pass = new char[Length];\n            int[] pos = new int[Length];\n            int i = 0, j = 0, temp = 0;\n            bool flag = false;\n\n            //Random the position values of the pos array for the string Pass\n            while (i &lt; Length - 1)\n            {\n                j = 0;\n                flag = false;\n                temp = rd.Next(0, Length);\n                for (j = 0; j &lt; Length; j++)\n                    if (temp == pos[j])\n                    {\n                        flag = true;\n                        j = Length;\n                    }\n\n                if (!flag)\n                {\n                    pos[i] = temp;\n                    i++;\n                }\n            }\n\n            //Random the AlphaNumericChars\n            for (i = 0; i &lt; Length - NonAlphaNumericChars; i++)\n                pass[i] = allowedChars[rd.Next(0, allowedChars.Length)];\n\n            //Random the NonAlphaNumericChars\n            for (i = Length - NonAlphaNumericChars; i &lt; Length; i++)\n                pass[i] = allowedNonAlphaNum[rd.Next(0, allowedNonAlphaNum.Length)];\n\n            //Set the sorted array values by the pos array for the rigth posistion\n            char[] sorted = new char[Length];\n            for (i = 0; i &lt; Length; i++)\n                sorted[i] = pass[pos[i]];\n\n            string Pass = new String(sorted);\n\n            return Pass;\n    }\n</code></pre>\n'}, {'answer_id': 14287335, 'author': 'Troy Alford', 'author_id': 1454806, 'author_profile': 'https://Stackoverflow.com/users/1454806', 'pm_score': 3, 'selected': False, 'text': '<p>I know that this is an old thread, but I have what might be a fairly simple solution for someone to use. Easy to implement, easy to understand, and easy to validate.</p>\n\n<p>Consider the following requirement:</p>\n\n<blockquote>\n  <p>I need a random password to be generated which has at least 2 lower-case letters, 2 upper-case letters and 2 numbers. The password must also be a minimum of 8 characters in length.</p>\n</blockquote>\n\n<p>The following regular expression can validate this case:</p>\n\n<pre><code>^(?=\\b\\w*[a-z].*[a-z]\\w*\\b)(?=\\b\\w*[A-Z].*[A-Z]\\w*\\b)(?=\\b\\w*[0-9].*[0-9]\\w*\\b)[a-zA-Z0-9]{8,}$\n</code></pre>\n\n<p>It\'s outside the scope of this question - but the regex is based on <a href="http://www.regular-expressions.info/lookaround.html">lookahead/lookbehind</a> and <a href="http://www.regular-expressions.info/lookaround.html">lookaround</a>.</p>\n\n<p>The following code will create a random set of characters which match this requirement:</p>\n\n<pre><code>public static string GeneratePassword(int lowercase, int uppercase, int numerics) {\n    string lowers = "abcdefghijklmnopqrstuvwxyz";\n    string uppers = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";\n    string number = "0123456789";\n\n    Random random = new Random();\n\n    string generated = "!";\n    for (int i = 1; i &lt;= lowercase; i++)\n        generated = generated.Insert(\n            random.Next(generated.Length), \n            lowers[random.Next(lowers.Length - 1)].ToString()\n        );\n\n    for (int i = 1; i &lt;= uppercase; i++)\n        generated = generated.Insert(\n            random.Next(generated.Length), \n            uppers[random.Next(uppers.Length - 1)].ToString()\n        );\n\n    for (int i = 1; i &lt;= numerics; i++)\n        generated = generated.Insert(\n            random.Next(generated.Length), \n            number[random.Next(number.Length - 1)].ToString()\n        );\n\n    return generated.Replace("!", string.Empty);\n\n}\n</code></pre>\n\n<p>To meet the above requirement, simply call the following:</p>\n\n<pre><code>String randomPassword = GeneratePassword(3, 3, 3);\n</code></pre>\n\n<p>The code starts with an invalid character (<code>"!"</code>) - so that the string has a length into which new characters can be injected.</p>\n\n<p>It then loops from 1 to the # of lowercase characters required, and on each iteration, grabs a random item from the lowercase list, and injects it at a random location in the string.</p>\n\n<p>It then repeats the loop for uppercase letters and for numerics.</p>\n\n<p>This gives you back strings of length = <code>lowercase + uppercase + numerics</code> into which lowercase, uppercase and numeric characters of the count you want have been placed in a random order.</p>\n'}, {'answer_id': 19067818, 'author': 'Joe', 'author_id': 2724942, 'author_profile': 'https://Stackoverflow.com/users/2724942', 'pm_score': -1, 'selected': False, 'text': '<p>Insert a Timer: timer1, 2 buttons: button1, button2, 1 textBox: textBox1, and a comboBox: comboBox1. Make sure you declare:</p>\n\n<pre><code>int count = 0;\n</code></pre>\n\n<hr>\n\n<p>Source Code:</p>\n\n<pre><code> private void button1_Click(object sender, EventArgs e)\n    {\n    // This clears the textBox, resets the count, and starts the timer\n        count = 0;\n        textBox1.Clear();\n        timer1.Start();\n    }\n\n    private void timer1_Tick(object sender, EventArgs e)\n    {\n    // This generates the password, and types it in the textBox\n        count += 1;\n            string possible = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890";\n            string psw = "";\n            Random rnd = new Random { };\n            psw += possible[rnd.Next(possible.Length)];\n            textBox1.Text += psw;\n            if (count == (comboBox1.SelectedIndex + 1))\n            {\n                timer1.Stop();\n            }\n    }\n    private void Form1_Load(object sender, EventArgs e)\n    {\n        // This adds password lengths to the comboBox to choose from.\n        comboBox1.Items.Add("1");\n        comboBox1.Items.Add("2");\n        comboBox1.Items.Add("3");\n        comboBox1.Items.Add("4");\n        comboBox1.Items.Add("5");\n        comboBox1.Items.Add("6");\n        comboBox1.Items.Add("7");\n        comboBox1.Items.Add("8");\n        comboBox1.Items.Add("9");\n        comboBox1.Items.Add("10");\n        comboBox1.Items.Add("11");\n        comboBox1.Items.Add("12");\n    }\n    private void button2_click(object sender, EventArgs e)\n    {\n        // This encrypts the password\n        tochar = textBox1.Text;\n        textBox1.Clear();\n        char[] carray = tochar.ToCharArray();\n        for (int i = 0; i &lt; carray.Length; i++)\n        {\n            int num = Convert.ToInt32(carray[i]) + 10;\n            string cvrt = Convert.ToChar(num).ToString();\n            textBox1.Text += cvrt;\n        }\n    }\n</code></pre>\n'}, {'answer_id': 19068116, 'author': 'CodesInChaos', 'author_id': 445517, 'author_profile': 'https://Stackoverflow.com/users/445517', 'pm_score': 6, 'selected': False, 'text': '<p>The main goals of my code are:</p>\n\n<ol>\n<li>The distribution of strings is almost uniform (don\'t care about minor deviations, as long as they\'re small)</li>\n<li>It outputs more than a few billion strings for each argument set. Generating an 8 character string (~47 bits of entropy) is meaningless if your PRNG only generates 2 billion (31 bits of entropy) different values.</li>\n<li>It\'s secure, since I expect people to use this for passwords or other security tokens.</li>\n</ol>\n\n<p>The first property is achieved by taking a 64 bit value modulo the alphabet size. For small alphabets (such as the 62 characters from the question) this leads to negligible bias. The second and third property are achieved by using <a href="http://msdn.microsoft.com/en-us/library/system.security.cryptography.rngcryptoserviceprovider.aspx" rel="noreferrer"><code>RNGCryptoServiceProvider</code></a> instead of <a href="http://msdn.microsoft.com/en-us/library/system.random.aspx" rel="noreferrer"><code>System.Random</code></a>.</p>\n\n<pre><code>using System;\nusing System.Security.Cryptography;\n\npublic static string GetRandomAlphanumericString(int length)\n{\n    const string alphanumericCharacters =\n        "ABCDEFGHIJKLMNOPQRSTUVWXYZ" +\n        "abcdefghijklmnopqrstuvwxyz" +\n        "0123456789";\n    return GetRandomString(length, alphanumericCharacters);\n}\n\npublic static string GetRandomString(int length, IEnumerable&lt;char&gt; characterSet)\n{\n    if (length &lt; 0)\n        throw new ArgumentException("length must not be negative", "length");\n    if (length &gt; int.MaxValue / 8) // 250 million chars ought to be enough for anybody\n        throw new ArgumentException("length is too big", "length");\n    if (characterSet == null)\n        throw new ArgumentNullException("characterSet");\n    var characterArray = characterSet.Distinct().ToArray();\n    if (characterArray.Length == 0)\n        throw new ArgumentException("characterSet must not be empty", "characterSet");\n\n    var bytes = new byte[length * 8];\n    new RNGCryptoServiceProvider().GetBytes(bytes);\n    var result = new char[length];\n    for (int i = 0; i &lt; length; i++)\n    {\n        ulong value = BitConverter.ToUInt64(bytes, i * 8);\n        result[i] = characterArray[value % (uint)characterArray.Length];\n    }\n    return new string(result);\n}\n</code></pre>\n\n<p><em>(This is a copy of my answer to <a href="https://stackoverflow.com/questions/1344221/how-can-i-generate-random-8-character-alphanumeric-strings-in-c/13416143#13416143">How can I generate random 8 character, alphanumeric strings in C#?</a>)</em></p>\n'}, {'answer_id': 19613574, 'author': 'user1058637', 'author_id': 1058637, 'author_profile': 'https://Stackoverflow.com/users/1058637', 'pm_score': -1, 'selected': False, 'text': '<p>This is short and it works great for me.</p>\n\n<pre><code>public static string GenerateRandomCode(int length)\n{\n    Random rdm = new Random();\n    StringBuilder sb = new StringBuilder();\n\n    for(int i = 0; i &lt; length; i++)\n        sb.Append(Convert.ToChar(rdm.Next(101,132)));\n\n    return sb.ToString();\n}\n</code></pre>\n'}, {'answer_id': 23973810, 'author': 'Alex Siepman', 'author_id': 1333374, 'author_profile': 'https://Stackoverflow.com/users/1333374', 'pm_score': 3, 'selected': False, 'text': '<p>I created <a href="https://www.siepman.nl/blog/random-password-generator-with-numbers-and-special-characters" rel="nofollow noreferrer">this class</a> that uses RNGCryptoServiceProvider and it is flexible. Example:</p>\n\n<pre><code>var generator = new PasswordGenerator(minimumLengthPassword: 8,\n                                      maximumLengthPassword: 15,\n                                      minimumUpperCaseChars: 2,\n                                      minimumNumericChars: 3,\n                                      minimumSpecialChars: 2);\nstring password = generator.Generate();\n</code></pre>\n'}, {'answer_id': 24711536, 'author': 'anaximander', 'author_id': 1448943, 'author_profile': 'https://Stackoverflow.com/users/1448943', 'pm_score': 5, 'selected': False, 'text': '<pre><code>public string GenerateToken(int length)\n{\n    using (RNGCryptoServiceProvider cryptRNG = new RNGCryptoServiceProvider())\n    {\n        byte[] tokenBuffer = new byte[length];\n        cryptRNG.GetBytes(tokenBuffer);\n        return Convert.ToBase64String(tokenBuffer);\n    }\n}\n</code></pre>\n\n<p><em>(You could also have the class where this method lives implement IDisposable, hold a reference to the <code>RNGCryptoServiceProvider</code>, and dispose of it properly, to avoid repeatedly instantiating it.)</em></p>\n\n<p>It\'s been noted that as this returns a base-64 string, the output length is always a multiple of 4, with the extra space using <code>=</code> as a padding character. The <code>length</code> parameter specifies the length of the byte buffer, not the output string (and is therefore perhaps not the best name for that parameter, now I think about it). This controls how many bytes of <a href="http://en.wikipedia.org/wiki/Password_strength#Entropy_as_a_measure_of_password_strength" rel="noreferrer">entropy</a> the password will have. However, because base-64 uses a 4-character block to encode each 3 bytes of input, if you ask for a length that\'s not a multiple of 3, there will be some extra "space", and it\'ll use <code>=</code> to fill the extra.</p>\n\n<p>If you don\'t like using base-64 strings for any reason, you can replace the <code>Convert.ToBase64String()</code> call with either a conversion to regular string, or with any of the <code>Encoding</code> methods; eg. <code>Encoding.UTF8.GetString(tokenBuffer)</code> - just make sure you pick a character set that can represent the full range of values coming out of the RNG, and that produces characters that are compatible with wherever you\'re sending or storing this. Using Unicode, for example, tends to give a lot of Chinese characters. Using base-64 guarantees a widely-compatible set of characters, and the characteristics of such a string shouldn\'t make it any less secure as long as you use a decent hashing algorithm.</p>\n'}, {'answer_id': 29334830, 'author': 'GRUNGER', 'author_id': 4727475, 'author_profile': 'https://Stackoverflow.com/users/4727475', 'pm_score': -1, 'selected': False, 'text': '<p>On my website I use this method:</p>\n\n<pre><code>    //Symb array\n    private const string _SymbolsAll = "~`!@#$%^&amp;*()_+=-\\\\|[{]}\'\\";:/?.&gt;,&lt;";\n\n    //Random symb\n    public string GetSymbol(int Length)\n    {\n        Random Rand = new Random(DateTime.Now.Millisecond);\n        StringBuilder result = new StringBuilder();\n        for (int i = 0; i &lt; Length; i++)\n            result.Append(_SymbolsAll[Rand.Next(0, _SymbolsAll.Length)]);\n        return result.ToString();\n    }\n</code></pre>\n\n<p>Edit string <code>_SymbolsAll</code> for your array list. </p>\n'}, {'answer_id': 30830874, 'author': 'Peter', 'author_id': 328968, 'author_profile': 'https://Stackoverflow.com/users/328968', 'pm_score': 2, 'selected': False, 'text': "<p>I've always been very happy with the password generator built-in to KeePass.  Since KeePass is a .Net program, and open source, I decided to dig around the code a bit.  I ended up just referncing KeePass.exe, the copy provided in the standard application install, as a reference in my project and writing the code below.  You can see how flexible it is thanks to KeePass.  You can specify length, which characters to include/not include, etc...</p>\n\n<pre><code>using KeePassLib.Cryptography.PasswordGenerator;\nusing KeePassLib.Security;\n\n\npublic static string GeneratePassword(int passwordLength, bool lowerCase, bool upperCase, bool digits,\n        bool punctuation, bool brackets, bool specialAscii, bool excludeLookAlike)\n    {\n        var ps = new ProtectedString();\n        var profile = new PwProfile();\n        profile.CharSet = new PwCharSet();\n        profile.CharSet.Clear();\n\n        if (lowerCase)\n            profile.CharSet.AddCharSet('l');\n        if(upperCase)\n            profile.CharSet.AddCharSet('u');\n        if(digits)\n            profile.CharSet.AddCharSet('d');\n        if (punctuation)\n            profile.CharSet.AddCharSet('p');\n        if (brackets)\n            profile.CharSet.AddCharSet('b');\n        if (specialAscii)\n            profile.CharSet.AddCharSet('s');\n\n        profile.ExcludeLookAlike = excludeLookAlike;\n        profile.Length = (uint)passwordLength;\n        profile.NoRepeatingCharacters = true;\n\n        KeePassLib.Cryptography.PasswordGenerator.PwGenerator.Generate(out ps, profile, null, _pool);\n\n        return ps.ReadString();\n    }\n</code></pre>\n"}, {'answer_id': 34060765, 'author': 'Skyler Campbell', 'author_id': 2465875, 'author_profile': 'https://Stackoverflow.com/users/2465875', 'pm_score': -1, 'selected': False, 'text': '<p>Here Is what i put together quickly. </p>\n\n<pre><code>    public string GeneratePassword(int len)\n    {\n        string res = "";\n        Random rnd = new Random();\n        while (res.Length &lt; len) res += (new Func&lt;Random, string&gt;((r) =&gt; {\n            char c = (char)((r.Next(123) * DateTime.Now.Millisecond % 123)); \n            return (Char.IsLetterOrDigit(c)) ? c.ToString() : ""; \n        }))(rnd);\n        return res;\n    }\n</code></pre>\n'}, {'answer_id': 35722429, 'author': 'Ercan ILIK', 'author_id': 5166814, 'author_profile': 'https://Stackoverflow.com/users/5166814', 'pm_score': -1, 'selected': False, 'text': '<pre><code>public string Sifre_Uret(int boy, int noalfa)\n{\n\n    //  01.03.2016   \n    // Genel amaçlı şifre üretme fonksiyonu\n\n\n    //Fonskiyon 128 den büyük olmasına izin vermiyor.\n    if (boy &gt; 128 ) { boy = 128; }\n    if (noalfa &gt; 128) { noalfa = 128; }\n    if (noalfa &gt; boy) { noalfa = boy; }\n\n\n    string passch = System.Web.Security.Membership.GeneratePassword(boy, noalfa);\n\n    //URL encoding ve Url Pass + json sorunu yaratabilecekler pass ediliyor.\n    //Microsoft Garanti etmiyor. Alfa Sayısallar Olabiliyorimiş . !@#$%^&amp;*()_-+=[{]};:&lt;&gt;|./?.\n    //https://msdn.microsoft.com/tr-tr/library/system.web.security.membership.generatepassword(v=vs.110).aspx\n\n\n    //URL ve Json ajax lar için filtreleme\n    passch = passch.Replace(":", "z");\n    passch = passch.Replace(";", "W");\n    passch = passch.Replace("\'", "t");\n    passch = passch.Replace("\\"", "r");\n    passch = passch.Replace("/", "+");\n    passch = passch.Replace("\\\\", "e");\n\n    passch = passch.Replace("?", "9");\n    passch = passch.Replace("&amp;", "8");\n    passch = passch.Replace("#", "D");\n    passch = passch.Replace("%", "u");\n    passch = passch.Replace("=", "4");\n    passch = passch.Replace("~", "1");\n\n    passch = passch.Replace("[", "2");\n    passch = passch.Replace("]", "3");\n    passch = passch.Replace("{", "g");\n    passch = passch.Replace("}", "J");\n\n\n    //passch = passch.Replace("(", "6");\n    //passch = passch.Replace(")", "0");\n    //passch = passch.Replace("|", "p");\n    //passch = passch.Replace("@", "4");\n    //passch = passch.Replace("!", "u");\n    //passch = passch.Replace("$", "Z");\n    //passch = passch.Replace("*", "5");\n    //passch = passch.Replace("_", "a");\n\n    passch = passch.Replace(",", "V");\n    passch = passch.Replace(".", "N");\n    passch = passch.Replace("+", "w");\n    passch = passch.Replace("-", "7");\n\n\n\n\n\n    return passch;\n\n\n\n}\n</code></pre>\n'}, {'answer_id': 41449547, 'author': 'Matt', 'author_id': 2157661, 'author_profile': 'https://Stackoverflow.com/users/2157661', 'pm_score': -1, 'selected': False, 'text': '<p>Added some supplemental code to the accepted answer.  It improves upon answers just using Random and allows for some password options.  I also liked some of the options from the KeePass answer but did not want to include the executable in my solution.</p>\n\n<pre><code>private string RandomPassword(int length, bool includeCharacters, bool includeNumbers, bool includeUppercase, bool includeNonAlphaNumericCharacters, bool includeLookAlikes)\n{\n    if (length &lt; 8 || length &gt; 128) throw new ArgumentOutOfRangeException("length");\n    if (!includeCharacters &amp;&amp; !includeNumbers &amp;&amp; !includeNonAlphaNumericCharacters) throw new ArgumentException("RandomPassword-Key arguments all false, no values would be returned");\n\n    string pw = "";\n    do\n    {\n        pw += System.Web.Security.Membership.GeneratePassword(128, 25);\n        pw = RemoveCharacters(pw, includeCharacters, includeNumbers, includeUppercase, includeNonAlphaNumericCharacters, includeLookAlikes);\n    } while (pw.Length &lt; length);\n\n    return pw.Substring(0, length);\n}\n\nprivate string RemoveCharacters(string passwordString, bool includeCharacters, bool includeNumbers, bool includeUppercase, bool includeNonAlphaNumericCharacters, bool includeLookAlikes)\n{\n    if (!includeCharacters)\n    {\n        var remove = new string[] { "a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z" };\n        foreach (string r in remove)\n        {\n            passwordString = passwordString.Replace(r, string.Empty);\n            passwordString = passwordString.Replace(r.ToUpper(), string.Empty);\n        }\n    }\n\n    if (!includeNumbers)\n    {\n        var remove = new string[] { "0", "1", "2", "3", "4", "5", "6", "7", "8", "9" };\n        foreach (string r in remove)\n            passwordString = passwordString.Replace(r, string.Empty);\n    }\n\n    if (!includeUppercase)\n        passwordString = passwordString.ToLower();\n\n    if (!includeNonAlphaNumericCharacters)\n    {\n        var remove = new string[] { "!", "@", "#", "$", "%", "^", "&amp;", "*", "(", ")", "-", "_", "+", "=", "{", "}", "[", "]", "|", "\\\\", ":", ";", "&lt;", "&gt;", "/", "?", "." };\n        foreach (string r in remove)\n            passwordString = passwordString.Replace(r, string.Empty);\n    }\n\n    if (!includeLookAlikes)\n    {\n        var remove = new string[] { "(", ")", "0", "O", "o", "1", "i", "I", "l", "|", "!", ":", ";" };\n        foreach (string r in remove)\n            passwordString = passwordString.Replace(r, string.Empty);\n    }\n\n    return passwordString;\n}\n</code></pre>\n\n<p>This was the first link when I searched for generating random passwords and the following is out of scope for the current question but might be important to consider.  </p>\n\n<ul>\n<li>Based upon the assumption that <code>System.Web.Security.Membership.GeneratePassword</code> is cryptographically secure with a minimum of 20% of the characters being Non-Alphanumeric.</li>\n<li>Not sure if removing characters and appending strings is considered good practice in this case and provides enough entropy.</li>\n<li>Might want to consider implementing in some way with <a href="https://msdn.microsoft.com/en-us/library/system.security.securestring(v=vs.110).aspx" rel="nofollow noreferrer">SecureString</a> for secure password storage in memory.</li>\n</ul>\n'}, {'answer_id': 46550870, 'author': 'Sean', 'author_id': 6114538, 'author_profile': 'https://Stackoverflow.com/users/6114538', 'pm_score': -1, 'selected': False, 'text': '<p>validChars can be any construct, but I decided to select based on ascii code ranges removing control chars. In this example, it is a 12 character string. </p>\n\n<pre><code>string validChars = String.Join("", Enumerable.Range(33, (126 - 33)).Where(i =&gt; !(new int[] { 34, 38, 39, 44, 60, 62, 96 }).Contains(i)).Select(i =&gt; { return (char)i; }));\nstring.Join("", Enumerable.Range(1, 12).Select(i =&gt; { return validChars[(new Random(Guid.NewGuid().GetHashCode())).Next(0, validChars.Length - 1)]; }))\n</code></pre>\n'}, {'answer_id': 48701757, 'author': 'akshay tilekar', 'author_id': 8152379, 'author_profile': 'https://Stackoverflow.com/users/8152379', 'pm_score': -1, 'selected': False, 'text': '<pre><code> Generate random password of specified length with \n  - Special characters   \n  - Number\n  - Lowecase\n  - Uppercase\n\n  public static string CreatePassword(int length = 12)\n    {\n        const string lower = "abcdefghijklmnopqrstuvwxyz";\n        const string upper = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";\n        const string number = "1234567890";\n        const string special = "!@#$%^&amp;*";\n\n        var middle = length / 2;\n        StringBuilder res = new StringBuilder();\n        Random rnd = new Random();\n        while (0 &lt; length--)\n        {\n            if (middle == length)\n            {\n                res.Append(number[rnd.Next(number.Length)]);\n            }\n            else if (middle - 1 == length)\n            {\n                res.Append(special[rnd.Next(special.Length)]);\n            }\n            else\n            {\n                if (length % 2 == 0)\n                {\n                    res.Append(lower[rnd.Next(lower.Length)]);\n                }\n                else\n                {\n                    res.Append(upper[rnd.Next(upper.Length)]);\n                }\n            }\n        }\n        return res.ToString();\n    }\n</code></pre>\n'}, {'answer_id': 51023300, 'author': 'Saeed Ahmad', 'author_id': 7351330, 'author_profile': 'https://Stackoverflow.com/users/7351330', 'pm_score': 0, 'selected': False, 'text': '<pre><code>public static string GeneratePassword(int passLength) {\n        var chars = "abcdefghijklmnopqrstuvwxyz@#$&amp;ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";\n        var random = new Random();\n        var result = new string(\n            Enumerable.Repeat(chars, passLength)\n                      .Select(s =&gt; s[random.Next(s.Length)])\n                      .ToArray());\n        return result;\n    }\n</code></pre>\n'}, {'answer_id': 55130798, 'author': 'kitsu.eb', 'author_id': 770443, 'author_profile': 'https://Stackoverflow.com/users/770443', 'pm_score': 3, 'selected': False, 'text': '<p>I\'ll add another ill-advised answer to the pot.</p>\n\n<p>I have a use case where I need random passwords for machine-machine communication, so I don\'t have any requirement for human readability. I also don\'t have access to <code>Membership.GeneratePassword</code> in my project, and don\'t want to add the dependency.</p>\n\n<p>I am fairly certain <code>Membership.GeneratePassword</code> is doing something similar to this, but here you can tune the pools of characters to draw from.</p>\n\n<pre><code>public static class PasswordGenerator\n{\n    private readonly static Random _rand = new Random();\n\n    public static string Generate(int length = 24)\n    {\n        const string lower = "abcdefghijklmnopqrstuvwxyz";\n        const string upper = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";\n        const string number = "1234567890";\n        const string special = "!@#$%^&amp;*_-=+";\n\n        // Get cryptographically random sequence of bytes\n        var bytes = new byte[length];\n        new RNGCryptoServiceProvider().GetBytes(bytes);\n\n        // Build up a string using random bytes and character classes\n        var res = new StringBuilder();\n        foreach(byte b in bytes)\n        {\n            // Randomly select a character class for each byte\n            switch (_rand.Next(4))\n            {\n                // In each case use mod to project byte b to the correct range\n                case 0:\n                    res.Append(lower[b % lower.Count()]);\n                    break;\n                case 1:\n                    res.Append(upper[b % upper.Count()]);\n                    break;\n                case 2:\n                    res.Append(number[b % number.Count()]);\n                    break;\n                case 3:\n                    res.Append(special[b % special.Count()]);\n                    break;\n            }\n        }\n        return res.ToString();\n    }\n}\n</code></pre>\n\n<p>And some example output:</p>\n\n<pre><code>PasswordGenerator.Generate(12)\n"pzY=64@-ChS$"\n"BG0OsyLbYnI_"\n"l9#5^2&amp;adj_i"\n"#++Ws9d$%O%X"\n"IWhdIN-#&amp;O^s"\n</code></pre>\n\n<p>To preempt complaints about the use of <code>Random</code>: The primary source of randomness is still the crypto RNG. Even if you could deterministically preordain the sequence coming out of <code>Random</code> (say it only produced <code>1</code>) you still wouldn\'t know the next char that would be picked (though that <em>would</em> limit the range of possibilities).</p>\n\n<p>One simple extension would be to add weighting to the different character sets, which could be as simple as upping the max value and adding fall-through cases to increase weight.</p>\n\n<pre><code>switch (_rand.Next(6))\n{\n    // Prefer letters 2:1\n    case 0:\n    case 1:\n        res.Append(lower[b % lower.Count()]);\n        break;\n    case 2:\n    case 3:\n        res.Append(upper[b % upper.Count()]);\n        break;\n    case 4:\n        res.Append(number[b % number.Count()]);\n        break;\n    case 5:\n        res.Append(special[b % special.Count()]);\n        break;\n}\n</code></pre>\n\n<p>For a more humanistic random password generator I once implemented a prompt system using <a href="https://www.eff.org/deeplinks/2016/07/new-wordlists-random-passphrases" rel="noreferrer">the EFF dice-word list</a>.</p>\n'}, {'answer_id': 57331316, 'author': 'Roohi Ali', 'author_id': 3706939, 'author_profile': 'https://Stackoverflow.com/users/3706939', 'pm_score': -1, 'selected': False, 'text': '<p>I use this code for generate password with balance composition of alphabet, numeric and non_alpha_numeric chars.   </p>\n\n<pre><code>public static string GeneratePassword(int Length, int NonAlphaNumericChars)\n    {\n        string allowedChars = "abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNOPQRSTUVWXYZ0123456789";\n        string allowedNonAlphaNum = "!@#$%^&amp;*()_-+=[{]};:&lt;&gt;|./?";\n        string pass = "";\n        Random rd = new Random(DateTime.Now.Millisecond);\n        for (int i = 0; i &lt; Length; i++)\n        {\n            if (rd.Next(1) &gt; 0 &amp;&amp; NonAlphaNumericChars &gt; 0)\n            {\n                pass += allowedNonAlphaNum[rd.Next(allowedNonAlphaNum.Length)];\n                NonAlphaNumericChars--;\n            }\n            else\n            {\n                pass += allowedChars[rd.Next(allowedChars.Length)];\n            }\n        }\n        return pass;\n    }\n</code></pre>\n'}, {'answer_id': 59933028, 'author': 'Johan Maes', 'author_id': 9266796, 'author_profile': 'https://Stackoverflow.com/users/9266796', 'pm_score': 0, 'selected': False, 'text': '<p>This package allows you to generate a random password while fluently indicating which characters it should contain (if needed):</p>\n\n<p><a href="https://github.com/prjseal/PasswordGenerator/" rel="nofollow noreferrer">https://github.com/prjseal/PasswordGenerator/</a></p>\n\n<p>Example:</p>\n\n<pre><code>var pwd = new Password().IncludeLowercase().IncludeUppercase().IncludeSpecial();\nvar password = pwd.Next();\n</code></pre>\n'}, {'answer_id': 60382377, 'author': 'samgak', 'author_id': 696391, 'author_profile': 'https://Stackoverflow.com/users/696391', 'pm_score': 0, 'selected': False, 'text': '<p>If you want to make use of the cryptographically secure random number generation used by System.Web.Security.Membership.GeneratePassword but also want to restrict the character set to alphanumeric characters, you can filter the result with a regex:</p>\n\n<pre><code>static string GeneratePassword(int characterCount)\n{\n    string password = String.Empty;\n    while(password.Length &lt; characterCount)\n        password += Regex.Replace(System.Web.Security.Membership.GeneratePassword(128, 0), "[^a-zA-Z0-9]", string.Empty);\n    return password.Substring(0, characterCount);\n}\n</code></pre>\n'}, {'answer_id': 66334368, 'author': 'RD07 Dz', 'author_id': 13557184, 'author_profile': 'https://Stackoverflow.com/users/13557184', 'pm_score': 0, 'selected': False, 'text': '<p>check this code...\nI added the .remove(length) to improve <a href="https://stackoverflow.com/users/1448943/anaximander">anaximander</a>\'s response</p>\n<pre><code>            public string GeneratePassword(int length)\n            {\n                using(RNGCryptoServiceProvider cryptRNG = new RNGCryptoServiceProvider();)\n               {\n                      byte[] tokenBuffer = new byte[length];\n                      cryptRNG.GetBytes(tokenBuffer);\n                      return Convert.ToBase64String(tokenBuffer).Remove(length);\n                }\n                          \n            }\n</code></pre>\n'}, {'answer_id': 67102548, 'author': 'Vijay Kumavat', 'author_id': 12376492, 'author_profile': 'https://Stackoverflow.com/users/12376492', 'pm_score': 0, 'selected': False, 'text': '<p>How to Generate the Random Password in C#.<br />\nOutput : (<a href="https://prnt.sc/11fac8v" rel="nofollow noreferrer">https://prnt.sc/11fac8v</a>)<br />\nRun : <a href="https://onlinegdb.com/HJe5OHBLu" rel="nofollow noreferrer">https://onlinegdb.com/HJe5OHBLu</a></p>\n<pre><code>    private static Random random = new Random();\n    public static void Main()\n    {\n        Console.WriteLine(&quot;Random password with length of 8 character.&quot;);\n        Console.WriteLine(&quot;===========================================&quot;);\n        Console.WriteLine(&quot;Capital latters : 2&quot;);\n        Console.WriteLine(&quot;Number latters : 2&quot;);\n        Console.WriteLine(&quot;Special latters : 2&quot;);\n        Console.WriteLine(&quot;Small latters : 2&quot;);\n        Console.WriteLine(&quot;===========================================&quot;);\n        Console.Write(&quot;The Random Password : &quot;);\n        Console.WriteLine(RandomStringCap(2) + RandomStringNum(2) + RandomStringSpe(2) + RandomStringSml(2));\n        Console.WriteLine(&quot;===========================================&quot;);\n    }\n    public static string RandomStringCap(int length)\n    {\n        const string chars = &quot;ABCDEFGHIJKLMNOPQRSTUVWXYZ&quot;;\n        return new string(Enumerable.Repeat(chars, length)\n                         .Select(s =&gt; s[random.Next(s.Length)]).ToArray());\n    }\n    public static string RandomStringNum(int length)\n    {\n        const string chars = &quot;0123456789&quot;;\n        return new string(Enumerable.Repeat(chars, length)\n                         .Select(s =&gt; s[random.Next(s.Length)]).ToArray());\n    }\n    public static string RandomStringSml(int length)\n    {\n        const string chars = &quot;abcdefghijklmnopqrstuvwxyz&quot;;\n        return new string(Enumerable.Repeat(chars, length)\n                         .Select(s =&gt; s[random.Next(s.Length)]).ToArray());\n    }\n    public static string RandomStringSpe(int length)\n    {\n        const string chars = &quot;!@#$%^&amp;*_-=+&quot;;\n        return new string(Enumerable.Repeat(chars, length)\n                         .Select(s =&gt; s[random.Next(s.Length)]).ToArray());\n    }\n</code></pre>\n'}, {'answer_id': 73316960, 'author': 'Shane', 'author_id': 5564257, 'author_profile': 'https://Stackoverflow.com/users/5564257', 'pm_score': 0, 'selected': False, 'text': "<p>Inspired by the answer from @kitsu.eb, but using <code>RandomNumberGenerator</code> instead of <code>Random</code> or <code>RNGCryptoServiceProvider</code> (deprecated in .NET 6), and added a few more special characters.</p>\n<p>Optional parameter to exclude characters that will be escaped when using <code>System.Text.Json.JsonSerializer.Serialize</code> - for example <code>&amp;</code> which is escaped as <code>\\u0026</code> - so that you can guarantee the length of the serialized string will match the length of the password.</p>\n<p>For .NET Core 3.0 and above.</p>\n<pre><code>public static class PasswordGenerator\n{\n    const string lower = &quot;abcdefghijklmnopqrstuvwxyz&quot;;\n    const string upper = &quot;ABCDEFGHIJKLMNOPQRSTUVWXYZ&quot;;\n    const string number = &quot;1234567890&quot;;\n    const string special = &quot;!@#$%^&amp;*()[]{},.:`~_-=+&quot;; // excludes problematic characters like ;'&quot;/\\\n    const string specialJsonSafe = &quot;!@#$%^*()[]{},.:~_-=&quot;; // excludes problematic characters like ;'&quot;/\\ and &amp;`+\n\n    const int lowerLength = 26; // lower.Length\n    const int upperLength = 26; // upper.Length;\n    const int numberLength = 10; // number.Length;\n    const int specialLength = 23; // special.Length;\n    const int specialJsonSafeLength = 20; // specialJsonSafe.Length;\n\n    public static string Generate(int length = 96, bool jsonSafeSpecialCharactersOnly = false)\n    {\n        Span&lt;char&gt; result = length &lt; 1024 ? stackalloc char[length] : new char[length].AsSpan();\n\n        for (int i = 0; i &lt; length; ++i)\n        {\n            switch (RandomNumberGenerator.GetInt32(4))\n            {\n                case 0:\n                    result[i] = lower[RandomNumberGenerator.GetInt32(0, lowerLength)];\n                    break;\n                case 1:\n                    result[i] = upper[RandomNumberGenerator.GetInt32(0, upperLength)];\n                    break;\n                case 2:\n                    result[i] = number[RandomNumberGenerator.GetInt32(0, numberLength)];\n                    break;\n                case 3:\n                    if (jsonSafeSpecialCharactersOnly)\n                    {\n                        result[i] = specialJsonSafe[RandomNumberGenerator.GetInt32(0, specialJsonSafeLength)];\n                    }\n                    else\n                    {\n                        result[i] = special[RandomNumberGenerator.GetInt32(0, specialLength)];\n                    }\n                    break;\n            }\n        }\n\n        return result.ToString();\n    }\n}\n</code></pre>\n"}, {'answer_id': 73913189, 'author': 'clamchoda', 'author_id': 591285, 'author_profile': 'https://Stackoverflow.com/users/591285', 'pm_score': 0, 'selected': False, 'text': "<p>Pretty easy way to require one from each group using <code>Random</code> and linq-to-objects.</p>\n<ul>\n<li>Randomize each group</li>\n<li>Select random amount from first group</li>\n<li>Select remaining random amounts from following groups</li>\n</ul>\n<p>\xa0</p>\n<pre><code>Random rand = new Random();\nint min = 8;\nint max = 16;\nint totalLen = rand.Next(min, max);\nint remainingGroups = 4;\n                \nstring[] allowedLowerChars = &quot;a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t,u,v,w,x,y,z&quot;.Split(',');           \nstring [] allowedUpperChars = &quot;A,B,C,D,E,F,G,H,I,J,K,L,M,N,O,P,Q,R,S,T,U,V,W,X,Y,Z&quot;.Split(',');\nstring [] allowedNumbers = &quot;1,2,3,4,5,6,7,8,9,0&quot;.Split(',');\nstring [] allowedSpecialChars = &quot;!,@,#,$,%,&amp;,?&quot;.Split(',');\n\n\nvar password = allowedLowerChars.OrderBy(c =&gt; rand.Next()).Take(rand.Next(1, totalLen-remainingGroups--)).ToList();\npassword.AddRange(allowedUpperChars.OrderBy(c =&gt; rand.Next()).Take(rand.Next(1, totalLen-password.Count-remainingGroups--)).ToList());\npassword.AddRange(allowedNumbers.OrderBy(c =&gt; rand.Next()).Take(rand.Next(1, totalLen-password.Count-remainingGroups--)).ToList());\npassword.AddRange(allowedSpecialChars.OrderBy(c =&gt; rand.Next()).Take(totalLen-password.Count).ToList());\npassword = password.OrderBy(c =&gt; rand.Next()).ToList(); // randomize groups\n</code></pre>\n"}]
['https://Stackoverflow.com/questions/54991', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/231/']