Generate a random string of specified length that contains only specified characters (in Java)

梦想与她 提交于 2019-12-12 05:26:07

问题


Does anybody know of a good way to generate a random String of specified length and characters in Java.

For example 'length' could be 5 and 'possibleChars' could be 'a,b,c,1,2,3,!'.

So

c!a1b is valid

BUT

cba16 is not.

I could try to write something from scratch but I feel like this must be a common use case for things like generating passwords, generating coupon codes, etc...

Any ideas?


回答1:


You want something like this?

Random r=new Random();

char[] possibleChars="abc123!".toCharArray();
int length=5;

char[] newPassword=new char[length];

for (int i=0; i<length;i++)
    newPassword[i]=possibleChars[r.nextInt(possibleChars.length)];

System.out.println(new String(newPassword));



回答2:


The code to do this is pretty short. Have a char[] or String with N legal chars, and, length times, pick a random number R between 0 and N-1, use R to pick a character to append to your generated String.




回答3:


I could try to write something from scratch but I feel like this must be a common use case for things like generating passwords, generating coupon codes, etc...

It is not that common, and the detailed requirements are different each time. Besides, the code is simple to the point of being trivial. (Modulo the concerns below ... which are really about the requirements rather than the solution.)

In short, it is quicker to write your own method than to go looking for an existing library method that does this.


When you use a scheme that involves random numbers, you need to be aware of the possibility that you will get collisions; i.e. that the method will generate the same random string on more than one occasion. You can mitigate this by using a longer string, but that only works to a certain point ... depending on your random number generator. (Typical random number generators are actually pseudo-random number generators, and produce a sequence of numbers that eventually cycle around. And even with a perfect random number generator there is a finite probability of repeats over a short sequence.)

In fact, this is another reason why a "one size fits all" solution to your problem is not a good idea.




回答4:


If this is for real security, as opposed to homework or a programming exercise, then use SecureRandom, not Random.

Read the Diceware website for a lot of very good ideas on the random generation of passwords and other things.



来源:https://stackoverflow.com/questions/10923445/generate-a-random-string-of-specified-length-that-contains-only-specified-charac

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!