java - Generate Random String Containing Alpha-Numeric and Special Chars? -


i'm interested in generating (secure) random string following properties:

  1. atleast 1 upper case letter
  2. atleast 1 lower case letter
  3. atleast 1 digit 0-9
  4. atleast 1 special char chars $&@?<>~!%#

the length of string should 12-13 digits/chars long.

i know there class in apache commons can generate random strings there no option include special chars.

i'm aware of other similar questions on none of them address these requirements.

i've tried following far:

import java.security.securerandom;  public final class sessionidentifiergenerator {   private securerandom random = new securerandom();    public string nextsessionid() {     return       new biginteger(130, random).tostring(32);       }     } 

but not contain char set each of 4 points.

i tried:

static final string ab = "0123456789abcdefghijklmnopqrstuvwxyz"; static random rnd = new random();  string randomstring( int len )  {    stringbuilder sb = new stringbuilder( len );    for(int = 0; < len; i++)        sb.append(ab.charat( rnd.nextint(ab.length())));    return sb.tostring(); } 

i know can modify string ab include special chars there's no way guarantee string contain atleast 1 upper, 1 lower, 1 digit , 1 special char.

i'm using java.

the easiest way in case generate random password containing of allowed symbols, test whether criteria met:

private static final string symbols =       "abcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyz0123456789$&@?<>~!%#";  public static string genpassword(random r) {     while(true) {         char[] password = new char[r.nextboolean()?12:13];         boolean hasupper = false, haslower = false, hasdigit = false, hasspecial = false;         for(int i=0; i<password.length; i++) {             char ch = symbols.charat(r.nextint(symbols.length()));             if(character.isuppercase(ch))                 hasupper = true;             else if(character.islowercase(ch))                 haslower = true;             else if(character.isdigit(ch))                 hasdigit = true;             else                 hasspecial = true;             password[i] = ch;         }         if(hasupper && haslower && hasdigit && hasspecial) {             return new string(password);         }     } } 

according tests, number of required iterations exceeds 5 , in more half tests first generated password meets criteria. though don't force users memoize such passwords! here's how like:

c3h$oyukczzl si4e8f4swjy#i v$9www7zj8ba ~9htwmwcfc!s wbm94~ah%z%mu p4te36s&y>j14 r9bsqq@23eyk ptfcvr5u?pizq ce8ot>a74pmzp 4zaco~p6xuf3e aiv?vdn4j9pe 

Comments

Popular posts from this blog

dns - How To Use Custom Nameserver On Free Cloudflare? -

python - Pygame screen.blit not working -

c# - Web API response xml language -