使用for循环生成密码

kev*_*vin 6 c#

我正在创建一个生成随机数的密码生成器,然后我使用ascii将其转换为一个字母.在for循环中,我需要字母来转换字符串而不是列表.它可以工作,但它只是将随机字母显示为列表.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;

class MainClass
{
    static void Main()
    {
        int x = 1;
        int length;
        string a = "Press any key to continue";
        object num;


        while (x == 1)

        {
            Console.WriteLine("How many Characters would you like the Password to be? (Press -1 to Stop)");
            length = Convert.ToInt32(Console.ReadLine());
            try
            {
                for (int i = 0; i < length; i++)
                {
                    int num1 = Number();
                    Int32 ASCII = num1;
                    num = (char)num1;

                    if (length > 0)
                    {
                        Console.WriteLine(num);
                    }
                }
            }
            catch
            {
                Console.WriteLine(a);
            }

            if (length == -1)
                break;
        }
    }
    static Random _r = new Random();
    static int Number()
    {
        return _r.Next(65, 90); // decimal
    }
}
Run Code Online (Sandbox Code Playgroud)

Tim*_*ora 16

StringBuilder sb = new StringBuilder();

for( int i = 0; i < length; i++ )
{
    int num1 = Number();
    Int32 ASCII = num1;
    num = (char)num1;

    sb.Append( num );
}

Console.WriteLine( sb.ToString() );
Run Code Online (Sandbox Code Playgroud)

这不是我建立密码的方式,也不是我如何生成随机文本,但这会给你一个字符串并回答原始问题.

至于我如何完成这项任务:

System.Security.Cryptography.RNGCryptoServiceProvider _crypto = new System.Security.Cryptography.RNGCryptoServiceProvider();

byte[] bytes = new byte[8]; // this array can be larger if desired
_crypto.GetBytes( bytes );

ulong randomNumber = (ulong)BitConverter.ToInt64( bytes, 0 );

// convert to a string with the encoding of your choice; I prefer Base 62
Run Code Online (Sandbox Code Playgroud)

为了完整起见,这是我使用的Base62算法.Base62比更常用的Base64具有优势,因为它不包含任何特殊字符,因此它易于在查询字符串,HTML和JavaScript中使用(有一些小的警告).当然,不应在任何这些地方使用密码,并且您可能希望包含特殊字符以使密码更复杂.

无论如何,这是我如何将随机数转换为Base62.

private static readonly char[] _base62Characters = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ".ToCharArray();

public static string ToBase62String( long value )
{
    if( value < 0L )
    {
        throw new ArgumentException( "Number must be zero or greater." );
    }

    if( value == 0 )
    {
        return "0";
    }

    string retVal = "";

    while( value > 0 )
    {
        retVal = _base62Characters[value % 62] + retVal;
        value = value / 62;
    }

    return retVal;
}
Run Code Online (Sandbox Code Playgroud)

最后,我想指出,很少会出于任何目的生成密码,因为这意味着它们以某种形式分发.密码应该是哈希和腌制的; 密码重置应依赖于随机,过期的安全令牌,允许用户进行一次性重置.密码不应该通过电子邮件发送给用户; 密码绝不应以明文或任何可逆格式存储.

对于密码重置令牌生成,我提供的代码可以很好地工作,因为它产生一个用Web安全格式编码的大型加密随机数.但在这种情况下,即使是散列的GUID也可以做到.


Oli*_*bes 6

var sb = new StringBuilder();
for (int i = 0; i < length; i++) {
    sb.Append((char)Number());
}
string password = sb.ToString();
Console.WriteLine(password );
Run Code Online (Sandbox Code Playgroud)

但我会将您的Number()方法更改为:

private static char GetRandomChar()
{
    return (char)_r.Next(65, 90);
}
Run Code Online (Sandbox Code Playgroud)

然后替换循环内的行:

sb.Append(GetRandomChar());
Run Code Online (Sandbox Code Playgroud)


Eni*_*ate 2

你可以试试这个

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace PasswordSample
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("Generated password: {0}", GeneratePassword(12, true));
        }

        /// <summary>
        /// Generate a random password
        /// </summary>
        /// <param name="pwdLenght">Password lenght</param>
        /// <param name="nonAlphaNumericChars">Indicates if password will include non alpha-numeric</param>
        /// <returns>Return a password</returns>
        private static String GeneratePassword(int pwdLenght, bool nonAlphaNumericChars)
        {
            // Allowed characters
            String allowedChars = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789abcdefghijklmnopqrstuvwxyz";

            if (nonAlphaNumericChars)
            {
                // Add non-alphanumeric chars
                allowedChars += "-&@#%!*$?_";
            }

            char[] passwordChars = new char[pwdLenght];
            Random rnd = new Random();

            // Generate a random password
            for (int i = 0; i < pwdLenght; i++)
                passwordChars[i] = allowedChars[rnd.Next(0, allowedChars.Length)];

            return new String(passwordChars);
        }
    }
}
Run Code Online (Sandbox Code Playgroud)