Browse Source

提交开源任务材料

10.0
LAPTOP-SB56SG4Q\86185 3 years ago
parent
commit
14d67361b5
  1. BIN
      JSD-9008-需求确认书V.docx
  2. 5
      README.md
  3. BIN
      lib/bcpkix-jdk15on-1.64.jar
  4. BIN
      lib/bcprov-jdk15on-1.54.jar
  5. BIN
      lib/nimbus-jose-jwt-9.1.2.jar
  6. 20
      plugin.xml
  7. 22
      src/main/java/com/fr/plugin/gzwauth/config/InitializeMonitor.java
  8. 47
      src/main/java/com/fr/plugin/gzwauth/config/PluginSimpleConfig.java
  9. 170
      src/main/java/com/fr/plugin/gzwauth/filter/SSOFilter.java
  10. 178
      src/main/java/com/fr/plugin/gzwauth/utils/FRUtils.java
  11. 93
      src/main/java/com/fr/plugin/gzwauth/utils/Md5Util.java
  12. 94
      src/main/java/com/fr/plugin/gzwauth/utils/ResponseUtils.java
  13. 358
      src/main/java/com/fr/plugin/gzwauth/utils/SM3.java
  14. 145
      src/main/java/com/fr/plugin/gzwauth/utils/SM3Digest.java
  15. 20
      src/main/java/com/fr/plugin/gzwauth/utils/SM3Util.java
  16. 48
      src/main/java/com/fr/plugin/gzwauth/utils/TokenUtil.java
  17. 662
      src/main/java/com/fr/plugin/gzwauth/utils/Util.java
  18. 227
      src/main/java/com/fr/plugin/gzwauth/utils/Utils.java
  19. 95
      src/main/resources/com/fr/plugin/gzwauth/error.html

BIN
JSD-9008-需求确认书V.docx

Binary file not shown.

5
README.md

@ -1,3 +1,6 @@
# open-JSD-9008
JSD-9008 请求鉴权(SM3 + JWT)
JSD-9008 请求鉴权(SM3 + JWT)\
免责说明:该源码为第三方爱好者提供,不保证源码和方案的可靠性,也不提供任何形式的源码教学指导和协助!\
仅作为开发者学习参考使用!禁止用于任何商业用途!\
为保护开发者隐私,开发者信息已隐去!若原开发者希望公开自己的信息,可联系hugh处理。

BIN
lib/bcpkix-jdk15on-1.64.jar

Binary file not shown.

BIN
lib/bcprov-jdk15on-1.54.jar

Binary file not shown.

BIN
lib/nimbus-jose-jwt-9.1.2.jar

Binary file not shown.

20
plugin.xml

@ -0,0 +1,20 @@
<?xml version="1.0" encoding="UTF-8" standalone="no"?><plugin>
<id>com.fr.plugin.gzwauth</id>
<name><![CDATA[权限校验]]></name>
<active>yes</active>
<version>1.0.1</version>
<env-version>10.0</env-version>
<jartime>2018-07-31</jartime>
<vendor>fr.open</vendor>
<description><![CDATA[权限校验]]></description>
<change-notes><![CDATA[
]]></change-notes>
<main-package>com.fr.plugin.gzwauth</main-package>
<lifecycle-monitor class="com.fr.plugin.gzwauth.config.InitializeMonitor"/>
<extra-decision>
<GlobalRequestFilterProvider class="com.fr.plugin.gzwauth.filter.SSOFilter"/>
</extra-decision>
<function-recorder class="com.fr.plugin.gzwauth.config.PluginSimpleConfig"/>
</plugin>

22
src/main/java/com/fr/plugin/gzwauth/config/InitializeMonitor.java

@ -0,0 +1,22 @@
package com.fr.plugin.gzwauth.config;
import com.fr.plugin.context.PluginContext;
import com.fr.plugin.observer.inner.AbstractPluginLifecycleMonitor;
/**
* @author fr.open
* @version 10.0
* Created by fr.open on 2018-12-04
*/
public class InitializeMonitor extends AbstractPluginLifecycleMonitor {
@Override
public void afterRun(PluginContext pluginContext) {
PluginSimpleConfig.getInstance();
}
@Override
public void beforeStop(PluginContext pluginContext) {
}
}

47
src/main/java/com/fr/plugin/gzwauth/config/PluginSimpleConfig.java

@ -0,0 +1,47 @@
package com.fr.plugin.gzwauth.config;
import com.fr.config.*;
import com.fr.config.holder.Conf;
import com.fr.config.holder.factory.Holders;
import com.fr.intelli.record.Focus;
import com.fr.intelli.record.Original;
import com.fr.record.analyzer.EnableMetrics;
@Visualization(category = "权限校验配置")
@EnableMetrics
public class PluginSimpleConfig extends DefaultConfiguration {
private static volatile PluginSimpleConfig config = null;
@Focus(id="com.fr.plugin.gzwauth.config", text = "权限校验配置", source = Original.PLUGIN)
public static PluginSimpleConfig getInstance() {
if (config == null) {
config = ConfigContext.getConfigInstance(PluginSimpleConfig.class);
}
return config;
}
@Identifier(value = "checkTokenUrl", name = "校验链接", description = "校验链接", status = Status.SHOW)
private Conf<String> checkTokenUrl = Holders.simple("http://127.0.0.1:8088/check/checkToken");
public String getCheckTokenUrl() {
return checkTokenUrl.get();
}
public void setCheckTokenUrl(String url) {
this.checkTokenUrl.set(url);
}
@Override
public Object clone() throws CloneNotSupportedException {
PluginSimpleConfig cloned = (PluginSimpleConfig) super.clone();
// cloned.text = (Conf<String>) text.clone();
// cloned.count = (Conf<Integer>) count.clone();
// cloned.price = (Conf<Double>) price.clone();
// cloned.time = (Conf<Long>) time.clone();
// cloned.student = (Conf<Boolean>) student.clone();
return cloned;
}
}

170
src/main/java/com/fr/plugin/gzwauth/filter/SSOFilter.java

@ -0,0 +1,170 @@
package com.fr.plugin.gzwauth.filter;
import com.fr.decision.fun.impl.AbstractGlobalRequestFilterProvider;
import com.fr.json.JSONObject;
import com.fr.plugin.context.PluginContexts;
import com.fr.plugin.gzwauth.config.PluginSimpleConfig;
import com.fr.plugin.gzwauth.utils.FRUtils;
import com.fr.plugin.gzwauth.utils.TokenUtil;
import com.fr.plugin.gzwauth.utils.Utils;
import com.fr.record.analyzer.EnableMetrics;
import com.fr.security.JwtUtils;
import com.fr.stable.fun.Authorize;
import javax.servlet.FilterChain;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.URL;
import java.net.URLConnection;
@EnableMetrics
@Authorize(callSignKey = "com.fr.plugin.gzwauth")
public class SSOFilter extends AbstractGlobalRequestFilterProvider {
@Override
public String filterName() {
return "gzwssoFilter";
}
@Override
public String[] urlPatterns() {
return new String[]{"/*"};
}
@Override
public void doFilter(HttpServletRequest req, HttpServletResponse res, FilterChain chain ){
if(PluginContexts.currentContext().isAvailable()) {
PluginSimpleConfig psc = PluginSimpleConfig.getInstance();
//拿到参数
String sysId = req.getParameter("sysId");
String jwtToken = req.getParameter("jwtToken");
if(Utils.isNullStr(sysId) || Utils.isNullStr(jwtToken)){
release(req,res,chain);
return;
}
FRUtils.FRLogInfo("sysId:"+sysId+";token:"+jwtToken);
//访问接口
boolean success = checkToken(sysId,jwtToken, psc);
//判断
if (!success) {
Utils.toErrorPage(res, "/com/fr/plugin/gzwauth/error.html", null);
}
}
release(req,res,chain);
}
private boolean checkToken(String sysid,String token, PluginSimpleConfig psc) {
String url = psc.getCheckTokenUrl();
String result = sendGETSync(sysid,token,url);
if(Utils.isNullStr(result)){
return true;
}
JSONObject json = new JSONObject(result);
String code = json.getString("code");
if(code.equals("2")){
return false;
}
return true;
}
/**
* 发送请求
* @param sysId 系统id
* @param jwtToken token
* @param url 请求url
* @return
*/
private String sendGETSync(String sysId, String jwtToken, String url){
//参数拼接json
String parameterJson = "{\"sysId\":\""+sysId+"\",\"jwtToken\":\""+jwtToken+"\"}";
//发送请求
String result = sendPost(url, parameterJson,jwtToken);
return result;
}
public static String sendPost(String url, String param,String jwtToken) {
PrintWriter out = null;
BufferedReader in = null;
String result = "";
try {
URL realUrl = new URL(url);
// 打开和URL之间的连接
URLConnection conn = realUrl.openConnection();
// 设置通用的请求属性
//接收数据格式
conn.setRequestProperty("Accept", "*/*");
conn.setRequestProperty("connection", "Keep-Alive");
conn.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
//发送数据格式
conn.setRequestProperty("content-type", "application/json;charset=UTF-8");
conn.setRequestProperty("slw.jwt.token", jwtToken);
// 发送POST请求必须设置如下两行
conn.setDoOutput(true);
conn.setDoInput(true);
// 获取URLConnection对象对应的输出流
out = new PrintWriter(conn.getOutputStream());
// 发送请求参数
out.print(param);
// flush输出流的缓冲
out.flush();
// 定义BufferedReader输入流来读取URL的响应
in = new BufferedReader(
new InputStreamReader(conn.getInputStream()));
String line;
while ((line = in.readLine()) != null) {
result += line;
}
} catch (Exception e) {
FRUtils.FRLogError("发送 POST 请求出现异常!"+e.getMessage());
return "";
}
//使用finally块来关闭输出流、输入流
finally{
try{
if(out!=null){
out.close();
}
if(in!=null){
in.close();
}
}
catch(IOException ex){
FRUtils.FRLogError("发送 POST 请求出现异常!"+ex.getMessage());
return "";
}
}
return result;
}
private boolean isRelease(HttpServletRequest req) {
String url = FRUtils.getAllUrl(req);
FRUtils.FRLogInfo("requestUrl:"+url);
boolean isRemote = url.contains("remote");
boolean isLoginPage = url.contains("login")||url.contains("decision/file")||url.contains("decision/resource")||url.contains("decision/system")||url.contains("query/ip");
return isRemote || isLoginPage ;
}
//放行拦截器
private void release(HttpServletRequest req, HttpServletResponse res, FilterChain chain) {
try{
chain.doFilter(req,res);
}catch (Exception e){
FRUtils.FRLogInfo("拦截失败");
}
}
}

178
src/main/java/com/fr/plugin/gzwauth/utils/FRUtils.java

@ -0,0 +1,178 @@
package com.fr.plugin.gzwauth.utils;
import com.fr.base.TableData;
import com.fr.decision.authority.AuthorityContext;
import com.fr.decision.authority.data.User;
import com.fr.decision.webservice.login.LogInOutResultInfo;
import com.fr.decision.webservice.utils.DecisionServiceConstants;
import com.fr.decision.webservice.v10.login.LoginService;
import com.fr.decision.webservice.v10.login.event.LogInOutEvent;
import com.fr.decision.webservice.v10.user.UserService;
import com.fr.event.EventDispatcher;
import com.fr.file.TableDataConfig;
import com.fr.general.data.DataModel;
import com.fr.log.FineLoggerFactory;
import com.fr.script.Calculator;
import com.fr.stable.StringUtils;
import com.fr.stable.query.QueryFactory;
import com.fr.stable.query.restriction.RestrictionFactory;
import com.fr.web.utils.WebUtils;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.List;
public class FRUtils {
/**
* 判断用户是否存在
* @param userName
* @return
*/
public static boolean isUserExist(String userName){
if (StringUtils.isEmpty(userName)) {
return false;
} else {
try {
List var1 = AuthorityContext.getInstance().getUserController().find(QueryFactory.create().addRestriction(RestrictionFactory.eq("userName", userName)));
return var1 != null && !var1.isEmpty();
} catch (Exception var2) {
FineLoggerFactory.getLogger().error(var2.getMessage());
return false;
}
}
}
/**
* 判断是否登录FR
* @param req
* @return
*/
public static boolean isLogin(HttpServletRequest req){
return LoginService.getInstance().isLogged(req);
}
/**
* 帆软登录
* @param httpServletRequest
* @param httpServletResponse
* @param userName
* @param url
*/
public static void login(HttpServletRequest httpServletRequest,HttpServletResponse httpServletResponse,String userName,String url){
FineLoggerFactory.getLogger().info("FRLOG:用户名:"+userName);
FineLoggerFactory.getLogger().info("FRLOG:跳转链接:"+url);
//判断用户名是否为空
if(!Utils.isNullStr(userName)){
if(isUserExist(userName)){
String FRToken = "";
try {
HttpSession session = httpServletRequest.getSession(true);
FRToken = LoginService.getInstance().login(httpServletRequest, httpServletResponse, userName);
httpServletRequest.setAttribute(DecisionServiceConstants.FINE_AUTH_TOKEN_NAME,FRToken);
session.setAttribute(DecisionServiceConstants.FINE_AUTH_TOKEN_NAME, FRToken);
EventDispatcher.fire(LogInOutEvent.LOGIN,new LogInOutResultInfo(httpServletRequest,httpServletResponse,userName,true));
FineLoggerFactory.getLogger().info("FRLOG:登陆成功!");
if(!Utils.isNullStr(url)){
httpServletResponse.sendRedirect(url);
}
} catch (Exception e) {
ResponseUtils.failedResponse(httpServletResponse,"登录异常,请联系管理员!");
FineLoggerFactory.getLogger().info("FRLOG:登录异常,请联系管理员!");
FineLoggerFactory.getLogger().info("FRLOGException:"+e.getMessage());
}
}else{
ResponseUtils.failedResponse(httpServletResponse,"用户在报表系统中不存在!");
FineLoggerFactory.getLogger().info("FRLOG:用户在报表系统中不存在!");
}
}else{
ResponseUtils.failedResponse(httpServletResponse,"用户名不能为空!");
FineLoggerFactory.getLogger().info("FRLOG:用户名不能为空!");
}
}
/**
*
* @param httpServletRequest
* @param httpServletResponse
*/
public static void logout(HttpServletRequest httpServletRequest,HttpServletResponse httpServletResponse)
{
if(!isLogin(httpServletRequest)){
return ;
}
try {
LoginService.getInstance().logout(httpServletRequest,httpServletResponse);
} catch (Exception e) {
ResponseUtils.failedResponse(httpServletResponse,"登出异常,请联系管理员!");
FineLoggerFactory.getLogger().info("FRLOG:登出异常,请联系管理员!");
FineLoggerFactory.getLogger().info("FRLOGException:"+e.getMessage());
}
}
/**
* 打印FR日志
* @param message
*/
public static void FRLogInfo(String message){
FineLoggerFactory.getLogger().info("FRLOG:"+message);
}
/**
* 打印FR日志-error
* @param message
*/
public static void FRLogError(String message){
FineLoggerFactory.getLogger().error("FRLOG:"+message);
}
/**
* 根据用户名获取用户信息
* @param userName
* @return
*/
public static User getFRUserByUserName(String userName){
try {
return UserService.getInstance().getUserByUserName(userName);
} catch (Exception e) {
FRLogInfo("获取用户信息异常:"+e.getMessage());
}
return null;
}
/**
* 解密FR密码
* @param password
* @return
*/
// public static String decryptFRPsd(String password){
// FRLogInfo("解密密码:"+password);
// return TransmissionTool.decrypt(password);
// }
/**
* 获取带参数的访问链接
* @return
*/
public static String getAllUrl(HttpServletRequest httpServletRequest){
return WebUtils.getOriginalURL(httpServletRequest);
}
public static TableData getTableData(String serverDataSetName){
TableData userInfo = TableDataConfig.getInstance().getTableData("serverDataSetName");
// DataModel userInfoDM = userInfo.createDataModel(Calculator.createCalculator());
return userInfo;
}
}

93
src/main/java/com/fr/plugin/gzwauth/utils/Md5Util.java

@ -0,0 +1,93 @@
package com.fr.plugin.gzwauth.utils;
import java.io.File;
import java.io.FileInputStream;
import java.nio.MappedByteBuffer;
import java.nio.channels.FileChannel;
import java.security.MessageDigest;
/**
* 内容摘要工具类
*
* @since 1.0
* @author paladin
*/
public class Md5Util {
/**
* 生成MD5摘要信息
*
* @param sourceString
* @return
*/
public static String MD5Encode(String sourceString) {
String resultString = null;
try {
resultString = new String(sourceString);
MessageDigest md = MessageDigest.getInstance("MD5");
resultString = byte2hexString(md.digest(resultString.getBytes()));
} catch (Exception ex) {
}
return resultString;
}
/**
* 以字符串形式显示字节数组内容
*
* @param bytes
* @return
*/
public static final String byte2hexString(byte[] bytes) {
StringBuffer buf = new StringBuffer(bytes.length * 2);
for (int i = 0; i < bytes.length; i++) {
if (((int) bytes[i] & 0xff) < 0x10) {
buf.append("0");
}
buf.append(Long.toString((int) bytes[i] & 0xff, 16));
}
return buf.toString();
}
/**
* 对文件全文生成MD5摘要
*
* @param file
* 要加密的文件
* @return MD5摘要码
*/
public static String getMD5(File file) throws Exception {
FileInputStream in = new FileInputStream(file);
FileChannel ch = in.getChannel();
MappedByteBuffer byteBuffer = ch.map(FileChannel.MapMode.READ_ONLY, 0, file.length());
MessageDigest md = MessageDigest.getInstance("MD5");
md.update(byteBuffer);
return byte2hexString(md.digest());
}
/**
* 对一段String生成MD5加密信息
*
* @param message
* 要加密的String
* @return 生成的MD5信息
*/
public static String getMD5(String s) throws Exception {
if (s == null)
return "";
return getMD5(s.getBytes());
}
/**
* 对byte生成MD5加密信息
*
* @param bytes
* @return
*/
public static String getMD5(byte[] bytes) throws Exception {
if (bytes == null)
return "";
MessageDigest md = MessageDigest.getInstance("MD5");
md.update(bytes);
return byte2hexString(md.digest());
}
}

94
src/main/java/com/fr/plugin/gzwauth/utils/ResponseUtils.java

@ -0,0 +1,94 @@
package com.fr.plugin.gzwauth.utils;
import com.fr.json.JSONObject;
import com.fr.log.FineLoggerFactory;
import com.fr.web.utils.WebUtils;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;
public class ResponseUtils {
private static final int SUCCESS = 200;
private static final int FAILED = -1;
public static void successResponse(HttpServletResponse res, String body) {
response(res, body, SUCCESS);
}
public static void failedResponse(HttpServletResponse res, String body) {
response(res, body, FAILED);
}
private static void response(HttpServletResponse res, String body, int code) {
JSONObject object = new JSONObject();
PrintWriter pw;
try {
object.put("code", code);
object.put("data", body);
pw = WebUtils.createPrintWriter(res);
} catch (Exception e) {
FineLoggerFactory.getLogger().info(e.getMessage());
return;
}
res.setContentType("application/json;charset=utf-8");
String result = object.toString();
pw.println(result);
pw.flush();
pw.close();
}
public static void response(HttpServletResponse res,JSONObject json){
PrintWriter pw;
try {
pw = WebUtils.createPrintWriter(res);
} catch (Exception e) {
FineLoggerFactory.getLogger().info(e.getMessage());
return;
}
res.setContentType("application/json;charset=utf-8");
String result = json.toString();
pw.println(result);
pw.flush();
pw.close();
}
public static void responseXml(HttpServletResponse res,String xml){
PrintWriter pw;
try {
pw = WebUtils.createPrintWriter(res);
} catch (Exception e) {
FineLoggerFactory.getLogger().info(e.getMessage());
return;
}
res.setContentType("text/xml;charset=utf-8");
pw.println(xml);
pw.flush();
pw.close();
}
public static void setCSRFHeader(HttpServletResponse httpServletResponse){
httpServletResponse.setHeader("Access-Control-Allow-Origin", "*");
httpServletResponse.setHeader("Access-Control-Allow-Methods", "POST,GET,OPTIONS,DELETE,HEAD,PUT,PATCH");
httpServletResponse.setHeader("Access-Control-Max-Age", "36000");
httpServletResponse.setHeader("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept,Authorization,authorization");
}
public static void responseJsonp(HttpServletRequest req, HttpServletResponse res, JSONObject json){
PrintWriter pw;
try {
pw = WebUtils.createPrintWriter(res);
} catch (Exception e) {
FineLoggerFactory.getLogger().info(e.getMessage());
return;
}
res.setContentType("text/javascript;charset=utf-8;charset=utf-8");
String result = json.toString();
String jsonp=req.getParameter("callback");
pw.println(jsonp+"("+result+")");
pw.flush();
pw.close();
}
}

358
src/main/java/com/fr/plugin/gzwauth/utils/SM3.java

@ -0,0 +1,358 @@
package com.fr.plugin.gzwauth.utils;
public class SM3
{
/*public static final byte[] iv = { 0x2C, (byte) 0x91, (byte) 0xB4, 0x01,
(byte) 0xFC, 0x64, (byte) 0xB2, (byte) 0xCE, 0x7C, 0x4E,
(byte) 0xAE, (byte) 0xFB, (byte) 0xB1, 0x3B, (byte) 0xB6,
(byte) 0xD3, 0x17, 0x60, (byte) 0xB6, 0x35, (byte) 0xF3, 0x6F,
0x13, (byte) 0xEB, (byte) 0xC8, 0x77, (byte) 0xE9, (byte) 0xA0,
(byte) 0xC2, 0x76, (byte) 0xA8, 0x17 };*/
public static final byte[] iv = { 0x73, (byte) 0x80, 0x16, 0x6f, 0x49,
0x14, (byte) 0xb2, (byte) 0xb9, 0x17, 0x24, 0x42, (byte) 0xd7,
(byte) 0xda, (byte) 0x8a, 0x06, 0x00, (byte) 0xa9, 0x6f, 0x30,
(byte) 0xbc, (byte) 0x16, 0x31, 0x38, (byte) 0xaa, (byte) 0xe3,
(byte) 0x8d, (byte) 0xee, 0x4d, (byte) 0xb0, (byte) 0xfb, 0x0e,
0x4e };
public static int[] Tj = new int[64];
static
{
for (int i = 0; i < 16; i++)
{
Tj[i] = 0x79cc4519;
}
for (int i = 16; i < 64; i++)
{
Tj[i] = 0x7a879d8a;
}
}
public static byte[] CF(byte[] V, byte[] B)
{
int[] v, b;
v = convert(V);
b = convert(B);
return convert(CF(v, b));
}
private static int[] convert(byte[] arr)
{
int[] out = new int[arr.length / 4];
byte[] tmp = new byte[4];
for (int i = 0; i < arr.length; i += 4)
{
System.arraycopy(arr, i, tmp, 0, 4);
out[i / 4] = bigEndianByteToInt(tmp);
}
return out;
}
private static byte[] convert(int[] arr)
{
byte[] out = new byte[arr.length * 4];
byte[] tmp = null;
for (int i = 0; i < arr.length; i++)
{
tmp = bigEndianIntToByte(arr[i]);
System.arraycopy(tmp, 0, out, i * 4, 4);
}
return out;
}
public static int[] CF(int[] V, int[] B)
{
int a, b, c, d, e, f, g, h;
int ss1, ss2, tt1, tt2;
a = V[0];
b = V[1];
c = V[2];
d = V[3];
e = V[4];
f = V[5];
g = V[6];
h = V[7];
/*System.out.println("IV: ");
System.out.print(Integer.toHexString(a)+" ");
System.out.print(Integer.toHexString(b)+" ");
System.out.print(Integer.toHexString(c)+" ");
System.out.print(Integer.toHexString(d)+" ");
System.out.print(Integer.toHexString(e)+" ");
System.out.print(Integer.toHexString(f)+" ");
System.out.print(Integer.toHexString(g)+" ");
System.out.print(Integer.toHexString(h)+" ");
System.out.println("");
System.out.println("");
System.out.println("填充后的消息: ");
for(int i=0; i<B.length; i++)
{
System.out.print(Integer.toHexString(B[i])+" ");
}
System.out.println("");
System.out.println("");*/
int[][] arr = expand(B);
int[] w = arr[0];
int[] w1 = arr[1];
/*System.out.println("扩展后的消息: ");
System.out.println("W0W1...W67");
print(w);
System.out.println("");
System.out.println("W'0W'1...W'67");
print(w1);
System.out.println("迭代压缩中间值: ");*/
for (int j = 0; j < 64; j++)
{
ss1 = (bitCycleLeft(a, 12) + e + bitCycleLeft(Tj[j], j));
ss1 = bitCycleLeft(ss1, 7);
ss2 = ss1 ^ bitCycleLeft(a, 12);
tt1 = FFj(a, b, c, j) + d + ss2 + w1[j];
tt2 = GGj(e, f, g, j) + h + ss1 + w[j];
d = c;
c = bitCycleLeft(b, 9);
b = a;
a = tt1;
h = g;
g = bitCycleLeft(f, 19);
f = e;
e = P0(tt2);
/*System.out.print(j+" ");
System.out.print(Integer.toHexString(a)+" ");
System.out.print(Integer.toHexString(b)+" ");
System.out.print(Integer.toHexString(c)+" ");
System.out.print(Integer.toHexString(d)+" ");
System.out.print(Integer.toHexString(e)+" ");
System.out.print(Integer.toHexString(f)+" ");
System.out.print(Integer.toHexString(g)+" ");
System.out.print(Integer.toHexString(h)+" ");
System.out.println("");*/
}
// System.out.println("");
int[] out = new int[8];
out[0] = a ^ V[0];
out[1] = b ^ V[1];
out[2] = c ^ V[2];
out[3] = d ^ V[3];
out[4] = e ^ V[4];
out[5] = f ^ V[5];
out[6] = g ^ V[6];
out[7] = h ^ V[7];
return out;
}
private static int[][] expand(int[] B)
{
int W[] = new int[68];
int W1[] = new int[64];
for (int i = 0; i < B.length; i++)
{
W[i] = B[i];
}
for (int i = 16; i < 68; i++)
{
W[i] = P1(W[i - 16] ^ W[i - 9] ^ bitCycleLeft(W[i - 3], 15))
^ bitCycleLeft(W[i - 13], 7) ^ W[i - 6];
}
for (int i = 0; i < 64; i++)
{
W1[i] = W[i] ^ W[i + 4];
}
int arr[][] = new int[][] { W, W1 };
return arr;
}
private static byte[] bigEndianIntToByte(int num)
{
return back(Util.intToBytes(num));
}
private static int bigEndianByteToInt(byte[] bytes)
{
return Util.byteToInt(back(bytes));
}
private static int FFj(int X, int Y, int Z, int j)
{
if (j >= 0 && j <= 15)
{
return FF1j(X, Y, Z);
}
else
{
return FF2j(X, Y, Z);
}
}
private static int GGj(int X, int Y, int Z, int j)
{
if (j >= 0 && j <= 15)
{
return GG1j(X, Y, Z);
}
else
{
return GG2j(X, Y, Z);
}
}
// 逻辑位运算函数
private static int FF1j(int X, int Y, int Z)
{
int tmp = X ^ Y ^ Z;
return tmp;
}
private static int FF2j(int X, int Y, int Z)
{
int tmp = ((X & Y) | (X & Z) | (Y & Z));
return tmp;
}
private static int GG1j(int X, int Y, int Z)
{
int tmp = X ^ Y ^ Z;
return tmp;
}
private static int GG2j(int X, int Y, int Z)
{
int tmp = (X & Y) | (~X & Z);
return tmp;
}
private static int P0(int X)
{
int y = rotateLeft(X, 9);
y = bitCycleLeft(X, 9);
int z = rotateLeft(X, 17);
z = bitCycleLeft(X, 17);
int t = X ^ y ^ z;
return t;
}
private static int P1(int X)
{
int t = X ^ bitCycleLeft(X, 15) ^ bitCycleLeft(X, 23);
return t;
}
/**
* 对最后一个分组字节数据padding
*
* @param in
* @param bLen
* 分组个数
* @return
*/
public static byte[] padding(byte[] in, int bLen)
{
int k = 448 - (8 * in.length + 1) % 512;
if (k < 0)
{
k = 960 - (8 * in.length + 1) % 512;
}
k += 1;
byte[] padd = new byte[k / 8];
padd[0] = (byte) 0x80;
long n = in.length * 8 + bLen * 512;
byte[] out = new byte[in.length + k / 8 + 64 / 8];
int pos = 0;
System.arraycopy(in, 0, out, 0, in.length);
pos += in.length;
System.arraycopy(padd, 0, out, pos, padd.length);
pos += padd.length;
byte[] tmp = back(Util.longToBytes(n));
System.arraycopy(tmp, 0, out, pos, tmp.length);
return out;
}
/**
* 字节数组逆序
*
* @param in
* @return
*/
private static byte[] back(byte[] in)
{
byte[] out = new byte[in.length];
for (int i = 0; i < out.length; i++)
{
out[i] = in[out.length - i - 1];
}
return out;
}
public static int rotateLeft(int x, int n)
{
return (x << n) | (x >> (32 - n));
}
private static int bitCycleLeft(int n, int bitLen)
{
bitLen %= 32;
byte[] tmp = bigEndianIntToByte(n);
int byteLen = bitLen / 8;
int len = bitLen % 8;
if (byteLen > 0)
{
tmp = byteCycleLeft(tmp, byteLen);
}
if (len > 0)
{
tmp = bitSmall8CycleLeft(tmp, len);
}
return bigEndianByteToInt(tmp);
}
private static byte[] bitSmall8CycleLeft(byte[] in, int len)
{
byte[] tmp = new byte[in.length];
int t1, t2, t3;
for (int i = 0; i < tmp.length; i++)
{
t1 = (byte) ((in[i] & 0x000000ff) << len);
t2 = (byte) ((in[(i + 1) % tmp.length] & 0x000000ff) >> (8 - len));
t3 = (byte) (t1 | t2);
tmp[i] = (byte) t3;
}
return tmp;
}
private static byte[] byteCycleLeft(byte[] in, int byteLen)
{
byte[] tmp = new byte[in.length];
System.arraycopy(in, byteLen, tmp, 0, in.length - byteLen);
System.arraycopy(in, 0, tmp, in.length - byteLen, byteLen);
return tmp;
}
/*private static void print(int[] arr)
{
for (int i = 0; i < arr.length; i++)
{
System.out.print(Integer.toHexString(arr[i]) + " ");
if ((i + 1) % 16 == 0)
{
System.out.println();
}
}
System.out.println();
}*/
}

145
src/main/java/com/fr/plugin/gzwauth/utils/SM3Digest.java

@ -0,0 +1,145 @@
package com.fr.plugin.gzwauth.utils;
import org.bouncycastle.util.encoders.Hex;
public class SM3Digest
{
/** SM3值的长度 */
private static final int BYTE_LENGTH = 32;
/** SM3分组长度 */
private static final int BLOCK_LENGTH = 64;
/** 缓冲区长度 */
private static final int BUFFER_LENGTH = BLOCK_LENGTH * 1;
/** 缓冲区 */
private byte[] xBuf = new byte[BUFFER_LENGTH];
/** 缓冲区偏移量 */
private int xBufOff;
/** 初始向量 */
private byte[] V = SM3.iv.clone();
private int cntBlock = 0;
public SM3Digest() {
}
public SM3Digest(SM3Digest t)
{
System.arraycopy(t.xBuf, 0, this.xBuf, 0, t.xBuf.length);
this.xBufOff = t.xBufOff;
System.arraycopy(t.V, 0, this.V, 0, t.V.length);
}
/**
* SM3结果输出
*
* @param out 保存SM3结构的缓冲区
* @param outOff 缓冲区偏移量
* @return
*/
public int doFinal(byte[] out, int outOff)
{
byte[] tmp = doFinal();
System.arraycopy(tmp, 0, out, 0, tmp.length);
return BYTE_LENGTH;
}
public void reset()
{
xBufOff = 0;
cntBlock = 0;
V = SM3.iv.clone();
}
/**
* 明文输入
*
* @param in
* 明文输入缓冲区
* @param inOff
* 缓冲区偏移量
* @param len
* 明文长度
*/
public void update(byte[] in, int inOff, int len)
{
int partLen = BUFFER_LENGTH - xBufOff;
int inputLen = len;
int dPos = inOff;
if (partLen < inputLen)
{
System.arraycopy(in, dPos, xBuf, xBufOff, partLen);
inputLen -= partLen;
dPos += partLen;
doUpdate();
while (inputLen > BUFFER_LENGTH)
{
System.arraycopy(in, dPos, xBuf, 0, BUFFER_LENGTH);
inputLen -= BUFFER_LENGTH;
dPos += BUFFER_LENGTH;
doUpdate();
}
}
System.arraycopy(in, dPos, xBuf, xBufOff, inputLen);
xBufOff += inputLen;
}
private void doUpdate()
{
byte[] B = new byte[BLOCK_LENGTH];
for (int i = 0; i < BUFFER_LENGTH; i += BLOCK_LENGTH)
{
System.arraycopy(xBuf, i, B, 0, B.length);
doHash(B);
}
xBufOff = 0;
}
private void doHash(byte[] B)
{
byte[] tmp = SM3.CF(V, B);
System.arraycopy(tmp, 0, V, 0, V.length);
cntBlock++;
}
private byte[] doFinal()
{
byte[] B = new byte[BLOCK_LENGTH];
byte[] buffer = new byte[xBufOff];
System.arraycopy(xBuf, 0, buffer, 0, buffer.length);
byte[] tmp = SM3.padding(buffer, cntBlock);
for (int i = 0; i < tmp.length; i += BLOCK_LENGTH)
{
System.arraycopy(tmp, i, B, 0, B.length);
doHash(B);
}
return V;
}
public void update(byte in)
{
byte[] buffer = new byte[] { in };
update(buffer, 0, 1);
}
public int getDigestSize()
{
return BYTE_LENGTH;
}
public static void main(String[] args)
{
byte[] md = new byte[32];
byte[] msg1 = "abc".getBytes();
SM3Digest sm3 = new SM3Digest();
sm3.update(msg1, 0, msg1.length);
sm3.doFinal(md, 0);
String s = new String(Hex.encode(md));
System.out.println(s);
}
}

20
src/main/java/com/fr/plugin/gzwauth/utils/SM3Util.java

@ -0,0 +1,20 @@
package com.fr.plugin.gzwauth.utils;
import org.bouncycastle.util.encoders.Hex;
public class SM3Util {
public static final String SM3Encode(String str) {
byte[] md = new byte[32];
byte[] msg1 = str.getBytes();
SM3Digest sm3 = new SM3Digest();
sm3.update(msg1, 0, msg1.length);
sm3.doFinal(md, 0);
String s = new String(Hex.encode(md));
return s;
}
public static void main(String[] args){
System.out.println(SM3Util.SM3Encode(("admin111111")));
}
}

48
src/main/java/com/fr/plugin/gzwauth/utils/TokenUtil.java

@ -0,0 +1,48 @@
package com.fr.plugin.gzwauth.utils;
import com.nimbusds.jose.*;
import com.nimbusds.jose.crypto.MACSigner;
import com.nimbusds.jose.shaded.json.JSONObject;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
public class TokenUtil {
public static final JWSHeader header = new JWSHeader(JWSAlgorithm.HS256, JOSEObjectType.JWT, null, null, null, null, null, null, null, null, null, null, null);
/**
* 获取Token
* @param sysId 系统ID
* @param secretkey 密钥
* @return
*/
public static String getToken(String sysId, String secretkey){
Map<String, Object> payload = new HashMap();
payload.put("sid", sysId);
payload.put("iat", System.currentTimeMillis());
payload.put("rand", UUID.randomUUID());
String token = "";
try {
token = createToken(header, SM3Util.SM3Encode(Md5Util.getMD5(secretkey)).getBytes(), payload);
} catch (Exception e) {
e.printStackTrace();
}
return token;
}
public static String createToken(JWSHeader header, byte[] SECRET, Map<String, Object> payload) {
String tokenString = null;
// 创建一个 JWS object
JWSObject jwsObject = new JWSObject(header, new Payload(new JSONObject(payload)));
try {
// 将jwsObject 进行HMAC签名
jwsObject.sign(new MACSigner(SECRET));
tokenString = jwsObject.serialize();
} catch (JOSEException e) {
e.printStackTrace();
}
return tokenString;
}
public static void main(String[] args) {
System.out.println(getToken("1001","admin111111"));
}
}

662
src/main/java/com/fr/plugin/gzwauth/utils/Util.java

@ -0,0 +1,662 @@
package com.fr.plugin.gzwauth.utils;
import java.math.BigInteger;
public class Util
{
/**
* 整形转换成网络传输的字节流字节数组型数据
*
* @param num 一个整型数据
* @return 4个字节的自己数组
*/
public static byte[] intToBytes(int num)
{
byte[] bytes = new byte[4];
bytes[0] = (byte) (0xff & (num >> 0));
bytes[1] = (byte) (0xff & (num >> 8));
bytes[2] = (byte) (0xff & (num >> 16));
bytes[3] = (byte) (0xff & (num >> 24));
return bytes;
}
/**
* 四个字节的字节数据转换成一个整形数据
*
* @param bytes 4个字节的字节数组
* @return 一个整型数据
*/
public static int byteToInt(byte[] bytes)
{
int num = 0;
int temp;
temp = (0x000000ff & (bytes[0])) << 0;
num = num | temp;
temp = (0x000000ff & (bytes[1])) << 8;
num = num | temp;
temp = (0x000000ff & (bytes[2])) << 16;
num = num | temp;
temp = (0x000000ff & (bytes[3])) << 24;
num = num | temp;
return num;
}
/**
* 长整形转换成网络传输的字节流字节数组型数据
*
* @param num 一个长整型数据
* @return 4个字节的自己数组
*/
public static byte[] longToBytes(long num)
{
byte[] bytes = new byte[8];
for (int i = 0; i < 8; i++)
{
bytes[i] = (byte) (0xff & (num >> (i * 8)));
}
return bytes;
}
/**
* 大数字转换字节流字节数组型数据
*
* @param n
* @return
*/
public static byte[] byteConvert32Bytes(BigInteger n)
{
byte tmpd[] = (byte[])null;
if(n == null)
{
return null;
}
if(n.toByteArray().length == 33)
{
tmpd = new byte[32];
System.arraycopy(n.toByteArray(), 1, tmpd, 0, 32);
}
else if(n.toByteArray().length == 32)
{
tmpd = n.toByteArray();
}
else
{
tmpd = new byte[32];
for(int i = 0; i < 32 - n.toByteArray().length; i++)
{
tmpd[i] = 0;
}
System.arraycopy(n.toByteArray(), 0, tmpd, 32 - n.toByteArray().length, n.toByteArray().length);
}
return tmpd;
}
/**
* 换字节流字节数组型数据转大数字
*
* @param b
* @return
*/
public static BigInteger byteConvertInteger(byte[] b)
{
if (b[0] < 0)
{
byte[] temp = new byte[b.length + 1];
temp[0] = 0;
System.arraycopy(b, 0, temp, 1, b.length);
return new BigInteger(temp);
}
return new BigInteger(b);
}
/**
* 根据字节数组获得值(十六进制数字)
*
* @param bytes
* @return
*/
public static String getHexString(byte[] bytes)
{
return getHexString(bytes, true);
}
/**
* 根据字节数组获得值(十六进制数字)
*
* @param bytes
* @param upperCase
* @return
*/
public static String getHexString(byte[] bytes, boolean upperCase)
{
String ret = "";
for (int i = 0; i < bytes.length; i++)
{
ret += Integer.toString((bytes[i] & 0xff) + 0x100, 16).substring(1);
}
return upperCase ? ret.toUpperCase() : ret;
}
/**
* 打印十六进制字符串
*
* @param bytes
*/
public static void printHexString(byte[] bytes)
{
for (int i = 0; i < bytes.length; i++)
{
String hex = Integer.toHexString(bytes[i] & 0xFF);
if (hex.length() == 1)
{
hex = '0' + hex;
}
System.out.print("0x" + hex.toUpperCase() + ",");
}
System.out.println("");
}
/**
* Convert hex string to byte[]
*
* @param hexString
* the hex string
* @return byte[]
*/
public static byte[] hexStringToBytes(String hexString)
{
if (hexString == null || hexString.equals(""))
{
return null;
}
hexString = hexString.toUpperCase();
int length = hexString.length() / 2;
char[] hexChars = hexString.toCharArray();
byte[] d = new byte[length];
for (int i = 0; i < length; i++)
{
int pos = i * 2;
d[i] = (byte) (charToByte(hexChars[pos]) << 4 | charToByte(hexChars[pos + 1]));
}
return d;
}
/**
* Convert char to byte
*
* @param c
* char
* @return byte
*/
public static byte charToByte(char c)
{
return (byte) "0123456789ABCDEF".indexOf(c);
}
/**
* 用于建立十六进制字符的输出的小写字符数组
*/
private static final char[] DIGITS_LOWER = {'0', '1', '2', '3', '4', '5',
'6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'};
/**
* 用于建立十六进制字符的输出的大写字符数组
*/
private static final char[] DIGITS_UPPER = {'0', '1', '2', '3', '4', '5',
'6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F'};
/**
* 将字节数组转换为十六进制字符数组
*
* @param data byte[]
* @return 十六进制char[]
*/
public static char[] encodeHex(byte[] data) {
return encodeHex(data, true);
}
/**
* 将字节数组转换为十六进制字符数组
*
* @param data byte[]
* @param toLowerCase <code>true</code> 传换成小写格式 <code>false</code> 传换成大写格式
* @return 十六进制char[]
*/
public static char[] encodeHex(byte[] data, boolean toLowerCase) {
return encodeHex(data, toLowerCase ? DIGITS_LOWER : DIGITS_UPPER);
}
/**
* 将字节数组转换为十六进制字符数组
*
* @param data byte[]
* @param toDigits 用于控制输出的char[]
* @return 十六进制char[]
*/
protected static char[] encodeHex(byte[] data, char[] toDigits) {
int l = data.length;
char[] out = new char[l << 1];
// two characters form the hex value.
for (int i = 0, j = 0; i < l; i++) {
out[j++] = toDigits[(0xF0 & data[i]) >>> 4];
out[j++] = toDigits[0x0F & data[i]];
}
return out;
}
/**
* 将字节数组转换为十六进制字符串
*
* @param data byte[]
* @return 十六进制String
*/
public static String encodeHexString(byte[] data) {
return encodeHexString(data, true);
}
/**
* 将字节数组转换为十六进制字符串
*
* @param data byte[]
* @param toLowerCase <code>true</code> 传换成小写格式 <code>false</code> 传换成大写格式
* @return 十六进制String
*/
public static String encodeHexString(byte[] data, boolean toLowerCase) {
return encodeHexString(data, toLowerCase ? DIGITS_LOWER : DIGITS_UPPER);
}
/**
* 将字节数组转换为十六进制字符串
*
* @param data byte[]
* @param toDigits 用于控制输出的char[]
* @return 十六进制String
*/
protected static String encodeHexString(byte[] data, char[] toDigits) {
return new String(encodeHex(data, toDigits));
}
/**
* 将十六进制字符数组转换为字节数组
*
* @param data 十六进制char[]
* @return byte[]
* @throws RuntimeException 如果源十六进制字符数组是一个奇怪的长度将抛出运行时异常
*/
public static byte[] decodeHex(char[] data) {
int len = data.length;
if ((len & 0x01) != 0) {
throw new RuntimeException("Odd number of characters.");
}
byte[] out = new byte[len >> 1];
// two characters form the hex value.
for (int i = 0, j = 0; j < len; i++) {
int f = toDigit(data[j], j) << 4;
j++;
f = f | toDigit(data[j], j);
j++;
out[i] = (byte) (f & 0xFF);
}
return out;
}
/**
* 将十六进制字符转换成一个整数
*
* @param ch 十六进制char
* @param index 十六进制字符在字符数组中的位置
* @return 一个整数
* @throws RuntimeException 当ch不是一个合法的十六进制字符时抛出运行时异常
*/
protected static int toDigit(char ch, int index) {
int digit = Character.digit(ch, 16);
if (digit == -1) {
throw new RuntimeException("Illegal hexadecimal character " + ch
+ " at index " + index);
}
return digit;
}
/**
* 数字字符串转ASCII码字符串
*
* @param String
* 字符串
* @return ASCII字符串
*/
public static String StringToAsciiString(String content) {
String result = "";
int max = content.length();
for (int i = 0; i < max; i++) {
char c = content.charAt(i);
String b = Integer.toHexString(c);
result = result + b;
}
return result;
}
/**
* 十六进制转字符串
*
* @param hexString
* 十六进制字符串
* @param encodeType
* 编码类型4Unicode2普通编码
* @return 字符串
*/
public static String hexStringToString(String hexString, int encodeType) {
String result = "";
int max = hexString.length() / encodeType;
for (int i = 0; i < max; i++) {
char c = (char) hexStringToAlgorism(hexString
.substring(i * encodeType, (i + 1) * encodeType));
result += c;
}
return result;
}
/**
* 十六进制字符串装十进制
*
* @param hex
* 十六进制字符串
* @return 十进制数值
*/
public static int hexStringToAlgorism(String hex) {
hex = hex.toUpperCase();
int max = hex.length();
int result = 0;
for (int i = max; i > 0; i--) {
char c = hex.charAt(i - 1);
int algorism = 0;
if (c >= '0' && c <= '9') {
algorism = c - '0';
} else {
algorism = c - 55;
}
result += Math.pow(16, max - i) * algorism;
}
return result;
}
/**
* 十六转二进制
*
* @param hex
* 十六进制字符串
* @return 二进制字符串
*/
public static String hexStringToBinary(String hex) {
hex = hex.toUpperCase();
String result = "";
int max = hex.length();
for (int i = 0; i < max; i++) {
char c = hex.charAt(i);
switch (c) {
case '0':
result += "0000";
break;
case '1':
result += "0001";
break;
case '2':
result += "0010";
break;
case '3':
result += "0011";
break;
case '4':
result += "0100";
break;
case '5':
result += "0101";
break;
case '6':
result += "0110";
break;
case '7':
result += "0111";
break;
case '8':
result += "1000";
break;
case '9':
result += "1001";
break;
case 'A':
result += "1010";
break;
case 'B':
result += "1011";
break;
case 'C':
result += "1100";
break;
case 'D':
result += "1101";
break;
case 'E':
result += "1110";
break;
case 'F':
result += "1111";
break;
}
}
return result;
}
/**
* ASCII码字符串转数字字符串
*
* @param String
* ASCII字符串
* @return 字符串
*/
public static String AsciiStringToString(String content) {
String result = "";
int length = content.length() / 2;
for (int i = 0; i < length; i++) {
String c = content.substring(i * 2, i * 2 + 2);
int a = hexStringToAlgorism(c);
char b = (char) a;
String d = String.valueOf(b);
result += d;
}
return result;
}
/**
* 将十进制转换为指定长度的十六进制字符串
*
* @param algorism
* int 十进制数字
* @param maxLength
* int 转换后的十六进制字符串长度
* @return String 转换后的十六进制字符串
*/
public static String algorismToHexString(int algorism, int maxLength) {
String result = "";
result = Integer.toHexString(algorism);
if (result.length() % 2 == 1) {
result = "0" + result;
}
return patchHexString(result.toUpperCase(), maxLength);
}
/**
* 字节数组转为普通字符串ASCII对应的字符
*
* @param bytearray
* byte[]
* @return String
*/
public static String byteToString(byte[] bytearray) {
String result = "";
char temp;
int length = bytearray.length;
for (int i = 0; i < length; i++) {
temp = (char) bytearray[i];
result += temp;
}
return result;
}
/**
* 二进制字符串转十进制
*
* @param binary
* 二进制字符串
* @return 十进制数值
*/
public static int binaryToAlgorism(String binary) {
int max = binary.length();
int result = 0;
for (int i = max; i > 0; i--) {
char c = binary.charAt(i - 1);
int algorism = c - '0';
result += Math.pow(2, max - i) * algorism;
}
return result;
}
/**
* 十进制转换为十六进制字符串
*
* @param algorism
* int 十进制的数字
* @return String 对应的十六进制字符串
*/
public static String algorismToHEXString(int algorism) {
String result = "";
result = Integer.toHexString(algorism);
if (result.length() % 2 == 1) {
result = "0" + result;
}
result = result.toUpperCase();
return result;
}
/**
* HEX字符串前补0主要用于长度位数不足
*
* @param str
* String 需要补充长度的十六进制字符串
* @param maxLength
* int 补充后十六进制字符串的长度
* @return 补充结果
*/
static public String patchHexString(String str, int maxLength) {
String temp = "";
for (int i = 0; i < maxLength - str.length(); i++) {
temp = "0" + temp;
}
str = (temp + str).substring(0, maxLength);
return str;
}
/**
* 将一个字符串转换为int
*
* @param s
* String 要转换的字符串
* @param defaultInt
* int 如果出现异常,默认返回的数字
* @param radix
* int 要转换的字符串是什么进制的,如16 8 10.
* @return int 转换后的数字
*/
public static int parseToInt(String s, int defaultInt, int radix) {
int i = 0;
try {
i = Integer.parseInt(s, radix);
} catch (NumberFormatException ex) {
i = defaultInt;
}
return i;
}
/**
* 将一个十进制形式的数字字符串转换为int
*
* @param s
* String 要转换的字符串
* @param defaultInt
* int 如果出现异常,默认返回的数字
* @return int 转换后的数字
*/
public static int parseToInt(String s, int defaultInt) {
int i = 0;
try {
i = Integer.parseInt(s);
} catch (NumberFormatException ex) {
i = defaultInt;
}
return i;
}
/**
* 十六进制串转化为byte数组
*
* @return the array of byte
*/
public static byte[] hexToByte(String hex)
throws IllegalArgumentException {
if (hex.length() % 2 != 0) {
throw new IllegalArgumentException();
}
char[] arr = hex.toCharArray();
byte[] b = new byte[hex.length() / 2];
for (int i = 0, j = 0, l = hex.length(); i < l; i++, j++) {
String swap = "" + arr[i++] + arr[i];
int byteint = Integer.parseInt(swap, 16) & 0xFF;
b[j] = new Integer(byteint).byteValue();
}
return b;
}
/**
* 字节数组转换为十六进制字符串
*
* @param b
* byte[] 需要转换的字节数组
* @return String 十六进制字符串
*/
public static String byteToHex(byte b[]) {
if (b == null) {
throw new IllegalArgumentException(
"Argument b ( byte array ) is null! ");
}
String hs = "";
String stmp = "";
for (int n = 0; n < b.length; n++) {
stmp = Integer.toHexString(b[n] & 0xff);
if (stmp.length() == 1) {
hs = hs + "0" + stmp;
} else {
hs = hs + stmp;
}
}
return hs.toUpperCase();
}
public static byte[] subByte(byte[] input, int startIndex, int length) {
byte[] bt = new byte[length];
for (int i = 0; i < length; i++) {
bt[i] = input[i + startIndex];
}
return bt;
}
}

227
src/main/java/com/fr/plugin/gzwauth/utils/Utils.java

@ -0,0 +1,227 @@
package com.fr.plugin.gzwauth.utils;
import com.fr.base.TemplateUtils;
import com.fr.data.NetworkHelper;
import com.fr.io.utils.ResourceIOUtils;
import com.fr.json.JSONObject;
import com.fr.stable.CodeUtils;
import com.fr.stable.StringUtils;
import com.fr.third.org.apache.commons.codec.digest.DigestUtils;
import com.fr.web.utils.WebUtils;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedReader;
import java.io.InputStream;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Utils {
/**
* 判断字符串是否为空
* @param str
* @return true 空字符串 false 非空字符串
*/
public static boolean isNullStr(String str){
return !(str != null && !str.isEmpty() && !"null".equals(str));
}
/**
* 判断字符串是否非空
* @param str
* @return
*/
public static boolean isNotNullStr(String str){
return !isNullStr(str);
}
/**
* MD5加密
* @param str
* @return
*/
public static String getMd5Str(String str)
{
return DigestUtils.md5Hex(str);
}
/**
* 帆软shaEncode加密
*/
public static String shaEncode(String str){
return CodeUtils.sha256Encode(str);
}
/**
* 获取uuid
*/
public static String uuid(){
return UUID.randomUUID().toString();
}
/**
* 替换空字符串
* @param str
* @param replace
* @return
*/
public static String replaceNullStr(String str,String replace){
if(isNullStr(str)){
return replace;
}
return str;
}
/**
* 获取请求体
* @param req
* @return
*/
public static JSONObject getRequestBody(HttpServletRequest req){
StringBuffer sb = new StringBuffer();
String line = null;
try {
BufferedReader reader = req.getReader();
while ((line = reader.readLine()) != null)
sb.append(line);
} catch (Exception e) {
FRUtils.FRLogInfo("getRequestBody:exception:"+e.getMessage());
}
//将空格和换行符替换掉避免使用反序列化工具解析对象时失败
String jsonString = sb.toString().replaceAll("\\s","").replaceAll("\n","");
JSONObject json = new JSONObject(jsonString);
return json;
}
/**
* 获取ip
* @return
*/
public static String getIp(HttpServletRequest req){
String realIp = req.getHeader("X-Real-IP");
String fw = req.getHeader("X-Forwarded-For");
if (StringUtils.isNotEmpty(fw) && !"unKnown".equalsIgnoreCase(fw)) {
int var3 = fw.indexOf(",");
return var3 != -1 ? fw.substring(0, var3) : fw;
} else {
fw = realIp;
if (StringUtils.isNotEmpty(realIp) && !"unKnown".equalsIgnoreCase(realIp)) {
return realIp;
} else {
if (StringUtils.isBlank(realIp) || "unknown".equalsIgnoreCase(realIp)) {
fw = req.getHeader("Proxy-Client-IP");
}
if (StringUtils.isBlank(fw) || "unknown".equalsIgnoreCase(fw)) {
fw = req.getHeader("WL-Proxy-Client-IP");
}
if (StringUtils.isBlank(fw) || "unknown".equalsIgnoreCase(fw)) {
fw = req.getHeader("HTTP_CLIENT_IP");
}
if (StringUtils.isBlank(fw) || "unknown".equalsIgnoreCase(fw)) {
fw = req.getHeader("HTTP_X_FORWARDED_FOR");
}
if (StringUtils.isBlank(fw) || "unknown".equalsIgnoreCase(fw)) {
fw = req.getRemoteAddr();
}
return fw;
}
}
}
/**
* 根据key获取cookie
* @param req
* @return
*/
public static String getCookieByKey(HttpServletRequest req,String key){
Cookie[] cookies = req.getCookies();
String cookie = "";
if(cookies == null || cookies.length <=0){
return "";
}
for(int i = 0; i < cookies.length; i++) {
Cookie item = cookies[i];
if (item.getName().equalsIgnoreCase(key)) {
cookie = item.getValue();
}
}
FRUtils.FRLogInfo("cookie:"+cookie);
return cookie;
}
/**
* 判断是否是手机端的链接
* @param req
* @return
*/
public static boolean isMobile(HttpServletRequest req) {
String[] mobileArray = {"iPhone", "iPad", "android", "windows phone", "xiaomi"};
String userAgent = req.getHeader("user-agent");
if (userAgent != null && userAgent.toUpperCase().contains("MOBILE")) {
for(String mobile : mobileArray) {
if(userAgent.toUpperCase().contains(mobile.toUpperCase())) {
return true;
}
}
}
return NetworkHelper.getDevice(req).isMobile();
}
/**
* 只编码中文
* @param url
* @return
*/
public static String encodeCH(String url ){
Matcher matcher = Pattern.compile("[\\u4e00-\\u9fa5]").matcher(url);
while(matcher.find()){
String chn = matcher.group();
url = url.replaceAll(chn, URLEncoder.encode(chn));
}
return url;
}
/**
* 获取web-inf文件夹下的文件
* filename /resources/ip4enc.properties
*/
public static InputStream getResourcesFile(String filename){
return ResourceIOUtils.read(filename);
}
public static void toErrorPage(HttpServletResponse res,String path,Map<String, String> parameterMap){
if(parameterMap == null){
parameterMap = new HashMap<String, String>();
}
try {
String macPage = TemplateUtils.renderTemplate(path, parameterMap);
WebUtils.printAsString(res, macPage);
}catch (Exception e){
FRUtils.FRLogError("跳转页面异常");
}
}
}

95
src/main/resources/com/fr/plugin/gzwauth/error.html

@ -0,0 +1,95 @@
<html><head>
<meta charset="utf-8">
<title></title>
<style>
body {
background-color: #ffffff;
}
.main {
position: absolute;
top: 25%;
left: 10%;
right: 10%;
margin: auto;
}
.main div {
text-align: center;
}
#header-content {
min-width: 40%;
min-height: 40%;
max-width: 100%;
max-height: 100%;
}
.simple-message {
font-weight: 500;
width: 100%;
font-size: 28px;
color: #3685f2;
text-align: center;
margin-top: 20px;
line-height: 40px;
}
.detail-message {
font-size: 16px;
color: #ff4949;
margin: 15px auto;
line-height: 24px;
}
.solution {
font-size: 16px;
color: #ff4949;
line-height: 24px;
}
.login {
color: #3685f2;
text-decoration: none;
line-height: 24px;
float: right;
height: 24px;
font-size: 12px;
margin-right: 40px;
margin-top: 40px;
}
</style>
<script type="text/javascript" src="/webroot/decision/file?path=com.fr.decision.web.i18n.NormalTextGenerator&amp;type=class&amp;parser=plain"></script>
</head>
<body>
<!--<a href="/webroot/decision/login" class="login"></a>-->
<div class="main" id="12aaed1d-7cb5-488f-91bb-dba35342c9d2">
<div>
<img id="header-content" src="/webroot/decision/resources?path=/com/fr/web/resources/dist/images/1x/background/error_page.png" alt="error page">
</div>
<div class="simple-message" id="simple-message">500</div>
<div class="detail-message" id="detail-message">无权限访问,请联系管理员!</div>
<!-- <div class="solution" id="solution">请确认地址是否正确</div>-->
</div>
<script>
function getI18n(key) {
var value;
try {
value = (I18n && I18n[key]);
} catch (e) {
value = (FR && FR.i18nText(key))
}
return !value ? key : value;
}
var id = "12aaed1d-7cb5-488f-91bb-dba35342c9d2";
var simple = document.getElementById(id).children[1];
var detail = document.getElementById(id).children[2];
var solution = document.getElementById(id).children[3];;
simple.innerText = getI18n(simple.innerText);
detail.innerText = getI18n(detail.innerText);
solution.innerText = getI18n(solution.innerText);
</script>
</body></html>
Loading…
Cancel
Save