Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Generating a random hex string (of length 50) in Java ME/J2ME

Tags:

My app needs to generate a hex string to use as a session ID. Java's SecureRandom doesn't seem to be working ("java/lang/NoClassDefFoundError: java/security/SecureRandom: Cannot create class in system package")

I thought of doing something like this:

byte[]  resBuf = new byte[50]; new Random().nextBytes(resBuf); String  resStr = new String(Hex.encode(resBuf)); 

But the method nextBytes(byte[] bytes) isn't available for some strange reason.

Does anyone have a means of generating a random hex number in Java ME/J2ME?

Many thanks.

Edit: The above generator seems to work when using Bouncy Castle lcrypto-j2me-145 (but not lcrypto-j2me-147).

like image 977
Bataleon Avatar asked Jan 31 '13 09:01

Bataleon


People also ask

How do you generate a random hexadecimal in Java?

To generate Random Hexadecimal Bytes, first, a random byte can be generated in decimal form using Java. util. Random. nextInt() and then it can be converted to hexadecimal form using Integer.

How do you generate a random text string in Java?

Using randomUUID() java. util. UUID is another Java class that can be used to generate a random string. It offers a static randomUUID() method that returns a random alphanumeric string of 32 characters.

Can we generate random string?

Using the random index number, we have generated the random character from the string alphabet. We then used the StringBuilder class to append all the characters together. If we want to change the random string into lower case, we can use the toLowerCase() method of the String .


1 Answers

JavaME is a subset of JavaSE, so many classes and methods in the desktop version are not available.

Looks like you are trying to get a random string of a given length. You can do something like this:

    private String getRandomHexString(int numchars){         Random r = new Random();         StringBuffer sb = new StringBuffer();         while(sb.length() < numchars){             sb.append(Integer.toHexString(r.nextInt()));         }          return sb.toString().substring(0, numchars);     } 
like image 178
Mister Smith Avatar answered Oct 10 '22 01:10

Mister Smith