@@ -131,22 +131,28 @@ public function hash160($data)
131131 }
132132
133133 /**
134+ * Generates a random 256 bytes hexadecimal encoded string that is smaller than n
135+ *
134136 * @param string $extra
135137 * @return string Hex
136138 * @throws \Exception
137139 */
138140 public function generateRandom256BitsHexaString ($ extra = 'FkejkzqesrfeifH3ioio9hb55sdssdsdfOO:ss ' )
139141 {
140- $ bytes = openssl_random_pseudo_bytes (256 , $ cStrong );
141- $ hex = bin2hex ($ bytes );
142- $ random = $ hex . microtime (true ).rand (100000000000 , 1000000000000 ) . $ extra ;
143-
144- if (!$ cStrong )
142+ do
145143 {
146- throw new \Exception ('Your system is not able to generate strong enough random numbers ' );
147- }
144+ $ bytes = openssl_random_pseudo_bytes (256 , $ cStrong );
145+ $ hex = bin2hex ($ bytes );
146+ $ random = $ hex . microtime (true ) . rand (100000000000 , 1000000000000 ) . $ extra ;
147+
148+ if (!$ cStrong ) {
149+ throw new \Exception ('Your system is not able to generate strong enough random numbers ' );
150+ }
151+ $ res = $ this ->hash256 ($ random );
148152
149- return $ this ->hash256 ($ random );
153+ } while (gmp_cmp (gmp_init ($ res , 16 ), gmp_sub ($ this ->n , gmp_init (1 , 10 ))) == 1 ); // make sure the generate string is smaller than n
154+
155+ return $ res ;
150156 }
151157
152158 /***
@@ -789,11 +795,7 @@ public function getPrivateKey()
789795 */
790796 public function generateRandomPrivateKey ($ extra = 'FSQF5356dsdsqdfEFEQ3fq4q6dq4s5d ' )
791797 {
792- //private key has to be passed as an hexadecimal number
793- do { //generate a new random private key until to find one that is valid
794- $ this ->k = $ this ->generateRandom256BitsHexaString ($ extra );
795-
796- } while (gmp_cmp (gmp_init ($ this ->k , 16 ), gmp_sub ($ this ->n , gmp_init (1 , 10 ))) == 1 );
798+ $ this ->k = $ this ->generateRandom256BitsHexaString ($ extra );
797799 }
798800
799801 /***
0 commit comments