在java代码同一目录下,存在已js文件,里面编辑好需要调用的js函数
function encrypt(str,key){
var code ='';
var c = str.split('');
var k = key.split('');
for(var i=0; i<c.length; i++){
var hc = c[i].charCodeAt();
var ki = i;
if(i >= k.length){
ki = i % k.length;
}
var kt = k[ki].charCodeAt() - 97;
if(hc >= 97 && hc <= 122){
hc = 97 + (((hc -97) + kt) % 26);
}
if(hc >= 65 && hc <= 90){
hc = 65 + (((hc - 65) + kt) % 26);
}
if(hc >=48 && hc<=57){
if(kt >= 10){
kt = 10;
}
hc = 48 + (((hc - 48) + kt) % 10);
}
var temp = String.fromCharCode(hc);
code += temp;
}
return code;
}
新建接口用于调用js函数
package com.*******.crawl.crawlers.mobile.hl;
public interface IHlMobilePsc {
/**
* 登录黑龙江移动服务密码明文加密.
* @param passwd 明文密码
* @param pscToken token串
* @return
*/
public String encrypt(String passwd, String pscToken);
}
接口实现
package com.*****.crawl.crawlers.mobile.hl;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.script.Invocable;
import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
import javax.script.ScriptException;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
public class HlMobilePsc {
private static Logger logger = LoggerFactory.getLogger(HlMobilePsc.class);
private static ScriptEngine engine = new ScriptEngineManager().getEngineByName("js");
private HlMobilePsc(){
// nothing to do
}
public static IHlMobilePsc loadJs() {
IHlMobilePsc hlMobilePsc = null;
try (InputStream is = IHlMobilePsc.class.getResourceAsStream("Psc.js")){//需要调用的js函数所在文件
engine.eval(new BufferedReader(new InputStreamReader(is)));
if (engine instanceof Invocable) {
Invocable invocable = (Invocable) engine;
// 返回一个接口的实现,该接口使用解释器中编译的函数
hlMobilePsc = invocable.getInterface(IHlMobilePsc.class);
}
} catch (IOException | ScriptException e) {
logger.error(e.getMessage(), e);
}
return hlMobilePsc;
}
/**
* 调用JS加密密码.
* @param password 密码明文
* @param pscToken token
* @return 加密后
*/
public static String encrypt(String password, String pscToken){
return HlMobilePsc.loadJs().encrypt(password, pscToken);
}
}
执行调用
//加密密码
String password = HlMobilePsc.encrypt(password, pscToken);