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

拈花ヽ惹草 提交于 2020-01-03 06:47:08

问题


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).


回答1:


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);
    }


来源:https://stackoverflow.com/questions/14622622/generating-a-random-hex-string-of-length-50-in-java-me-j2me

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