This is the mail archive of the gcc-bugs@gcc.gnu.org mailing list for the GCC project.


Index Nav: [Date Index] [Subject Index] [Author Index] [Thread Index]
Message Nav: [Date Prev] [Date Next] [Thread Prev] [Thread Next]
Other format: [Raw text]

libgcj/9271: Severe bias in java.security.SecureRandom


>Number:         9271
>Category:       libgcj
>Synopsis:       Severe bias in java.security.SecureRandom
>Confidential:   no
>Severity:       non-critical
>Priority:       medium
>Responsible:    unassigned
>State:          open
>Class:          sw-bug
>Submitter-Id:   net
>Arrival-Date:   Fri Jan 10 19:56:00 PST 2003
>Closed-Date:
>Last-Modified:
>Originator:     Casey Marshall
>Release:        gcj (GCC) 3.4 20030105 (experimental) (probably in most versions)
>Organization:
>Environment:
Linux 2.4.19-gentoo-r9 i686
configure: --enable-threads=posix --enable-shared --enable-languages=c++,java
>Description:
java.security.SecureRandom.nextBoolean() returns `true' an inordinate number of times.

java.security.SecureRandom.nextInt() returns negative integers too often.

The problem seems to be in the next(int numBits) method of java.security.SecureRandom. When packing the bits into the integer, line 360:

   for (int i = 0; i < tmp.length; i++)
      ret |= tmp[i] << (8 * i);

promotes the byte tmp[i] to an integer, therefore if tmp[i] is *negative* `ret' will be OR'd with 0xffffffXX, shifted left. This behavior is incorrect.

Furthermore, this method returns 8 bits of random data for next(1), meaning that nextBoolean() (in java.util.Random), which returns:

   return next(1) != 0;

will return `false' with only a 1 in 256 probability!
>How-To-Repeat:
// Shows that SecureRandom.nextBoolean() returns
// true far more often than false.

class randtest {
public static void main(String[] argv) {
   int ntrue = 0;
   int nfalse = 0;

   SecureRandom rand = new SecureRandom();
   for (int i = 0; i < 10000; i++)
      if (rand.nextBoolean())
         ntrue++;
      else
         nfalse++;

   System.out.println("true=" + ntrue + " false=" + nfalse);
   System.out.println("proportion t:f=" +
      ((double) ntrue / (double) nfalse) + ":1");
}
}
>Fix:
Patch as follows:

diff -u -r1.7 SecureRandom.java
--- libjava/java/security/SecureRandom.java     13 Dec 2002 14:21:07 -0000     1.7
+++ libjava/java/security/SecureRandom.java     11 Jan 2003 03:39:30 -0000
@@ -358,9 +358,13 @@
     int ret = 0;
 
     for (int i = 0; i < tmp.length; i++)
-      ret |= tmp[i] << (8 * i);
+      ret |= tmp[i] & 0xFF << (8 * i);
 
-    return ret;
+    int mask = 0;
+    for (int i = 0; i < numBits; i++)
+      mask |= 1 << i;
+
+    return ret & mask;
   }
 
   /**
>Release-Note:
>Audit-Trail:
>Unformatted:


Index Nav: [Date Index] [Subject Index] [Author Index] [Thread Index]
Message Nav: [Date Prev] [Date Next] [Thread Prev] [Thread Next]