开发者

Code for password generator

I'm working on a C# project where I need to generate random passwords.

Can anyone provide some code or a high-level approach for password generation?

It should be possible to specify the following:

  1. Minimum password length
  2. Maximum password len开发者_运维问答gth
  3. Valid uppercase characters
  4. Minimum number of uppercase chars
  5. Valid lowercase chars
  6. Minimum number of lowercase chars
  7. Valid numeric chars
  8. Minimum number of numeric chars
  9. Valid alfanum chars.
  10. Minimum number of alfanum chars


you can use this method and modify according to your need

private static string CreateRandomPassword(int passwordLength)
{
 string allowedChars = "abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNOPQRSTUVWXYZ0123456789!@$?_-";
 char[] chars = new char[passwordLength];
 Random rd = new Random();

 for (int i = 0; i < passwordLength; i++)
 {
  chars[i] = allowedChars[rd.Next(0, allowedChars.Length)];
 }

 return new string(chars);
}


I wrote a simple Data generation library ages ago to mock up some data we needed, you could take a look at that to get some ideas. You provide it with a pattern which you want to generate and it will create random data to match that pattern.

The pattern is as follows:

  • * - An upper-case or lower-case letter or number.
  • L - An upper-case Letter.
  • l - A lower-case letter.
  • V - An upper-case Vowel.
  • v - A lower-case vowel.
  • C - An upper-case Consonant.
  • c - A lower-case consonant.
  • X - Any number, 0-9.
  • x - Any number, 1-9.

Its not exactly what you are looking for but you should be able to modify it to suit your needs.

This is the main logic
EDIT: Reading through your requirements again I think you should be able to alter my code to get it to work. You would need to create a pattern that matches the minimum character/number requirements for a valid password, add logic to vary the length of the generated password by adding in random characters, and perhaps add some random sort logic at the end to mix the characters up so that they are not always in the same pattern.

EDIT(2): Moved the code to GitHub, updated links.

EDIT(3): Linked to main Github repo instead.


Have you had a look at the codeproject example?

http://www.codeproject.com/KB/cs/pwdgen.aspx


A C# Password Generator

namespace WorkingCode.CodeProject.PwdGen
{
    using System;
    using System.Security.Cryptography;
    using System.Text;

    public class PasswordGenerator
    {
        public PasswordGenerator() 
        {
            this.Minimum               = DefaultMinimum;
            this.Maximum               = DefaultMaximum;
            this.ConsecutiveCharacters = false;
            this.RepeatCharacters      = true;
            this.ExcludeSymbols        = false;
            this.Exclusions            = null;

            rng = new RNGCryptoServiceProvider();
        }       

        protected int GetCryptographicRandomNumber(int lBound, int uBound)
        {   
            // Assumes lBound >= 0 && lBound < uBound

            // returns an int >= lBound and < uBound

            uint urndnum;   
            byte[] rndnum = new Byte[4];   
            if (lBound == uBound-1)  
            {
                // test for degenerate case where only lBound can be returned

                return lBound;
            }

            uint xcludeRndBase = (uint.MaxValue -
                (uint.MaxValue%(uint)(uBound-lBound)));   

            do 
            {      
                rng.GetBytes(rndnum);      
                urndnum = System.BitConverter.ToUInt32(rndnum,0);      
            } while (urndnum >= xcludeRndBase);   

            return (int)(urndnum % (uBound-lBound)) + lBound;
        }

        protected char GetRandomCharacter()
        {            
            int upperBound = pwdCharArray.GetUpperBound(0);

            if ( true == this.ExcludeSymbols )
            {
                upperBound = PasswordGenerator.UBoundDigit;
            }

            int randomCharPosition = GetCryptographicRandomNumber(
                pwdCharArray.GetLowerBound(0), upperBound);

            char randomChar = pwdCharArray[randomCharPosition];

            return randomChar;
        }

        public string Generate()
        {
            // Pick random length between minimum and maximum   

            int pwdLength = GetCryptographicRandomNumber(this.Minimum,
                this.Maximum);

            StringBuilder pwdBuffer = new StringBuilder();
            pwdBuffer.Capacity = this.Maximum;

            // Generate random characters

            char lastCharacter, nextCharacter;

            // Initial dummy character flag

            lastCharacter = nextCharacter = '\n';

            for ( int i = 0; i < pwdLength; i++ )
            {
                nextCharacter = GetRandomCharacter();

                if ( false == this.ConsecutiveCharacters )
                {
                    while ( lastCharacter == nextCharacter )
                    {
                        nextCharacter = GetRandomCharacter();
                    }
                }

                if ( false == this.RepeatCharacters )
                {
                    string temp = pwdBuffer.ToString();
                    int duplicateIndex = temp.IndexOf(nextCharacter);
                    while ( -1 != duplicateIndex )
                    {
                        nextCharacter = GetRandomCharacter();
                        duplicateIndex = temp.IndexOf(nextCharacter);
                    }
                }

                if ( ( null != this.Exclusions ) )
                {
                    while ( -1 != this.Exclusions.IndexOf(nextCharacter) )
                    {
                        nextCharacter = GetRandomCharacter();
                    }
                }

                pwdBuffer.Append(nextCharacter);
                lastCharacter = nextCharacter;
            }

            if ( null != pwdBuffer )
            {
                return pwdBuffer.ToString();
            }
            else
            {
                return String.Empty;
            }   
        }

        public string Exclusions
        {
            get { return this.exclusionSet;  }
            set { this.exclusionSet = value; }
        }

        public int Minimum
        {
            get { return this.minSize; }
            set 
            { 
                this.minSize = value;
                if ( PasswordGenerator.DefaultMinimum > this.minSize )
                {
                    this.minSize = PasswordGenerator.DefaultMinimum;
                }
            }
        }

        public int Maximum
        {
            get { return this.maxSize; }
            set 
            { 
                this.maxSize = value;
                if ( this.minSize >= this.maxSize )
                {
                    this.maxSize = PasswordGenerator.DefaultMaximum;
                }
            }
        }

        public bool ExcludeSymbols
        {
            get { return this.hasSymbols; }
            set { this.hasSymbols = value;}
        }

        public bool RepeatCharacters
        {
            get { return this.hasRepeating; }
            set { this.hasRepeating = value;}
        }

        public bool ConsecutiveCharacters
        {
            get { return this.hasConsecutive; }
            set { this.hasConsecutive = value;}
        }

        private const int DefaultMinimum = 6;
        private const int DefaultMaximum = 10;
        private const int UBoundDigit    = 61;

        private RNGCryptoServiceProvider    rng;
        private int             minSize;
        private int             maxSize;
        private bool            hasRepeating;
        private bool            hasConsecutive;
        private bool            hasSymbols;
        private string          exclusionSet;
        private char[] pwdCharArray = "abcdefghijklmnopqrstuvwxyzABCDEFG" +
            "HIJKLMNOPQRSTUVWXYZ0123456789`~!@#$%^&*()-_=+[]{}\\|;:'\",<" + 
            ".>/?".ToCharArray();                                        
    }
}

I found also

http://www.codeproject.com/KB/cs/password-generator.aspx

http://www.codesnipr.com/snippet/504/c-Random-password-generator

http://www.yetanotherchris.me/home/2009/3/15/c-pronounceable-password-generator.html


does this help? you could have found it with google yourself .) C# Password Generator


Took the password generator from code project, cleaned up the code and fixed a logic fault in the Maximum property setter.

 public static class PasswordGenerator
{
    private const int DefaultMinimum = 6;
    private const int DefaultMaximum = 10;
    private const int UBoundDigit = 61;
    private readonly static char[] PwdCharArray = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789`~!@#$%^&*()-_=+[]{}\\|;:'\",./?".ToCharArray();

    private static readonly RNGCryptoServiceProvider _rng = new RNGCryptoServiceProvider();
    private static int _minSize=DefaultMinimum;
    private static int _maxSize=DefaultMaximum;

    public static int Minimum
    {
        get { return _minSize; }
        set
        {
            _minSize = value;
            if (DefaultMinimum > _minSize)
            {
                _minSize = DefaultMinimum;
            }

        }
    }
    public static int Maximum
    {
        get { return _maxSize; }
        set
        {
            _maxSize = value;
            if (_minSize >= _maxSize)
            {
                _maxSize = _minSize + 2;
            }
        }
    }
    public static string Exclusions { get; set; }
    public static bool ExcludeSymbols { get; set; }
    public static bool RepeatCharacters { get; set; }
    public static bool ConsecutiveCharacters { get; set; }



    static PasswordGenerator()
    {
        Minimum = DefaultMinimum;
        Maximum = DefaultMaximum;
        ConsecutiveCharacters = false;
        RepeatCharacters = true;
        ExcludeSymbols = false;
        Exclusions = null;

    }

    private static int GetCryptographicRandomNumber(int lBound, int uBound)
    {
        // Assumes lBound >= 0 && lBound < uBound
        // returns an int >= lBound and < uBound
        uint urndnum;
        var rndnum = new Byte[4];
        if (lBound == uBound - 1)
        {
            // test for degenerate case where only lBound can be returned
            return lBound;
        }

        uint xcludeRndBase = (uint.MaxValue -
            (uint.MaxValue % (uint)(uBound - lBound)));

        do
        {
            _rng.GetBytes(rndnum);
            urndnum = BitConverter.ToUInt32(rndnum, 0);
        } while (urndnum >= xcludeRndBase);

        return (int)(urndnum % (uBound - lBound)) + lBound;
    }

    private static char GetRandomCharacter()
    {
        var upperBound = PwdCharArray.GetUpperBound(0);

        if (ExcludeSymbols)
        {
            upperBound = UBoundDigit;
        }

        int randomCharPosition = GetCryptographicRandomNumber(
            PwdCharArray.GetLowerBound(0), upperBound);

        char randomChar = PwdCharArray[randomCharPosition];

        return randomChar;
    }

    public static string Generate()
    {
        // Pick random length between minimum and maximum   
        var pwdLength = GetCryptographicRandomNumber(Minimum,Maximum);

        var pwdBuffer = new StringBuilder {Capacity = Maximum};

        // Initial dummy character flag
        char lastCharacter  = '\n';

        for (var i = 0; i < pwdLength; i++)
        {
            var nextCharacter = GetRandomCharacter();

            while (nextCharacter == lastCharacter)
            {
                nextCharacter = GetRandomCharacter();
            }

            if (false == RepeatCharacters)
            {
                var temp = pwdBuffer.ToString();
                var duplicateIndex = temp.IndexOf(nextCharacter);
                while (-1 != duplicateIndex)
                {
                    nextCharacter = GetRandomCharacter();
                    duplicateIndex = temp.IndexOf(nextCharacter);
                }
            }

            if ((null != Exclusions))
            {
                while (-1 != Exclusions.IndexOf(nextCharacter))
                {
                    nextCharacter = GetRandomCharacter();
                }
            }

            pwdBuffer.Append(nextCharacter);
            lastCharacter = nextCharacter;
        }

        return pwdBuffer.ToString();
    }
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜