Categories

Tools

bitdefender

1&1 Web Hosting

Generate random passwords length prefixed, with Java


The Java code described below, allows you to generate random passwords. It is possible to insert the password length using a command-line argument, or generate a default length password, such as 8 characters.

Code:

import java.util.*;

public class PasswordGenerator
{  
	static final String CHAR_SET = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcbefghijklmnopqrstuvwxyz0123456789[]+#&£$";

	public static void main(String[] args)
	{  
		int passwordLength = 8;
		if (args.length > 0) {
			try {
			passwordLength = Integer.parseInt(args[0]);
			} catch (NumberFormatException e) { }
		}
		
		String p = RandomString(CHAR_SET, passwordLength);
		System.out.println("Your password of "+passwordLength+" char is: " + p);
	}
	
	private static String RandomChars(String cs)
	{
		String rc = "";
		int length = cs.length();
		int index = (int) (Math.random() * length);
		return rc + cs.charAt(index);
	}
	
	private static String RandomString(String cs, int lenght)
	{
		String rs = "";
		for(int i=0; i<lenght; i++) 
		{
		rs+= RandomChars( cs );
		}
		return rs;	
	}
}

Example usage:

>java -cp . PasswordGenerator
Your password of 8 char is: u[#cof9U
>Exit code: 0

>java -cp . PasswordGenerator 12
Your password of 12 char is: Af3LBRYZ41za
>Exit code: 0

>java -cp . PasswordGenerator 16
Your password of 16 char is: b3vB+NCDqo0p0Iao
>Exit code: 0

>java -cp . PasswordGenerator 18
Your password of 18 char is: Uvb7C2WP2VYUTb8AW£
>Exit code: 0

Posted in Java by MdmSoft

If our work has been of help, you can help us with a small donation...
Our programmers will thank you!



All information contained in this web site are the property of MdmSoft. The information is provided "as is", MdmSoft will not be liable for any misuse of the code contained in these pages, nor can it be for inaccuracies, grammatical errors or other factors that may have caused damage or lost earnings. MdmSoft is not responsible for the content of comments posted by users.
The examples in this area have the educational and demonstration purposes only, and may be copied only for your reference, but cannot be used for commercial purposes, or for any other purpose, without the express written consent of MdmSoft.
MdmSoft also reserves the right to change, without notice, to your liking this web site, the pages and its sections, and may suspend temporarily or definitely the various services included on this site.
While using this site, you agree to have read and accepted our Terms of Service and Privacy Policy.