javascriptrandomsalt-cryptographyrhinosecure-random

How can we generate Random Salt of 32 bytes in Rhino JS


I am trying to generate a random salt of 32 bytes size. But my JS engine Rhino 1.7.13 doesn't support SecureRandom class.

Below is the code snippet of the same.

function getSalt() {
    var random = new SecureRandom();
    var salt1 = new Array(32);
    random.nextBytes(salt1);
    return salt1;
}

Error logged as below.

java.util.concurrent.ExecutionException: javax.script.ScriptException: ReferenceError: "SecureRandom" is not defined.

Also, rhino js engine does not allow any import or load of external library. Is there a way we can generate secure random salts in Rhino?


Solution

  • For SecureRandom use the fully qualified name java.security.SecureRandom. And the byte array has to be a Java byte array, otherwise you'll get an error:

    Cannot convert org.mozilla.javascript.NativeArray@6b419da to byte[]

    I found this answer from Tomasz Gawel, which shows how to create a Java byte array in Rhino.

    With the above-mentioned modifications, the complete script is:

    function getSalt() {
        var random = new java.security.SecureRandom();
        var salt1 = java.lang.reflect.Array.newInstance(java.lang.Byte.TYPE, 32)
        random.nextBytes(salt1);
        return salt1;
    }
    
    saltB64 = java.lang.String(java.util.Base64.getEncoder().encode(getSalt()))
    print(saltB64)