密码生成器的代码

发布于 2024-10-20 18:12:06 字数 271 浏览 2 评论 0原文

我正在开发一个 C# 项目,需要生成随机密码。

任何人都可以提供一些代码或高级密码生成方法吗?

应该可以指定以下内容:

  1. 最小密码长度
  2. 最大密码长度
  3. 有效的大写字符
  4. 大写字符的最小数量
  5. 有效的小写字符
  6. 最小的小写字符数量
  7. 有效的数字字符
  8. 数字字符的最小数量
  9. 有效的阿尔法字符。
  10. 最小阿尔法字符数

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 length
  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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

迎风吟唱 2024-10-27 18:12:06

您可以使用此方法并根据您的需要进行修改

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);
}

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);
}
萌辣 2024-10-27 18:12:06

我很久以前编写了一个简单的数据生成库来模拟我们需要的一些数据,您可以看一下它以获得一些想法。您向它提供要生成的模式,它将创建随机数据来匹配该模式。

模式如下:

  • * - 大写或小写字母或数字。
  • L - 大写字母。
  • l - 小写字母。
  • V - 大写元音。
  • v - 小写元音。
  • C - 大写辅音。
  • c - 小写辅音。
  • X - 任意数字,0-9。
  • x - 任何数字,1-9。

它并不完全是您正在寻找的内容,但您应该能够对其进行修改以满足您的需求。

这是主要逻辑
编辑:再次阅读您的要求,我认为您应该能够更改我的代码以使其正常工作。您需要创建一个匹配有效密码的最小字符/数字要求的模式,添加逻辑以通过添加随机字符来改变生成的密码的长度,并且可能在末尾添加一些随机排序逻辑来混合字符以便它们不总是处于相同的模式。

编辑(2):将代码移至 GitHub,更新了链接。

编辑(3):链接到主 Github 存储库。

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.

初心 2024-10-27 18:12:06

AC# 密码生成器

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();                                        
    }
}

我还发现

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

http://www.codesnipr.com/snippet/504/c-随机密码生成器

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

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

归属感 2024-10-27 18:12:06

从代码项目中取出密码生成器,清理代码并修复最大属性设置器中的逻辑错误。

 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();
    }
}

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();
    }
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文