Skip to content
David Kittell
David Kittell

Application & System: Development / Integration / Orchestration

  • Services
    • Application Development
    • Online Application Integration
  • Code
  • Online Tools
  • Tech Support
David Kittell

Application & System: Development / Integration / Orchestration

CSharp – Random Password Generator

Posted on May 7, 2014April 9, 2019 By David Kittell

Sometimes it’s helpful to simply have a random password.

In this small group of code you can define what parameters to use, I have taken the liberty to remove some of the characters that are usually mistaken for a different character like an upper case I and the number 1.

private static int DEFAULT_MAX_PASSWORD_LENGTH = 10;
private static int DEFAULT_MIN_PASSWORD_LENGTH = 8;
private static string PASSWORD_CHARS_LCASE = "abcdefgijkmnopqrstwxyz";
private static string PASSWORD_CHARS_NUMERIC = "23456789";
private static string PASSWORD_CHARS_SPECIAL = "*$+?&!%";
private static string PASSWORD_CHARS_UCASE = "ABCDEFGHJKLMNPQRSTWXYZ";

Full Source Code

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Security.Cryptography;

namespace Project1
{
	public partial class Form1 : Form
	{
		public Form1()
		{
			InitializeComponent();
		}

		private void Form1_Load(object sender, EventArgs e)
		{
			MessageBox.Show(RandomPassword.Generate());
		}
	}

	public class RandomPassword
	{
		private static int DEFAULT_MAX_PASSWORD_LENGTH = 10;
		private static int DEFAULT_MIN_PASSWORD_LENGTH = 8;
		private static string PASSWORD_CHARS_LCASE = "abcdefgijkmnopqrstwxyz";
		private static string PASSWORD_CHARS_NUMERIC = "23456789";
		private static string PASSWORD_CHARS_SPECIAL = "*$+?&!%";
		private static string PASSWORD_CHARS_UCASE = "ABCDEFGHJKLMNPQRSTWXYZ";

		public static string Generate()
		{
			return Generate(DEFAULT_MIN_PASSWORD_LENGTH, DEFAULT_MAX_PASSWORD_LENGTH);
		}

		public static string Generate(int length)
		{
			return Generate(length, length);
		}

		public static string Generate(int minLength, int maxLength)
		{
			if (((minLength <= 0) || (maxLength <= 0)) || (minLength > maxLength))
			{
				return null;
			}
			char[][] chArray = new char[][] { PASSWORD_CHARS_LCASE.ToCharArray(), PASSWORD_CHARS_UCASE.ToCharArray(), PASSWORD_CHARS_NUMERIC.ToCharArray(), PASSWORD_CHARS_SPECIAL.ToCharArray() };
			int[] numArray = new int[chArray.Length];
			for (int i = 0; i < numArray.Length; i++)
			{
				numArray[i] = chArray[i].Length;
			}
			int[] numArray2 = new int[chArray.Length];
			for (int j = 0; j < numArray2.Length; j++)
			{
				numArray2[j] = j;
			}
			byte[] data = new byte[4];
			new RNGCryptoServiceProvider().GetBytes(data);
			int seed = ((((data[0] & 0x7f) << 0x18) | (data[1] << 0x10)) | (data[2] << 8)) | data[3];
			Random random = new Random(seed);
			char[] chArray2 = null;
			if (minLength < maxLength)
			{
				chArray2 = new char[random.Next(minLength, maxLength + 1)];
			}
			else
			{
				chArray2 = new char[minLength];
			}
			int maxValue = numArray2.Length - 1;
			for (int k = 0; k < chArray2.Length; k++)
			{
				int num4;
				int num6;
				if (maxValue == 0)
				{
					num6 = 0;
				}
				else
				{
					num6 = random.Next(0, maxValue);
				}
				int index = numArray2[num6];
				int num7 = numArray[index] - 1;
				if (num7 == 0)
				{
					num4 = 0;
				}
				else
				{
					num4 = random.Next(0, num7 + 1);
				}
				chArray2[k] = chArray[index][num4];
				if (num7 == 0)
				{
					numArray[index] = chArray[index].Length;
				}
				else
				{
					if (num7 != num4)
					{
						char ch = chArray[index][num7];
						chArray[index][num7] = chArray[index][num4];
						chArray[index][num4] = ch;
					}
					numArray[index]--;
				}
				if (maxValue == 0)
				{
					maxValue = numArray2.Length - 1;
				}
				else
				{
					if (maxValue != num6)
					{
						int num10 = numArray2[maxValue];
						numArray2[maxValue] = numArray2[num6];
						numArray2[num6] = num10;
					}
					maxValue--;
				}
			}
			return new string(chArray2);
		}
	}
}

Original Resource Unknown

Originally Posted on May 7, 2014
Last Updated on April 9, 2019
All information on this site is shared with the intention to help. Before any source code or program is ran on a production (non-development) system it is suggested you test it and fully understand what it is doing not just what it appears it is doing. I accept no responsibility for any damage you may do with this code.

Related

Code CSharp

Post navigation

Previous post
Next post

Related Posts

Bash – Rename Picture

Posted on November 15, 2022August 17, 2024

for f in *.HEIC; do mv -v "$f" "${f%.HEIC}.heic" done # 1 set -eu -o pipefail # 2 count=$(find . -depth 1 -name "*.heic" | wc -l | sed ‘s/[[:space:]]*//’) echo "converting $count files .heic files to .jpg" # 3 magick mogrify -monitor -format jpg *.heic # 4 echo "Remove…

Read More

LinkedIn API – Full Profile Details

Posted on April 15, 2015

Using LinkedIn API Console this URL will provide full profile details XML https://api.linkedin.com/v1/people/~:(id,first-name,last-name,headline,picture-url,industry,summary,specialties,positions:(id,title,summary,start-date,end-date,is-current,company:(id,name,type,size,industry,ticker)),educations:(id,school-name,field-of-study,start-date,end-date,degree,activities,notes),associations,interests,num-recommenders,date-of-birth,publications:(id,title,publisher:(name),authors:(id,name),date,url,summary),patents:(id,title,summary,number,status:(id,name),office:(name),inventors:(id,name),date,url),languages:(id,language:(name),proficiency:(level,name)),skills:(id,skill:(name)),certifications:(id,name,authority:(name),number,start-date,end-date),courses:(id,name,number),recommendations-received:(id,recommendation-type,recommendation-text,recommender),honors-awards,three-current-positions,three-past-positions,volunteer)?format=xml JSON https://api.linkedin.com/v1/people/~:(id,first-name,last-name,headline,picture-url,industry,summary,specialties,positions:(id,title,summary,start-date,end-date,is-current,company:(id,name,type,size,industry,ticker)),educations:(id,school-name,field-of-study,start-date,end-date,degree,activities,notes),associations,interests,num-recommenders,date-of-birth,publications:(id,title,publisher:(name),authors:(id,name),date,url,summary),patents:(id,title,summary,number,status:(id,name),office:(name),inventors:(id,name),date,url),languages:(id,language:(name),proficiency:(level,name)),skills:(id,skill:(name)),certifications:(id,name,authority:(name),number,start-date,end-date),courses:(id,name,number),recommendations-received:(id,recommendation-type,recommendation-text,recommender),honors-awards,three-current-positions,three-past-positions,volunteer)?format=json All information on this site is shared with the intention to help. Before any source code or program is ran on a production (non-development) system it is suggested you test it and fully understand what…

Read More

Azure PowerShell – Create Virtual Network Within Resource Group

Posted on December 29, 2016

This is still a work in progress to include all the variables but the script below will create a Resource Group then create a Virtual Network with 3 subnets and a gateway along with custom DNS. # Main Reference: https://docs.microsoft.com/en-us/azure/virtual-network/virtual-networks-create-vnet-arm-ps Clear Write-verbose "Setting Environment Variables – Start" $VNetName = “azuredev-eastus-vnet”…

Read More

Code

Top Posts & Pages

  • PowerShell - Rename Pictures to Image Taken
  • Front Page
  • PowerShell - IIS Remove Site
  • SQLite - Auto-Increment / Auto Generate GUID
  • PowerShell - FTP Upload Directory With Sub-Directories

Recent Posts

  • Javascript – Digital Clock with Style
  • BASH – Web Ping Log
  • BASH – Picture / Video File Name Manipulation
  • Mac OSX Terminal – Create SSH Key
  • Bash – Rename Picture

Top Posts

  • PowerShell - Rename Pictures to Image Taken
  • PowerShell - IIS Remove Site
  • SQLite - Auto-Increment / Auto Generate GUID
  • PowerShell - FTP Upload Directory With Sub-Directories
  • Raspberry Pi - Remove Default Apps
  • PowerShell - Change Windows CD/DVD Drive Letter
©2025 David Kittell | WordPress Theme by SuperbThemes