1

Java 代码:

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 代码

"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;
};

错误:

线程“main”javax.script.ScriptException 中的异常:ReferenceError:“window”未在 jdk.nashorn.api.scripting.NashornScriptEngine.throwAsScriptException(NashornScriptEngine. java:470) 在 jdk.nashorn.api.scripting.NashornScriptEngine.invokeImpl(NashornScriptEngine.java:392) 在 jdk.nashorn.api.scripting.NashornScriptEngine.invokeMethod(NashornScriptEngine.java:199) 在 WebCryptoInvoke.main(WebCryptoInvoke.java :20) 原因:/home/rajasekhar/Desktop/webcrypto.js:9 ReferenceError:“窗口”未在 jdk.nashorn 的 jdk.nashorn.internal.runtime.ECMAErrors.error(ECMAErrors.java:57) 中定义。 jdk.nashorn.internal.runtime.ECMAErrors 处的 internal.runtime.ECMAErrors.referenceError(ECMAErrors.java:319)。jdk.nashorn.internal.objects.Global 的参考错误(ECMAErrors.java:291)。jdk.nashorn.internal.scripts.Script的 noSuchProperty (Global.java:1441)$Recompilation$2$86$webcrypto.generateKeyPair(/home/rajasekhar/Desktop/webcrypto.js:9) 在 jdk.nashorn.internal.runtime.ScriptFunctionData .invoke(ScriptFunctionData.java:637) 在 jdk.nashorn.internal.runtime.ScriptFunction.invoke(ScriptFunction.java:494) 在 jdk.nashorn.internal.runtime.ScriptRuntime.apply(ScriptRuntime.java:393) 在 jdk。 nashorn.api.scripting.ScriptObjectMirror.callMember(ScriptObjectMirror.java:199) 在 jdk.nashorn.api.scripting.NashornScriptEngine.invokeImpl(NashornScriptEngine.java:386) ... 2 更多

4

0 回答 0