Link to home
Start Free TrialLog in
Avatar of itsme_asif
itsme_asif

asked on

Random String generation

Hi Experts,

I would you can send me Java code samples to generate a random string for password with the following requirements

Password Length = 10

One or more lowercase alphabetic characters (a-z)
One or more uppercase alphabetic characters (A-Z)
One or more numeric characters (0-9)
One or more special characters (!@#$%^&*-+= etc)

I already have the following code with generates, 1 number, 1 Upper case char, 1 Lower case char, however I dont know how to add special chars to the list.


public static String genPwd() {
    	// Generate alpha numeric password of length 10

        int length = 10;

        if (length > 0) {
            char[] pw = new char[length];
            int c ='A';
            int  r1 = 0;
            for (int i=0; i < length; i++) {
                r1 = (int)(Math.random() * 3);
                // pick a random upper case or lower case letter or a digit
                switch(r1) {
                case 0: c = '0' +  (int)(Math.random() * 10); break;
                case 1: c = 'a' +  (int)(Math.random() * 26); break;
                case 2: c = 'A' +  (int)(Math.random() * 26); break;
                }
                pw[i] = (char)c;
            }


            return new String(pw);
         }

        return null;
    }

Open in new window

Avatar of a_b
a_b

Here is a very simple example - http://stackoverflow.com/questions/41107/how-to-generate-a-random-alpha-numeric-string-in-java

Just add the symbols that you need to generate in the symbols array.
ASKER CERTIFIED SOLUTION
Avatar of Chandramouli k
Chandramouli k
Flag of India image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial