Java Code:
import javax.script.Invocable;
import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
public class WebCryptoInvoke {
public static void main(String[] args) throws Exception {
ScriptEngineManager manager = new ScriptEngineManager();
ScriptEngine engine = manager.getEngineByName("JavaScript");
if (!(engine instanceof Invocable)) {
System.out.println("Invoking methods is not supported.");
return;
}
Invocable inv = (Invocable) engine;
String scriptPath = "/home/rajasekhar/Desktop/webcrypto.js";
engine.eval("load('" + scriptPath + "')");
Object webCrypto = engine.get("webcrypto");
Object result = inv.invokeMethod(webCrypto, "generateKeyPair");
System.out.println(result);
}
}
JavaScript Code:
"use strict";
var webcrypto = new Object();
webcrypto.generateKeyPair = function ()
{
var result = {};
window.crypto.subtle.generateKey(
{
name: "RSASSA-PKCS1-v1_5",
modulusLength: 2048, //can be 1024, 2048, or 4096
publicExponent: new Uint8Array([0x01, 0x00, 0x01]),
hash: {name: "SHA-256"}, //can be "SHA-1", "SHA-256", "SHA-384", or "SHA-512"
},
true, //whether the key is extractable (i.e. can be used in exportKey)
["sign", "verify"] //can be any combination of "sign" and "verify"
)
.then(function(key){
//returns a keypair object
console.log(key);
console.log(key.publicKey);
console.log(key.privateKey);
result[0] = key.publicKey;
result[1] = key.privateKey;
})
.catch(function(err){
console.error(err);
});
return result;
};
Error:
Exception in thread "main" javax.script.ScriptException: ReferenceError: "window" is not defined in /home/rajasekhar/Desktop/webcrypto.js at line number 9 at jdk.nashorn.api.scripting.NashornScriptEngine.throwAsScriptException(NashornScriptEngine.java:470) at jdk.nashorn.api.scripting.NashornScriptEngine.invokeImpl(NashornScriptEngine.java:392) at jdk.nashorn.api.scripting.NashornScriptEngine.invokeMethod(NashornScriptEngine.java:199) at WebCryptoInvoke.main(WebCryptoInvoke.java:20) Caused by: /home/rajasekhar/Desktop/webcrypto.js:9 ReferenceError: "window" is not defined at jdk.nashorn.internal.runtime.ECMAErrors.error(ECMAErrors.java:57) at jdk.nashorn.internal.runtime.ECMAErrors.referenceError(ECMAErrors.java:319) at jdk.nashorn.internal.runtime.ECMAErrors.referenceError(ECMAErrors.java:291) at jdk.nashorn.internal.objects.Global.noSuchProperty(Global.java:1441) at jdk.nashorn.internal.scripts.Script$Recompilation$2$86$webcrypto.generateKeyPair(/home/rajasekhar/Desktop/webcrypto.js:9) at jdk.nashorn.internal.runtime.ScriptFunctionData.invoke(ScriptFunctionData.java:637) at jdk.nashorn.internal.runtime.ScriptFunction.invoke(ScriptFunction.java:494) at jdk.nashorn.internal.runtime.ScriptRuntime.apply(ScriptRuntime.java:393) at jdk.nashorn.api.scripting.ScriptObjectMirror.callMember(ScriptObjectMirror.java:199) at jdk.nashorn.api.scripting.NashornScriptEngine.invokeImpl(NashornScriptEngine.java:386) ... 2 more