True random numbers in flash/as3: measuring clock drift

This is one of those things that I will surely never come to use; it crossed my mind a couple of days ago though, and I though it would be worth putting together and then up here.

There are a many potential sources of true randomness in flash. An example would be listening for microphone or camera noise; such an approach is however contingent on access to a|v hardware. Entropy can also be pooled from simple user interactions, such as mouse movements. Still, any entropy pool could run dry after a series of requests if it is not given the chance to rebuild.

Measuring clock/cpu drift is very expensive, but provides pretty unpredictable output and, because random bits are generated and not pooled, does not limit the number of random bits that one could obtain at any given time.

package com.controul.math.rng
	import flash.utils.getTimer;
	public class ClockDrift
		public function random ( bits : uint = 32 ) : uint
			if ( bits > 32 )
				bits = 32;
			var	r : uint = 0,
				i : uint = 0,
				t : uint = getTimer ();
			for ( ;; )
				if ( t != ( t = getTimer () ) )
					if ( i & 1 )
						r |= 1;
					bits --;
					if ( bits > 0 )
						i = 0;
						r <<= 1;
				i ++;
			return r;

What the algorithm does is to count the number of loop iterations that happen during a millisecond, and then to set the next bit to true if this count is odd, or to false if it’s even. As it takes a millisecond to produce every single random bit, a random uint (zero to 0xffffffff) takes 32 milliseconds to get generated.

Such an extremely slow solution may be most useful as a last resort for keeping an entropy pool from running dry; the pool can rely on a mix of other stuff, like user mouse movements, download speed sampling, a/v hardware noise, enterframe timing, etc to provide enough random bits for occasional requests.

Anyway, only hardcore security stuff, such as the as3crypto framework, needs unpredictable ‘random’ number generation. For non-cryptographic uses, one should go for a regular prng, be it Math.random, or one with a specifiable seed value, such as the Park-Miller prng supplied by polygonal labs.


Bookmark and Share

0 Response to “True random numbers in flash/as3: measuring clock drift”

  • No Comments

Leave a Reply