RandomOrg RNG wrapper

Flash 10+

August 2016

Just discovred https://www.random.org/ provides a free API.
In the webTool menu there is a link the the “API to automated client” and on the page there is get “beta key button”, this key allow you to freely do 1000 requests/day.

Download the project
Download

Note that you have to claim your free API key and paste it in the call method of the RandomOrg.as Class.

Test project

package
{
import flash.display.Sprite;
import flash.events.ErrorEvent;
import flash.events.Event;
import flash.events.MouseEvent;
import org.random.RandomOrg;
import org.random.RandomOrgResult;

/**
* ...
* @author YopSolo
*/
public class Main extends Sprite
{
//
public function Main()
{
if (stage) init();
else addEventListener(Event.ADDED_TO_STAGE, init);
}

private function init(e:Event = null):void
{
removeEventListener(Event.ADDED_TO_STAGE, init);
// entry point
RandomOrg.loader.addEventListener(Event.COMPLETE, onComplete);
RandomOrg.loader.addEventListener(ErrorEvent.ERROR, onError);
// ... here all URLLoader error handling

stage.addEventListener(MouseEvent.CLICK, _onClick);
}

private function _onClick(e:MouseEvent):void
{
// Tests basic methods
RandomOrg.generateIntegers({n:10, min: 0, max: 100, replacement: false});
//RandomOrg.generateDecimalFractions({n: 8, decimalPlaces: 8, replacement: true});
//RandomOrg.generateGaussians({n: 10, mean: 100, standardDeviation: 100, significantDigits: 5});
//RandomOrg.generateStrings({n: 3, length: 10, characters: "&é'(-è_çà)AZERTYUIOPMLKJHGFDSQWXCVBN,;:!<>", replacement: false});
//RandomOrg.generateUUIDs({n: 3});
//RandomOrg.generateBlobs({n: 1, size: 256, format:"base64"});
//RandomOrg.getUsage();

// generate an error
//RandomOrg.generateIntegers({n:-10, min: "bablabla", max: "!", no_replacement: false, hey:111});
}

private function onComplete(e:Event):void
{
var ror:RandomOrgResult = new RandomOrgResult(RandomOrg.loader.data);
trace(ror);
}

private function onError(err:ErrorEvent):void
{
throw new Error(err);
}
}

}

RandomOrg Wrapper

package org.random
{
import flash.display.Loader;
import flash.events.ErrorEvent;
import flash.events.Event;
import flash.events.EventDispatcher;
import flash.net.URLLoader;
import flash.net.URLRequest;
import flash.net.URLRequestHeader;
import flash.net.URLRequestMethod;
import org.random.RandomOrgResult;

/**
* ...
* @author YopSolo
* randomOrg async RNG
* v 0.1.0
*/
public class RandomOrg
{
private static var _loader:URLLoader = new URLLoader;

public function RandomOrg()
{
}

/**
* visit https://api.random.org/json-rpc/1/
* and click the Get Beta key button
* you can make 1000 request/day for free
* @param	methodName
* @param	parameters
*/
private static function call(methodName:String, parameters:Object = null):void
{
const API_KEY:String = "your-api-key-here";
const INVOKE_URL:String = "https://api.random.org/json-rpc/1/invoke";

var request:URLRequest = new URLRequest();
request.method = URLRequestMethod.POST;
request.requestHeaders = [new URLRequestHeader("Content-type", "application/json-rpc")];
request.url = INVOKE_URL;

// create the json data
var json:Object = new Object();
json.jsonrpc = "2.0";
json.method = methodName;
// copy the ID then delete it (to avoid error code -32602 https://api.random.org/json-rpc/1/error-codes)
json.id = (parameters.id) ? parameters.id : new Date();
delete parameters.id;

// add the API key
parameters.apiKey = API_KEY;
json.params = parameters;

request.data = JSON.stringify(json);

_loader.load(request);
}

/**
* @see https://api.random.org/json-rpc/1/basic
* generateIntegers method
*
* obj.n How many random integers you need. Must be within the [1,1e4] range.
* obj.min The lower boundary for the range from which the random numbers will be picked. Must be within the [-1e9,1e9] range.
* obj.max The upper boundary for the range from which the random numbers will be picked. Must be within the [-1e9,1e9] range.
* obj.replacement (default value true)
* obj.base (default value 10)
* obj.id (optional request id)
* exemple :
* RandomOrg.generateIntegers({n: 10, min: 0, max: 100, replacement: false});
*
* will ask to generate 10 unique int between 0 and 100 (using base 10)
* > 65,45,71,5,15,72,22,76,2,90
* @param	obj
*/
public static function generateIntegers(obj:Object):void
{
call("generateIntegers", obj);
}

/**
* obj.n How many random decimal fractions you need. Must be within the [1,1e4] range.
* obj.decimalPlaces The number of decimal places to use. Must be within the [1,20] range.
* obj.replacement (default value true)
* obj.id (optional request id)
*
* exemple :
* RandomOrg.generateDecimalFractions({n: 8, decimalPlaces: 8, replacement: true});
*
* will ask to generate 8 number between 0 and 1 with 8 decimals
* > 0.67994134,0.17491799,0.87808314,0.78948193,0.89419947,0.33027066,0.38379519,0.29417465
* @param	obj
*/
public static function generateDecimalFractions(obj:Object):void
{
call("generateDecimalFractions", obj);
}

/**
* obj.n How many random numbers you need. Must be within the [1,1e4] range.
* obj.mean The distribution's mean. Must be within the [-1e6,1e6] range.
* obj.standardDeviation The distribution's standard deviation. Must be within the [-1e6,1e6] range.
* obj.significantDigits The number of significant digits to use. Must be within the [2,20] range.
* obj.id (optional request id)
* There are no optional parameters. In particular, Gaussians are always picked with replacement.
*
* exemple :
* RandomOrg.generateGaussians( { n:10, mean:100, standardDeviation:100, significantDigits:5 } );
* will ask to generate 10, 5-digits number with a mean of 100 and a standard deviation of 100
* > 115.46,39.607,131.27,281.66,96.91,223.33,-47.597,79.954,94.234,-18.355
* @param	obj
*/
public static function generateGaussians(obj:Object):void
{
call("generateGaussians", obj);
}

/**
* obj.n How many random strings you need. Must be within the [1,1e4] range.
* obj.length The length of each string. Must be within the [1,20] range. All strings will be of the same length
* obj.characters A string that contains the set of characters that are allowed to occur in the random strings. The maximum number of characters is 80.
* obj.replacement (default value true)
* obj.id (optional request id)
*
* exemple :
* RandomOrg.generateStrings({n: 3, length: 10, characters:"&é"'(-è_çà)AZERTYUIOPMLKJHGFDSQWXCVBN,;:!<>", replacement: false});
* will ask to generate 3 unique 10 characters long string using this alphabet "&é"'(-è_çà)AZERTYUIOPMLKJHGFDSQWXCVBN,;:!<>", witch could be cool to generate random password
* > 'QGàKO;F;R,QQK)NTL>)<,;HPV:IJL>T
* @param	obj
*/
public static function generateStrings(obj:Object):void
{
call("generateStrings", obj);
}

/**
* obj.n How many random UUIDs you need. Must be within the [1,1e3] range.
* obj.id (optional request id)
*
* exemple :
* RandomOrg.generateUUIDs({n: 3});
* will ask to generate 3 UUIDs
* > 76bc767d-1716-4839-9d8e-da823896fcc3,0cbc6497-cd00-4bf5-8aa6-848d0f9e6069,7b48d703-fdd7-40e7-aa93-349111f7b20d
* @param	obj
*/
public static function generateUUIDs(obj:Object):void
{
call("generateUUIDs", obj);
}

/**
* obj.n How many random blobs you need. Must be within the [1,100] range.
* obj.size The size of each blob, measured in bits. Must be within the [1,1048576] range and must be divisible by 8.
* obj.format  (default value base64) Specifies the format in which the blobs will be returned. Values allowed are base64 and hex.
* obj.id (optional request id)
*
* exemple :
* RandomOrg.generateBlobs({n: 1, size: 32, format:"base64"});
* will ask to generate 1 256 bit Binary Large OBjects in base64
* > +qPww+QRkZGwWVYOGcnsDrFj13nw4EFcmcaGRn3bsns=
* @param	obj
*/
public static function generateBlobs(obj:Object):void
{
call("generateBlobs", obj);
}

/**
* obj.id (optional request id)
* This method returns information related to the the usage of a given API key. Your client must set the method property of its JSON-RPC request object to getUsage. The request must also contain an id member, which will be returned in the response.
*/
public static function getUsage(obj:Object = null):void
{
if (obj == null)
{
obj = {};
}
call("getUsage", obj);
}

static public function get loader():URLLoader
{
return _loader;
}
}

}

RandomOrgResult Helper class

package org.random
{

/**
* ...
* @author YopSolo
* randomOrg async RNG
* v 0.1.0
*/
public class RandomOrgResult
{
private var _bitsUsed:uint = 0;
private var _bitsLeft:uint = 0;
private var _requestsLeft:uint = 0;
private var _advisoryDelay:uint = 0;
private var _data:Array;
private var _completionTime:String = "-";
private var _id:* = "-";
private var _status:String = "-";
private var _creationTime:String = "-";
private var _totalBits:uint = 0;
private var _totalRequests:int = 0;

public function RandomOrgResult(randomOrgDataString:String)
{
var r:Object = JSON.parse(randomOrgDataString);

// error
if (r.error)
{
_data = [];
_data.push(r);
_data.push("\n");
_data.push("https://api.random.org/json-rpc/1/error-codes");
_data.push("\n");
_data.push("rawString :" + randomOrgDataString);
}
else
{
// valid resut

_bitsLeft = r.result.bitsLeft;
_requestsLeft = r.result.requestsLeft;
_id = r.id;
// if it's a getUsage method
if (r.result.status)
{
_status = r.result.status;
_creationTime = r.result.creationTime;
_totalBits = r.result.totalBits;
_totalRequests = r.result.totalRequests;
}
else
{
// it's a regular method call
_bitsUsed = r.result.bitsUsed;
_advisoryDelay = r.result.advisoryDelay;
_data = r.result.random.data;
_completionTime = r.result.random.completionTime;
}
}

}

/**
* An integer containing the number of true random bits used to complete this request.
*/
public function get bitsUsed():uint
{
return _bitsUsed;
}

/**
* An integer containing the (estimated) number of remaining API requests available to the client.
*/
public function get requestsLeft():uint
{
return _requestsLeft;
}

/**
* An integer containing the recommended number of milliseconds that the client should delay before issuing another request.
*/
public function get advisoryDelay():uint
{
return _advisoryDelay;
}

/**
* An integer containing the (estimated) number of remaining true random bits available to the client.
*/
public function get bitsLeft():uint
{
return _bitsLeft;
}

/**
* An array containing the sequence of numbers requested. If the request specified base 10 (or did not specify a base and therefore defaults to 10),
* the elements in the array will be integers. Because JSON (according to RFC4627) only allows numbers to be written as decimal,
* the numbers will be typed as strings if a different base than 10 was specified in the request. Numbers in any base other than 10 will
* be padded with leading zeros up to the width required to display the chosen range.
*/
public function get data():Array
{
return _data ? _data : [];
}

/**
* A string containing the timestamp in ISO 8601 format at which the request was completed.
*/
public function get completionTime():String
{
return _completionTime;
}

/**
* return the the id passed when request was done
*/
public function get id():*
{
return _id;
}

/**
* A string indicating the API key's current status, which may be stopped, paused or running. An API key must be running for it to be able to serve requests.
*/
public function get status():String
{
return _status;
}

/**
* only for getUsage method
* An integer containing the number of bits used by this API key since it was created.
*/
public function get totalBits():uint
{
return _totalBits;
}

/**
* only for getUsage method
* An integer containing the number of requests used by this API key since it was created.
*/
public function get totalRequests():int
{
return _totalRequests;
}

/**
* only for getUsage method
* A string containing the timestamp in ISO 8601 format at which the API key was created.
*/
public function get creationTime():String
{
return _creationTime;
}

public function toString():String
{
if (data.length > 0)
{
return String(data);
}
else
{
return "status: " + status + "\ncreationTime: " + creationTime + "\nbitsLeft: " + bitsLeft + "\nrequestsLeft: " + requestsLeft + "\ntotalBits: " + totalBits + "\ntotalRequests: " + totalRequests;
}
}

}

}