How to generate a SecureRandom number with a specific bit range [duplicate] - java

This question already has answers here:
How do I generate random integers within a specific range in Java?
(72 answers)
Closed 1 year ago.
I have maximum number of bits that is not bit aligned E.g. 35 and required to generate unique random number from 1 - 68719476734 (max number for 35 bits).
Could use SecureRandom but will have to extract 5 bytes out of it and convert to Long maybe, but chances of collision seem to a concern. What are some options to generate a random for this range.
Could i seed this random with nanoTime maybe if there is a collision and regenerate in this range.

First, a few comments:
The max value for 35 bits is 34359738367, not 68719476734.
68719476734 is not even the max value for 36 bits, 68719476735 is.
Do not seed a SecureRandom. That reduces the security of it.
To generate a 35-bit random number, excluding value zero, just generate a long random value, take the last 35 bits, and redo if the value is zero.
SecureRandom r = new SecureRandom();
long value;
do {
value = r.nextLong() & ((1L << 35) - 1);
} while (value == 0);

There may be a better way, but perhaps this can help. The first simply prints the single number generated from a stream. The second masks off the required bits. Interesting that the values for the same seed are different (which I can't explain). But the first method which allows a range might be sufficient for what you want. I am clearly not an expert on this but provided it to foster some ideas.
SecureRandom r = new SecureRandom();
r.setSeed(23);
// generate a sum of 1 element to get the element from the stream.
long v = 0;
while (v == 0) {
v = r.longs(1,1L<<34, (1L<<35)-1).sum();
}
System.out.println(v);
System.out.println(64-Long.numberOfLeadingZeros(v));
r.setSeed(23);
long vv = 0;
while (vv == 0) {
vv = r.nextLong()&((1L<<35)-1);
}
System.out.println(vv);
System.out.println(64-Long.numberOfLeadingZeros(vv));
prints
31237208166
35
9741674490
34
My assumption here was that the stream version above would not be provided if the random numbers did not meet the secure requirements.

Related

Best way to generate unique Random number in Java

I have to generate unique serial numbers for users consisting of 12 to 13 digits. I want to use random number generator in Java giving the system. Time in milliseconds as a seed to it. Please let me know about the best practice for doing so. What I did was like this
Random serialNo = new Random(System.currentTimeMillis());
System.out.println("serial number is "+serialNo);
Output came out as: serial number is java.util.Random#13d8cc98
For a bit better algorithm pick SecureRandom.
You passed a seed to the random constructor. This will pick a fixed sequence with that number. A hacker knowing the approximate time of calling, might restrict the number of attempts. So another measure is not using the constructor and nextLong at the same spot.
SecureRandom random = new SecureRandom​();
long n = random.nextLong();
A symmetric bit operation might help:
n ^= System.currentMillis();
However there is a unique number generation, the UUID, a unique 128 bits number, two longs. If you xor them (^) the number no longer is that unique, but might still be better having mentioned the circumstantial usage of random numbers.
UUID id = UUID.randomUUID();
long n = id.getLeastSignificantBits() ^ id.getMostSignificantBits();
Create a random number generator using the current time as seed (as you did)
long seed = System.currentTimeMillis();
Random rng = new Random​(seed);
Now, to get a number, you have to use the generator, rng is NOT a number.
long number = rng.nextLong();
According to the documentation, this will give you a pseudorandom number with 281.474.976.710.656 different possible values.
Now, to get a number with a maximum of 13 digits:
long number = rng.nextLong() % 10000000000000;
And to get a number with exactly 13 digits:
long number = (rng.nextLong() % 9000000000000) + 1000000000000;
First, import the Random class:
import java.util.Random;
Then create an instance of this class, with the current milliseconds as its seed:
Random rng = new Random(System.currentTimeMillis());
This line would generate an integer that can have up to 13 digits:
long result = rng.nextLong() % 10000000000000;
This line would generate an integer that always have 13 digits:
long result = rng.nextLong() % 9000000000000 + 1000000000000;
There are three ways to generate Random numbers in java
java.util.Random class
We can generate random numbers of types integers, float, double, long, booleans using this class.
Example :
//Random rand = new Random();
// rand_int1 = rand.nextInt(1000)
Math.random method : Can Generate Random Numbers of double type.
random(), this method returns a double value with a positive sign, greater than or equal to 0.0 and less than 1.0.
Example :
Math.random());
//Gives output 0.15089348615777683
ThreadLocalRandom class
This class is introduced in java 1.7 to generate random numbers of type integers, doubles, booleans etc
Example :
//int random_int1 = ThreadLocalRandom.current().nextInt();
// Print random integers
//System.out.println("Random Integers: " + random_int1);

Difference between two random statements [duplicate]

This question already has answers here:
Java random numbers using a seed
(7 answers)
Closed 5 years ago.
I want to know why the numbers appearing in the first column will change each time the code is run. The numbers in the second column will always be the same. (83 51 77 90 96 58 35 38 86 54)?
Random randomGenerator = new Random();
Random otherGenerator = new Random(123);
for(int i = 0; i < 10; i++) {
int number1 = 1 + randomGenerator.nextInt(100);
int number2 = 1 + otherGenerator.nextInt(100);
System.out.println("random numbers "+number1+" " +number2);
}
This happens because the Random used for the second column is seeded with a constant 123, while the one for the first column has a seed that varies each time the code is executed.
Note that the values produced by Random are not truly random; they are completely determined by the seed.
The doc says:
Creates a new random number generator using a single long seed. The seed is the initial value of the internal state of the pseudorandom number generator which is maintained by method
You have fixed the initial state of the 2nd generator is fixed and it is from the seed that the next random numbers are generated.
On the other side, if you used System.nanoTime() to generate the seed, you would see each time your generator creates different random numbers.
See: https://docs.oracle.com/javase/7/docs/api/java/util/Random.html#Random(long)

Implementation of java.util.Random.nextInt

This function is from java.util.Random. It returns a pseudorandom int uniformly distributed between 0 and the given n. Unfortunately I did not get it.
public int nextInt(int n) {
if (n <= 0)
throw new IllegalArgumentException("n must be positive");
if ((n & -n) == n) // i.e., n is a power of 2
return (int)((n * (long)next(31)) >> 31);
int bits, val;
do {
bits = next(31);
val = bits % n;
} while (bits - val + (n-1) < 0);
return val;
}
My questions are:
Why does it treat the case where n is a power of two specially ? Is it just for performance ?
Why doest it reject numbers that bits - val + (n-1) < 0 ?
It does this in order to assure an uniform distribution of values between 0 and n. You might be tempted to do something like:
int x = rand.nextInt() % n;
but this will alter the distribution of values, unless n is a divisor of 2^31, i.e. a power of 2. This is because the modulo operator would produce equivalence classes whose size is not the same.
For instance, let's suppose that nextInt() generates an integer between 0 and 6 inclusive and you want to draw 0,1 or 2. Easy, right?
int x = rand.nextInt() % 3;
No. Let's see why:
0 % 3 = 0
1 % 3 = 1
2 % 3 = 2
3 % 3 = 0
4 % 3 = 1
5 % 3 = 2
6 % 3 = 0
So you have 3 values that map on 0 and only 2 values that map on 1 and 2. You have a bias now, as 0 is more likely to be returned than 1 or 2.
As always, the javadoc documents this behaviour:
The hedge "approximately" is used in the foregoing description only
because the next method is only approximately an unbiased source of
independently chosen bits. If it were a perfect source of randomly
chosen bits, then the algorithm shown would choose int values from the
stated range with perfect uniformity.
The algorithm is slightly tricky. It rejects values that would result
in an uneven distribution (due to the fact that 2^31 is not divisible
by n). The probability of a value being rejected depends on n. The
worst case is n=2^30+1, for which the probability of a reject is 1/2,
and the expected number of iterations before the loop terminates is 2.
The algorithm treats the case where n is a power of two specially: it
returns the correct number of high-order bits from the underlying
pseudo-random number generator. In the absence of special treatment,
the correct number of low-order bits would be returned. Linear
congruential pseudo-random number generators such as the one
implemented by this class are known to have short periods in the
sequence of values of their low-order bits. Thus, this special case
greatly increases the length of the sequence of values returned by
successive calls to this method if n is a small power of two.
The emphasis is mine.
next generates random bits.
When n is a power of 2, a random integer in that range can be generated just by generating random bits (I assume that always generating 31 and throwing some away is for reproducibility). This code path is simpler and I guess it's a more commonly used case so it's worth making a special "fast path" for this case.
When n isn't a power of 2, it throws away numbers at the "top" of the range so that the random number is evenly distributed. E.g. imagine we had n=3, and imagine we were using 3 bits rather than 31 bits. So bits is a randomly generated number between 0 and 7. How can you generate a fair random number there? Answer: if bits is 6 or 7, we throw it away and generate a new one.

Issue with implementation of Fermat's little therorm

Here's my implementation of Fermat's little theorem. Does anyone know why it's not working?
Here are the rules I'm following:
Let n be the number to test for primality.
Pick any integer a between 2 and n-1.
compute a^n mod n.
check whether a^n = a mod n.
myCode:
int low = 2;
int high = n -1;
Random rand = new Random();
//Pick any integer a between 2 and n-1.
Double a = (double) (rand.nextInt(high-low) + low);
//compute:a^n = a mod n
Double val = Math.pow(a,n) % n;
//check whether a^n = a mod n
if(a.equals(val)){
return "True";
}else{
return "False";
}
This is a list of primes less than 100000. Whenever I input in any of these numbers, instead of getting 'true', I get 'false'.
The First 100,008 Primes
This is the reason why I believe the code isn't working.
In java, a double only has a limited precision of about 15 to 17 digits. This means that while you can compute the value of Math.pow(a,n), for very large numbers, you have no guarantee you'll get an exact result once the value has more than 15 digits.
With large values of a or n, your computation will exceed that limit. For example
Math.pow(3, 67) will have a value of 9.270946314789783e31 which means that any digit after the last 3 is lost. For this reason, after applying the modulo operation, you have no guarantee to get the right result (example).
This means that your code does not actually test what you think it does. This is inherent to the way floating point numbers work and you must change the way you hold your values to solve this problem. You could use long but then you would have problems with overflows (a long cannot hold a value greater than 2^64 - 1 so again, in the case of 3^67 you'd have another problem.
One solution is to use a class designed to hold arbitrary large numbers such as BigInteger which is part of the Java SE API.
As the others have noted, taking the power will quickly overflow. For example, if you are picking a number n to test for primality as small as say, 30, and the random number a is 20, 20^30 = about 10^39 which is something >> 2^90. (I took the ln of 10^39).
You want to use BigInteger, which even has the exact method you want:
public BigInteger modPow(BigInteger exponent, BigInteger m)
"Returns a BigInteger whose value is (this^exponent mod m)"
Also, I don't think that testing a single random number between 2 and n-1 will "prove" anything. You have to loop through all the integers between 2 and n-1.
#evthim Even if you have used the modPow function of the BigInteger class, you cannot get all the prime numbers in the range you selected correctly. To clarify the issue further, you will get all the prime numbers in the range, but some numbers you have are not prime. If you rearrange this code using the BigInteger class. When you try all 64-bit numbers, some non-prime numbers will also write. These numbers are as follows;
341, 561, 645, 1105, 1387, 1729, 1905, 2047, 2465, 2701, 2821, 3277, 4033, 4369, 4371, 4681, 5461, 6601, 7957, 8321, 8481, 8911, 10261, 10585, 11305, 12801, 13741, 13747, 13981, 14491, 15709, 15841, 16705, 18705, 18721, 19951, 23001, 23377, 25761, 29341, ...
https://oeis.org/a001567
161038, 215326, 2568226, 3020626, 7866046, 9115426, 49699666, 143742226, 161292286, 196116194, 209665666, 213388066, 293974066, 336408382, 376366, 666, 566, 566, 666 2001038066, 2138882626, 2952654706, 3220041826, ...
https://oeis.org/a006935
As a solution, make sure that the number you tested is not in this list by getting a list of these numbers from the link below.
http://www.cecm.sfu.ca/Pseudoprimes/index-2-to-64.html
The solution for C # is as follows.
public static bool IsPrime(ulong number)
{
return number == 2
? true
: (BigInterger.ModPow(2, number, number) == 2
? (number & 1 != 0 && BinarySearchInA001567(number) == false)
: false)
}
public static bool BinarySearchInA001567(ulong number)
{
// Is number in list?
// todo: Binary Search in A001567 (https://oeis.org/A001567) below 2 ^ 64
// Only 2.35 Gigabytes as a text file http://www.cecm.sfu.ca/Pseudoprimes/index-2-to-64.html
}

Random identifier in java

I would like to generate random identifier in java. The identifier should have a fixed size, and the probability of generating the same identifier twice should be very low(The system has about 500 000 users).In addition; the identifier should be so long that it’s unfeasible to “guess it” by a brute force attack.
My approach so far is something along the lines of this:
String alphabet = "0123456789ABCDE....and so on";
int lengthOfAlphabet = 42;
long length = 12;
public String generateIdentifier(){
String identifier = "";
Random random = new Random();
for(int i = 0;i<length;i++){
identifier+= alphabet.charAt(random.nextInt(lengthOfAlphabet));
}
return identifier;
}
I’m enforcing the uniqueness by a constraint in the database. If I hit an identifier that already has been created, I’ll keep generating until I find one that’s not in use.
My assumption is that I can tweak lenghtOfAlpahbet and length to get the properties I’m looking for:
Rare collisions
Unfeasible to brute force
The identifier should be as short as possible, as the users of the system will have to type it.
Is this a good approach? Does anyone have any thoughts on the value of “length”?
I think randomUUID is your friend. It is fixed width. http://docs.oracle.com/javase/1.5.0/docs/api/java/util/UUID.html#randomUUID()
If I remember my math correctly, since the UUID is 32 hex numbers (0-f) then the number of permutations are 16^32, which is a big number, and therefore pretty hard to guess.
I would suggest keeping it simple, and use built in methods to represent normal pseudo-random integers encoded as Strings:
Random random = new Random();
/**
* Generates random Strings of 1 to 6 characters. 0 to zik0zj
*/
public String generateShortIdentifier() {
int number;
while((number=random.nextInt())<0);
return Integer.toString(number, Character.MAX_RADIX);
}
/**
* Generates random Strings of 1 to 13 characters. 0 to 1y2p0ij32e8e7
*/
public String generateLongIdentifier() {
long number;
while((number=random.nextLong())<0);
return Long.toString(number, Character.MAX_RADIX);
}
Character.MAX_RADIX is 36, which would equal an alphabet of all 0 to 9 and A to Z. In short, you would be converting the random integers to a number of base 36.
If you want, you can tweak the length you want, but in just 13 characters you can encode 2^63 numbers.
EDIT: Modified it to generate only 0 to 2^63, no negative numbers, but that's up to you.

Categories