简体   繁体   中英

Same random guarantee

I have got this code:

BigInteger bigInteger = new BigInteger(64, new Random());
Long longValue=-Math.abs(bigInteger.longValue());
int desiredLen=384;
Random random=new Random(longValue);
byte [] randomString=new byte[desiredLen];
for(int i=0;i<desiredLen;i++)
    randomString[i]=(byte)(Math.abs(random.nextInt())&255);

Now there are these values:

  • longValue - is sent to other side (server) and later used to generate key again on other side
  • randomString - is encryption key generated randomly based on longValue

Simply, client sends message containing first 8 bytes longValue and other stuff is encrypted content by randomString.

What is the guarantee that exactly the same numbers will be generated on all physical and virtual machines and across all Java versions based on received longValue? And how about if client is written in other language like C#?

The API documentation of java.util.Random specifies the exact algorithm being used.

This isn't a cast-iron guarantee that things won't change, not as much as the signatures of methods, but any implementation detail you publish in an API doc is almost as binding. Certainly Oracle are highly unlikely to ever change it.

Whether you feel that's enough for you is up to you.

I personally wouldn't rely on it, not because it might change but because it introduces a dependency that may not be immediately obvious. The decision should also depend on how important the task is. If it's a hobby project, it could be okay, if it's bank-to-bank communication, I wouldn't even think about using Random at all, as it isn't cryptographically secure.

As for interoperability with other languages, there's no guarantee whatsoever.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM