Ad

How Can We Generate Random Salt Of 32 Bytes In Rhino JS

- 1 answer

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?

Ad

Answer

For SecureRandom use the Java namespace. And the byte array has to be a Java byte array, otherwise you'll get an error:

Cannot convert [email protected] to byte[]

I found this answer from Tomasz Gawel, which shows how to declare 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)
Ad
source: stackoverflow.com
Ad