• http://www.techneurons.com/career/
  • experienced programming consultants for hire !!!

    Contact Now

    C#.NET Articles

    KB: Snippet: Generate random strong password string using C#

    TUESDAY, MARCH 23, 2010

    Here is a very useful C# code snippet for generating random strong passwords. There are two code snippets provided here, one for generating a simple random password, and other for generating a strong password. The password is generated using upper case and lower case alphabets, numerals and special characters.

    Simple Random Password:

    This generates a string of random characters, with only one condition - first character is an upper case alphabet. This password generation can be used in cases where you do not want to use a very strong complex password.

    //create constant strings for each type of characters
    static string alphaCaps = "QWERTYUIOPASDFGHJKLZXCVBNM";
    static string alphaLow = "qwertyuiopasdfghjklzxcvbnm";
    static string numerics = "1234567890";
    static string special = "@#$";
    //create another string which is a concatenation of all above
    string allChars = alphaCaps + alphaLow + numerics + special;
     
    public string GeneratePassword(int length)
    {
        Random r = new Random();
        String generatedPassword = "";
        for (int i = 0; i < length; i++)
        {
            double rand = r.NextDouble();
            if (i == 0)
            {
                //First character is an upper case alphabet
                generatedPassword += alphaCaps.ToCharArray()[(int)Math.Floor(rand * alphaCaps.Length)];
            }
            else
            {
                generatedPassword += allChars.ToCharArray()[(int)Math.Floor(rand * allChars.Length)];
            }
        }
        return generatedPassword;
    }

    Strong Password Generation:

    The strong password generation ensures the presence of upper case, lower case, numeric and special characters in the password. Because of the above condition, it throws an exception when you try to generate password with length less than 4 characters.

    //create constant strings for each type of characters
    static string alphaCaps = "QWERTYUIOPASDFGHJKLZXCVBNM";
    static string alphaLow = "qwertyuiopasdfghjklzxcvbnm";
    static string numerics = "1234567890";
    static string special = "@#$";
    //create another string which is a concatenation of all above
    string allChars = alphaCaps + alphaLow + numerics + special;
    Random r = new Random(); 
     
    public string GenerateStrongPassword(int length)
    {
        String generatedPassword = "";
     
        if (length < 4)
            throw new Exception("Number of characters should be greater than 4.");
     
        // Generate four repeating random numbers are postions of lower,
        // upper, numeric and special characters
        // By filling these positions with corresponding characters,
        // we can ensure the password has atleast one
        // character of those types
        int pLower, pUpper, pNumber, pSpecial;
        string posArray = "0123456789";
        if (length < posArray.Length)
            posArray = posArray.Substring(0, length);
        string randomChar = posArray.ToCharArray()[(int)Math.Floor(r.NextDouble() * posArray.Length)].ToString();
        pLower = int.Parse(randomChar); posArray = posArray.Replace(randomChar, "");
        randomChar = posArray.ToCharArray()[(int)Math.Floor(r.NextDouble() * posArray.Length)].ToString();
        pUpper = int.Parse(randomChar); posArray = posArray.Replace(randomChar, "");
        randomChar = posArray.ToCharArray()[(int)Math.Floor(r.NextDouble() * posArray.Length)].ToString();
        pNumber = int.Parse(randomChar); posArray = posArray.Replace(randomChar, "");
        randomChar = posArray.ToCharArray()[(int)Math.Floor(r.NextDouble() * posArray.Length)].ToString();
        pSpecial = int.Parse(randomChar); posArray = posArray.Replace(randomChar, "");
     
     
        for (int i = 0; i < length; i++)
        {
            double rand = r.NextDouble();
            if (i == pLower)
                generatedPassword += alphaCaps.ToCharArray()[(int)Math.Floor(rand * alphaCaps.Length)];
            else if (i == pUpper)
                generatedPassword += alphaLow.ToCharArray()[(int)Math.Floor(rand * alphaLow.Length)];
            else if (i == pNumber)
                generatedPassword += numerics.ToCharArray()[(int)Math.Floor(rand * numerics.Length)];
            else if (i == pSpecial)
                generatedPassword += special.ToCharArray()[(int)Math.Floor(rand * special.Length)];
            else
                generatedPassword += allChars.ToCharArray()[(int)Math.Floor(rand * allChars.Length)];
        }
        return generatedPassword;
    }

    Strong Password Generation (Optimized Code):

     
    //create constant strings for each type of characters
    static string alphaCaps = "QWERTYUIOPASDFGHJKLZXCVBNM";
    static string alphaLow = "qwertyuiopasdfghjklzxcvbnm";
    static string numerics = "1234567890";
    static string special = "@#$";
    //create another string which is a concatenation of all above
    string allChars = alphaCaps + alphaLow + numerics + special;
    Random r = new Random();
     
    public string GenerateStrongPassword(int length)
    {
        String generatedPassword = "";
     
        if (length < 4)
            throw new Exception("Number of characters should be greater than 4.");
     
        // Generate four repeating random numbers are postions of
        // lower, upper, numeric and special characters
        // By filling these positions with corresponding characters,
        // we can ensure the password has atleast one
        // character of those types
        int pLower, pUpper, pNumber, pSpecial;
        string posArray = "0123456789";
        if (length < posArray.Length)
            posArray = posArray.Substring(0, length);
        pLower = getRandomPosition(ref posArray);
        pUpper = getRandomPosition(ref posArray);
        pNumber = getRandomPosition(ref posArray);
        pSpecial = getRandomPosition(ref posArray);
     
     
        for (int i = 0; i < length; i++)
        {
            if (i == pLower)
                generatedPassword += getRandomChar(alphaCaps);
            else if (i == pUpper)
                generatedPassword += getRandomChar(alphaLow);
            else if (i == pNumber)
                generatedPassword += getRandomChar(numerics);
            else if (i == pSpecial)
                generatedPassword += getRandomChar(special);
            else
                generatedPassword += getRandomChar(allChars);
        }
        return generatedPassword;
    }
     
    private string getRandomChar(string fullString)
    {
        return fullString.ToCharArray()[(int)Math.Floor(r.NextDouble() * fullString.Length)].ToString();
    }
     
    private int getRandomPosition(ref string posArray)
    {
        int pos;
        string randomChar = posArray.ToCharArray()[(int)Math.Floor(r.NextDouble()
                                       * posArray.Length)].ToString();
        pos = int.Parse(randomChar);
        posArray = posArray.Replace(randomChar, "");
        return pos;
    }

    ConsultSarath - We provide end to end outsourcing solutions for .net programming requirements- you can hire programmer for hourly rates, for monthly commitments, for short term projects, for long term projects, Contact to know our hourly rates for programmer in India. ConsultSarath - We provide end to end outsourcing solutions for php programming requirements- you can hire programmer for hourly rates, for monthly commitments, for short term projects, for long term projects, Contact to know our hourly rates for programmer in India. ConsultSarath - We provide end to end outsourcing solutions for python programming requirements- you can hire programmer for hourly rates, for monthly commitments, for short term projects, for long term projects, Contact to know our hourly rates for programmer in India.

    Other Popular Articles
    We are experts in Cloud Computing Technologies. We can assist you to build high scalable business applications using Amazon Web Services (Amazon EC2, Amazon S3, Amazon SES, SNS, CloudFront), Windows Azure Platforms - Windows Azure and SQL Server Azure, Google App Engine using Python and Django Framework. We are Expert Programming Consultants available at affordable rates per hour. We work on several technologies - .NET, Python, Google App Engine, PHP, Windows Azure, Amazon Web Services ...