--- old/src/java.base/share/classes/java/math/BigInteger.java 2018-12-19 17:51:08.000000000 -0800 +++ new/src/java.base/share/classes/java/math/BigInteger.java 2018-12-19 17:51:08.000000000 -0800 @@ -699,6 +699,23 @@ private static byte[] randomBits(int numBits, Random rnd) { if (numBits < 0) throw new IllegalArgumentException("numBits must be non-negative"); + + // It is highly likely that the first, or one of the first few, bytes + // generated by Random.nextBytes() will be non-zero thereby making the + // distribution highly non-uniform by skewing it to the upper end of + // the interval [0, 2^numBits). To improve the uniformity of the + // distribution, adjust numBits to a random value in the interval + // [0, numBits]. + if (numBits < Integer.MAX_VALUE) { + final int numBitsOriginal = numBits; + numBits = rnd.nextInt(numBits + 1); + // Increment the adjusted maximum bit length to help prevent the + // very largest numbers from being underrepresented. + if (numBits < numBitsOriginal) { + numBits++; + } + } + int numBytes = (int)(((long)numBits+7)/8); // avoid overflow byte[] randomBits = new byte[numBytes]; --- old/test/jdk/java/math/BigInteger/ModPow.java 2018-12-19 17:51:09.000000000 -0800 +++ new/test/jdk/java/math/BigInteger/ModPow.java 2018-12-19 17:51:09.000000000 -0800 @@ -1,5 +1,5 @@ /* - * Copyright (c) 1998, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1998, 2018, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -33,7 +33,9 @@ Random rnd = new Random(1234); for (int i=0; i<2000; i++) { - BigInteger m = new BigInteger(800, rnd); + // Clamp random modulus to non-negative or modPow() will throw + // an ArithmeticException. + BigInteger m = new BigInteger(800, rnd).max(BigInteger.ONE); BigInteger base = new BigInteger(16, rnd); if (rnd.nextInt() % 1 == 0) base = base.negate();