Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Generate password using a for loop

Tags:

c#

I am making a password generator that generates a random number, then I have it converted to a letter using ascii. Inside the for loop, I need the letters to convert a string instead of a list. It works, but it just displays random letters as a list.

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
    }
}
like image 504
kevin Avatar asked Dec 15 '11 19:12

kevin


1 Answers

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

This isn't how I would build a password nor how I would generate random text, but this will give you a string and answer the original question.

As to how I would do this task:

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

For completeness sake, here's a Base62 algorithm which I use. Base62 has the advantage over the more commonly-used Base64 in that it does not include any special characters so it is easy to use in query strings, HTML, and JavaScript (with a few minor caveats). Of course, passwords shouldn't be used in any of those places, and you may want to include special characters to make a password more complex.

Regardless, here is how I convert random numbers to 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;
}

Lastly, I want to point out that passwords should very rarely be generated for any purpose, because that means they are being distributed in some form. Passwords should be hashed and salted; password resets should rely on random, expiring security tokens allowing the user a one-time reset. Passwords should never be emailed to a user; passwords should never be stored in plaintext or any reversible format.

For password reset token generation, the code I provided could work nicely because it produces a large, cryptographically random number encoded with a web-safe format. But even a hashed GUID would do the trick in that case.

like image 141
Tim M. Avatar answered Nov 05 '22 06:11

Tim M.