简体   繁体   中英

Unable to execute web-crypto script from java program

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

tl;dr use javafx 2 https://github.com/openjdk/jfx/search?q=document , https://stackoverflow.com/a/11266979/11711280

WebEngine webEngine = webView.getEngine();
webEngine.getLoadWorker().stateProperty().addListener(...)
webEngine.loadContent("load('" + scriptPath + "')");

However: " The full Oracle Java Runtime 8 ships with Nashorn." " Oracle Java dev 1.8 comes with its own bundled Java FX version , which generally can't be overridden. To use Java FX11, you will need to run the project with Java 11 and set the System property java.library.path to the location of the FX framework."

String scriptPath = "/home/rajasekhar/Desktop/webcrypto.js";
function ScriptWindow(scriptPath){
  return eval(scriptPath);
}.call({window:{}},[...(args=[])]);

I would expect static mutable ScriptEngine scope

engine.put("window", {});
engine.eval("load('" + scriptPath + "')");

or for all ScriptEngineManager engines

ScriptContext ctx = new SimpleScriptContext();
Bindings globalBindings = new SimpleBindings();
ctx.setBindings(globalBindings, ScriptContext.GLOBAL_SCOPE);
ctx.setAttribute("window", {}, ScriptContext.GLOBAL_SCOPE);

to be accessible in the function over int declarations (or class instantiations) yet https://stackoverflow.com/a/53561009/11711280 seems like you can set initial window that web-crypto might append.

public class Document {
};
Document window = new Document();

Hard to tell if more than mutable window or document properties are required here https://github.com/w3c/webcrypto/blob/main/spec/dfn.js

" When a script attempts to access a global variable not defined within it, nashorn searches for the variable in Bindings of the current ScriptContext used."

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM