lundi 2 juillet 2018

Random.nextBytes(byte[]) behavious in java

Question is, why is the behavior of acquiring the same number of bytes in separate method calls returns different bytes based on whether 5000 bytes where called in a single method call or 5000 method calls were made with a byte array of length 1.

Take the following example: Prints 21 in the terminal as opposed to 5000,(5000 divided by 256 gives ~19, which makes it likely that the 21 matches are simple coincidences).

                Random rand = new Random(0);
                byte tmp1[] = new byte[5000];
                rand.nextBytes(tmp1);
                rand = new Random(0);
                byte tmp2[] = new byte[5000];
                byte tmp3[] = new byte[1];
                for(int i = 0; i < 5000;i++)
                {
                    rand.nextBytes(tmp3);
                    tmp2[i] =tmp3[0];
                }
                int matches = 0;
                for(int i = 0; i < 5000;i++)
                {
                    if(tmp1[i] == tmp2[i])
                    {
                        matches++;
                    }
                }
                System.out.println(matches);

More importantly, any way to hack it to have identical bytes generated irrelevant of whether I invoke the method with an array of length 5000 once or an array of length 2500 twice, etc.

Thank you




Aucun commentaire:

Enregistrer un commentaire