在java中利用rhino执行javascript

以rhino中执行QQ邮箱的safeauth.js为例

js代码地址:http://res.qqmail.com/zh_CN/htmledition20091127/js/safeauth.js

 

(1)导入相应类

import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;

import com.sun.phobos.script.javascript.RhinoScriptEngineFactory;

 

(2)解析JS

ScriptEngineManager engineManager = new ScriptEngineManager();
engineManager.registerEngineExtension("js", new RhinoScriptEngineFactory());
ScriptEngine engine = engineManager.getEngineByName("js");
InputStream ins = getClass().getResourceAsStream("/safeauth.js");
InputStreamReader insReader = new InputStreamReader(ins);
engine.eval(insReader);

 

会报错,说找不到window,navigator对象

这是因为rhino只提供了执行脚本的引擎环境,没有提供类似浏览器的host环境,所以当然找不到这两个对象

 

将相应的带有window,navigator的行注释掉,并加入以下代码,构成新的safeauth.js文件:

//-- encrypt password --// function encryptPassword(pp, PublicKey, PublicTs) { print("pp=" + pp + "/n"); print("PublicKey=" + PublicKey + "/n"); print("PublicTs=" + PublicTs + "/n"); var RSA = new RSAKey(); RSA.setPublic(PublicKey, "10001"); var Res = RSA.encrypt(pp + '/n' + PublicTs + '/n'); if (Res){ return hex2b64(Res); } else { return "EncodingPasswordError"; } }

 

(3)执行JS:

engine.eval("var t=encryptPassword('" + pp + "','" + publicKey + "','" + publicTs + "');");
String p = engine.get("t").toString();

 

传入pp(密码域值),publicKey和publicTs(这两个值从http://mail.qq.com/cgi-bin/loginpage页面内容得到),即可以计算编码后的密码。

 

你可能感兴趣的:(JavaScript,java,String,浏览器,import,hex)