Generate a Secure Random Password in Java with Minimum Special Character Requirements

后端 未结 4 1900
暖寄归人
暖寄归人 2021-02-04 10:35

How do I create a random password that meets the system\'s length and character set requirements in Java?

I have to create a random password that is 10-14 characters lo

4条回答
  •  北恋
    北恋 (楼主)
    2021-02-04 10:59

    I suggest using apache commons RandomStringUtils. Use something what is already done.

    String characters = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789~`!@#$%^&*()-_=+[{]}\\|;:\'\",<.>/?";
    String pwd = RandomStringUtils.random( 15, characters );
    System.out.println( pwd );
    

    If you are using maven

    
        org.apache.commons
        commons-lang3
        3.4
    
    

    otherwise download jar

    UPDATE Version with secure random. So matter of required characters left and can be solved as in comment, generate required parts separately and normal ones. Then join them randomly.

    char[] possibleCharacters = (new String("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789~`!@#$%^&*()-_=+[{]}\\|;:\'\",<.>/?")).toCharArray();
    String randomStr = RandomStringUtils.random( randomStrLength, 0, possibleCharacters.length-1, false, false, possibleCharacters, new SecureRandom() );
    System.out.println( randomStr );
    

提交回复
热议问题