8132330: Ineffective SecureRandom usage in RSA encoding with PKCS1Padding
authorweijun
Sat, 15 Aug 2015 21:14:08 +0800
changeset 32212 9ced42a5a609
parent 32211 dc60c4df6b75
child 32213 acd9aab4ae86
8132330: Ineffective SecureRandom usage in RSA encoding with PKCS1Padding Reviewed-by: weijun Contributed-by: Sergey Kuksenko <sergey.kuksenko@oracle.com>
jdk/src/java.base/share/classes/sun/security/rsa/RSAPadding.java
--- a/jdk/src/java.base/share/classes/sun/security/rsa/RSAPadding.java	Sat Aug 15 04:38:51 2015 +0000
+++ b/jdk/src/java.base/share/classes/sun/security/rsa/RSAPadding.java	Sat Aug 15 21:14:08 2015 +0800
@@ -319,18 +319,17 @@
             }
             // generate non-zero padding bytes
             // use a buffer to reduce calls to SecureRandom
-            byte[] r = new byte[64];
-            int i = -1;
-            while (psSize-- > 0) {
-                int b;
-                do {
-                    if (i < 0) {
-                        random.nextBytes(r);
-                        i = r.length - 1;
+            while (psSize > 0) {
+                // extra bytes to avoid zero bytes,
+                // number of zero bytes <= 4 in 98% cases
+                byte[] r = new byte[psSize + 4];
+                random.nextBytes(r);
+                for (int i = 0; i < r.length && psSize > 0; i++) {
+                    if (r[i] != 0) {
+                        padded[k++] = r[i];
+                        psSize--;
                     }
-                    b = r[i--] & 0xff;
-                } while (b == 0);
-                padded[k++] = (byte)b;
+                }
             }
         }
         return padded;