2018-05-21 21:08:24 +02:00
/ * *
* @ author n1474335 [ n1474335 @ gmail . com ]
* @ copyright Crown Copyright 2016
* @ license Apache - 2.0
* /
2019-07-09 13:23:59 +02:00
import Operation from "../Operation.mjs" ;
import Utils from "../Utils.mjs" ;
2020-12-11 18:58:23 +01:00
import forge from "node-forge" ;
2018-05-21 21:08:24 +02:00
import BigNumber from "bignumber.js" ;
2019-07-09 13:23:59 +02:00
import { isWorkerEnvironment } from "../Utils.mjs" ;
2018-05-21 21:08:24 +02:00
/ * *
* Pseudo - Random Number Generator operation
* /
class PseudoRandomNumberGenerator extends Operation {
/ * *
* PseudoRandomNumberGenerator constructor
* /
constructor ( ) {
super ( ) ;
this . name = "Pseudo-Random Number Generator" ;
this . module = "Ciphers" ;
this . description = "A cryptographically-secure pseudo-random number generator (PRNG).<br><br>This operation uses the browser's built-in <code>crypto.getRandomValues()</code> method if available. If this cannot be found, it falls back to a Fortuna-based PRNG algorithm." ;
2018-08-21 20:07:13 +02:00
this . infoURL = "https://wikipedia.org/wiki/Pseudorandom_number_generator" ;
2018-05-21 21:08:24 +02:00
this . inputType = "string" ;
this . outputType = "string" ;
this . args = [
{
"name" : "Number of bytes" ,
"type" : "number" ,
"value" : 32
} ,
{
"name" : "Output as" ,
"type" : "option" ,
"value" : [ "Hex" , "Integer" , "Byte array" , "Raw" ]
}
] ;
}
/ * *
* @ param { string } input
* @ param { Object [ ] } args
* @ returns { string }
* /
run ( input , args ) {
const [ numBytes , outputAs ] = args ;
let bytes ;
2019-07-05 11:17:52 +02:00
if ( isWorkerEnvironment ( ) && self . crypto ) {
2018-05-21 21:08:24 +02:00
bytes = self . crypto . getRandomValues ( new Uint8Array ( numBytes ) ) ;
bytes = Utils . arrayBufferToStr ( bytes . buffer ) ;
} else {
bytes = forge . random . getBytesSync ( numBytes ) ;
}
let value = new BigNumber ( 0 ) ,
i ;
switch ( outputAs ) {
case "Hex" :
return forge . util . bytesToHex ( bytes ) ;
case "Integer" :
for ( i = bytes . length - 1 ; i >= 0 ; i -- ) {
value = value . times ( 256 ) . plus ( bytes . charCodeAt ( i ) ) ;
}
return value . toFixed ( ) ;
case "Byte array" :
return JSON . stringify ( Utils . strToCharcode ( bytes ) ) ;
case "Raw" :
default :
return bytes ;
}
}
}
export default PseudoRandomNumberGenerator ;