File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Swing / AWT / SWT and the fly likes Password creation using rng.nextInt() Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Swing / AWT / SWT
Bookmark "Password creation using rng.nextInt()" Watch "Password creation using rng.nextInt()" New topic

Password creation using rng.nextInt()

Mark Phylus

Joined: Mar 28, 2004
Posts: 18
I used rng.nextInt()to generate both username and password. The username is fine but the password contains wild character that I want to eliminate. How? Here is some code:
private void makePassWord()
int numEven = 0;
int numOdd = 0;
for(int k=0; k<4; k++)
numEven = rng.nextInt(65)+26; // any upper case letter or @
passWord += (char) numEven;
numOdd = rng.nextInt(49)+33; // any digitprintable character
// from 33 to 90
passWord += (char) numOdd;
Wayne L Johnson
Ranch Hand

Joined: Sep 03, 2003
Posts: 399

With the old way, numEven = rng.nextInt(65)+26;, nextInt will return a value in the range 0-64. Adding 26 to it gives you a value in the range 26-90, which is not what you want.
With the new way, numEven = rng.nextInt(27)+64;, nextInt will return a value in the range 0-26, and adding 64 to that will give you a value in the range 64-90, which is the uppercase characters and '@'.
For the "numOdd", I changed the seed to 58 to give you the full 33-90 range.
[ March 31, 2004: Message edited by: Wayne L Johnson ]
Brian Pipa
Ranch Hand

Joined: Sep 29, 2003
Posts: 299
Here's another way to do it. Put all characters that you consider legal/valid into an array and just randomly choose characters out of the array:

[ April 05, 2004: Message edited by: Brian Pipa ]

My Java Freeware:<br />MACCC - <a href="" target="_blank" rel="nofollow"></a><br />Nator - <a href="" target="_blank" rel="nofollow"></a>
Mark Phylus

Joined: Mar 28, 2004
Posts: 18
Thanks guys.
I agree. Here's the link:
subject: Password creation using rng.nextInt()
jQuery in Action, 3rd edition