Browse Source

增加的公共方法,分页,地图,返回结果集

XF--LRQYEJOKYDS\Administrator 4 năm trước cách đây
mục cha
commit
4a0b1bc48f

+ 126 - 0
YijiaRestful/src/main/java/com/platform/yijia/utils/ApiRequestBean.java

@@ -0,0 +1,126 @@
+package com.platform.yijia.utils;
+
+import java.io.Serializable;
+
+
+public class ApiRequestBean<T>  implements Serializable{
+	
+	private static final long serialVersionUID = -9073910802005694017L;
+
+	/**
+	 * 合作机构id
+	 */
+	private String orgId;
+	
+	/**
+	 * 请求id
+	 */
+	private String reqId;
+	
+	/**
+	 * 请求接口版本1.0
+	 */
+	private String version;
+	
+	/**
+	 * 代理商身份标识
+	 */
+	private String agentId;
+	
+	/**
+	 * 业务员编号
+	 */
+	private String salesCode;
+	
+	/**
+	 * 业务数据
+	 */
+	private T reqData;
+	
+	/**
+	 * 签名
+	 */
+	private String sign;
+	
+	/**
+	 * 签名类型
+	 */
+	private String signType;
+	
+	/**
+	 * 请求时间
+	 */
+	private String timestamp;
+
+	public String getOrgId() {
+		return orgId;
+	}
+
+	public void setOrgId(String orgId) {
+		this.orgId = orgId;
+	}
+
+	public String getReqId() {
+		return reqId;
+	}
+
+	public void setReqId(String reqId) {
+		this.reqId = reqId;
+	}
+
+	public String getVersion() {
+		return version;
+	}
+
+	public void setVersion(String version) {
+		this.version = version;
+	}
+
+	public String getAgentId() {
+		return agentId;
+	}
+
+	public void setAgentId(String agentId) {
+		this.agentId = agentId;
+	}
+
+	public String getSalesCode() {
+		return salesCode;
+	}
+
+	public void setSalesCode(String salesCode) {
+		this.salesCode = salesCode;
+	}
+
+	public T getReqData() {
+		return reqData;
+	}
+
+	public void setReqData(T reqData) {
+		this.reqData = reqData;
+	}
+
+	public String getSign() {
+		return sign;
+	}
+
+	public void setSign(String sign) {
+		this.sign = sign;
+	}
+
+	public String getSignType() {
+		return signType;
+	}
+
+	public void setSignType(String signType) {
+		this.signType = signType;
+	}
+
+	public String getTimestamp() {
+		return timestamp;
+	}
+
+	public void setTimestamp(String timestamp) {
+		this.timestamp = timestamp;
+	}
+}

+ 96 - 0
YijiaRestful/src/main/java/com/platform/yijia/utils/ApiResponseBean.java

@@ -0,0 +1,96 @@
+package com.platform.yijia.utils;
+
+import java.io.Serializable;
+
+public class ApiResponseBean<T>  implements Serializable {
+
+	private static final long serialVersionUID = -6027021300935759741L;
+	
+	/**
+	 * 系统响应码
+	 */
+	private String code;
+	/**
+	 * 系统消息
+	 */
+	private String msg;
+	
+	/**
+	 * 请求时id
+	 */
+	private String reqId;
+	
+	/**
+	 * 请求时orgId
+	 */
+	private String orgId;
+	
+	private String signType;
+	
+	
+	/**
+	 * 返回消息
+	 */
+	private T respData;
+	
+	/**
+	 * 签名
+	 */
+	private String sign;
+
+	public String getCode() {
+		return code;
+	}
+
+	public void setCode(String code) {
+		this.code = code;
+	}
+
+	public String getMsg() {
+		return msg;
+	}
+
+	public void setMsg(String msg) {
+		this.msg = msg;
+	}
+
+	public String getReqId() {
+		return reqId;
+	}
+
+	public void setReqId(String reqId) {
+		this.reqId = reqId;
+	}
+
+	public String getOrgId() {
+		return orgId;
+	}
+
+	public void setOrgId(String orgId) {
+		this.orgId = orgId;
+	}
+
+	public String getSignType() {
+		return signType;
+	}
+
+	public void setSignType(String signType) {
+		this.signType = signType;
+	}
+
+	public T getRespData() {
+		return respData;
+	}
+
+	public void setRespData(T respData) {
+		this.respData = respData;
+	}
+
+	public String getSign() {
+		return sign;
+	}
+
+	public void setSign(String sign) {
+		this.sign = sign;
+	}
+}

+ 8 - 0
YijiaRestful/src/main/java/com/platform/yijia/utils/Authentication.java

@@ -0,0 +1,8 @@
+package com.platform.yijia.utils;
+
+/**
+ * 身份验证
+ */
+public class Authentication {
+
+}

+ 32 - 0
YijiaRestful/src/main/java/com/platform/yijia/utils/CodeMsg.java

@@ -0,0 +1,32 @@
+package com.platform.yijia.utils;
+
+public class CodeMsg {
+    private int retCode;
+    private String message;
+    // 按照模块定义CodeMsg
+    // 通用异常
+    public static CodeMsg SUCCESS = new CodeMsg(0,"success");
+    public static CodeMsg SERVER_EXCEPTION = new CodeMsg(500100,"服务端异常");
+    public static CodeMsg USER_NOT_EXSIST = new CodeMsg(-1,"用户不存在");
+    public static CodeMsg SEARCH_FAIL = new CodeMsg(001,"查询失败");
+    public static CodeMsg INSERT_FAIL = new CodeMsg(001,"添加失败");
+
+    public static CodeMsg DELETE_FAIL = new CodeMsg(003,"删除失败");
+    public static CodeMsg UPDATE_FAIL = new CodeMsg(004,"修改失败");
+    public static CodeMsg REQUEST_FAIL = new CodeMsg(005,"传参失败");
+    public static CodeMsg YEWU_FAIL = new CodeMsg(006,"业务失败");
+
+    private CodeMsg(int retCode, String message) {
+        this.retCode = retCode;
+        this.message = message;
+    }
+    public int getRetCode() {
+        return retCode;
+    }
+    public String getMessage() {
+        return message;
+    }
+    public void setMessage(String message) {
+        this.message = message;
+    }
+}

+ 144 - 0
YijiaRestful/src/main/java/com/platform/yijia/utils/HttpUtils.java

@@ -0,0 +1,144 @@
+package com.platform.yijia.utils;
+
+import org.apache.http.HttpEntity;
+import org.apache.http.HttpStatus;
+import org.apache.http.client.ClientProtocolException;
+import org.apache.http.client.config.RequestConfig;
+import org.apache.http.client.methods.CloseableHttpResponse;
+import org.apache.http.client.methods.HttpGet;
+import org.apache.http.client.methods.HttpPost;
+import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
+import org.apache.http.conn.ssl.SSLContextBuilder;
+import org.apache.http.conn.ssl.TrustStrategy;
+import org.apache.http.entity.StringEntity;
+import org.apache.http.impl.client.CloseableHttpClient;
+import org.apache.http.impl.client.HttpClients;
+import org.apache.http.util.EntityUtils;
+
+import java.io.IOException;
+import java.security.KeyManagementException;
+import java.security.KeyStoreException;
+import java.security.NoSuchAlgorithmException;
+import java.security.cert.CertificateException;
+import java.security.cert.X509Certificate;
+
+public class HttpUtils {
+	
+	/**
+	 * 创建没有证书的SSL链接工厂类
+	 * @return
+	 * @throws NoSuchAlgorithmException
+	 * @throws KeyStoreException
+	 * @throws KeyManagementException
+	 */
+	public static SSLConnectionSocketFactory getSSLConnectionSocketFactory() throws NoSuchAlgorithmException, 
+			KeyStoreException, KeyManagementException {
+		SSLContextBuilder   context = new SSLContextBuilder().useProtocol("TLSv1.2");
+		context.loadTrustMaterial(null, new TrustStrategy() {
+			@Override
+			public boolean isTrusted(X509Certificate[] arg0, String arg1)
+					throws CertificateException {
+				return true;
+			}
+		});
+		return new SSLConnectionSocketFactory(context.build());
+	}
+	
+	/**
+	 * 链接GET请求
+	 * @param url
+	 * @return
+	 * @throws KeyManagementException
+	 * @throws NoSuchAlgorithmException
+	 * @throws KeyStoreException
+	 * @throws ClientProtocolException
+	 * @throws IOException
+	 */
+	public static String connectGetUrl(String url) throws KeyManagementException, 
+			NoSuchAlgorithmException, KeyStoreException, ClientProtocolException, IOException {
+		SSLConnectionSocketFactory sslsf = getSSLConnectionSocketFactory();
+		CloseableHttpClient client = HttpClients.custom().setSSLSocketFactory(sslsf).build();
+		RequestConfig config = RequestConfig.custom().setSocketTimeout(10000).setConnectTimeout(5000).build();
+		HttpGet httpGet = null;
+		CloseableHttpResponse resp = null;
+		String jsonString = "";
+		try {
+			httpGet =	new HttpGet(url);
+			httpGet.setConfig(config);
+			resp = client.execute(httpGet);
+			HttpEntity entity = resp.getEntity();
+		    jsonString = EntityUtils.toString(entity, "UTF-8");
+		} finally {
+        	if (resp != null) {
+        		try {
+        			resp.close();
+				} catch (IOException e) {
+					e.printStackTrace();
+				}
+        	}
+			if (httpGet != null) {
+				httpGet.releaseConnection();
+			}
+		}
+		return jsonString;
+	}
+	
+	/**
+	 * 链接POST请求
+	 * @param url
+	 * @param jsonParm
+	 * @return
+	 * @throws KeyManagementException
+	 * @throws NoSuchAlgorithmException
+	 * @throws KeyStoreException
+	 * @throws ClientProtocolException
+	 * @throws IOException
+	 */
+	public static String connectPostUrl(String url, String jsonParm) throws KeyManagementException, 
+			NoSuchAlgorithmException, KeyStoreException, ClientProtocolException, IOException {
+		SSLConnectionSocketFactory sslsf = getSSLConnectionSocketFactory();
+		CloseableHttpClient client = HttpClients.custom().setSSLSocketFactory(sslsf).build();
+		RequestConfig config = RequestConfig.custom().setSocketTimeout(40000).setConnectTimeout(10000).build();
+		HttpPost httpPost = null;
+		CloseableHttpResponse resp = null;
+		try {
+			httpPost = new HttpPost(url);
+			httpPost.setConfig(config);
+			StringEntity params = new StringEntity(jsonParm,"UTF-8");  
+			params.setContentType("application/json");
+	        httpPost.setEntity(params);
+			resp = client.execute(httpPost);
+			HttpEntity entity = resp.getEntity();
+			String jsonString = EntityUtils.toString(entity, "UTF-8");
+			
+			if (resp.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
+				return jsonString;
+			}
+		}catch (IOException e) {
+			if (e instanceof org.apache.http.conn.ConnectTimeoutException) {
+				throw new org.apache.http.conn.ConnectTimeoutException("connect timed out");
+			}
+			if (e instanceof java.net.SocketTimeoutException) {
+				throw new java.net.SocketTimeoutException("Read timed out");
+			}
+			throw new IOException("IOException");
+		}  finally {
+        	if (resp != null) {
+        		try {
+        			resp.close();
+				} catch (IOException e) {
+					e.printStackTrace();
+				}
+        	}
+			if (httpPost != null) {
+				httpPost.releaseConnection();
+			}
+			try {
+				client.close();
+			} catch (IOException e) {
+				e.printStackTrace();
+			}
+		}
+		return null;
+	}
+}

+ 33 - 0
YijiaRestful/src/main/java/com/platform/yijia/utils/PageUtil.java

@@ -0,0 +1,33 @@
+package com.platform.yijia.utils;
+
+import java.util.ArrayList;
+import java.util.List;
+
+public class PageUtil {
+
+    public static <T> List<T> splitList(List<T> list, int pageSize,int pageNum){
+        if(pageSize==0){
+            pageSize=10;
+        }
+        int listSize = list.size();
+        int dangqianye=pageNum*pageSize;
+        int kaishi = (pageNum-1)*pageSize;
+        List<T> subList = new ArrayList<T>();
+        if(listSize<dangqianye && kaishi<listSize ){
+           // int page = (listSize + (pageSize - 1)) / pageSize;
+            for (int i = 0; i < pageNum; i++){
+                for (int j = 0; j < listSize; j++){
+                    int pageIndex = ((j + 1) + (pageSize - 1)) / pageSize;
+                    if (pageIndex == (i + 1)) {
+                        subList.add(list.get(j));
+                    }
+                    if ((j + 1) == ((j + 1) * pageSize)){
+                        break;
+                    }
+                }
+            }
+        }
+
+        return subList;
+    }
+}

+ 380 - 0
YijiaRestful/src/main/java/com/platform/yijia/utils/RSAEncrypt.java

@@ -0,0 +1,380 @@
+package com.platform.yijia.utils;
+
+import com.alibaba.fastjson.JSON;
+import sun.misc.BASE64Decoder;
+import sun.misc.BASE64Encoder;
+
+import javax.crypto.BadPaddingException;
+import javax.crypto.Cipher;
+import javax.crypto.IllegalBlockSizeException;
+import javax.crypto.NoSuchPaddingException;
+import java.io.*;
+import java.security.*;
+import java.security.interfaces.RSAPrivateKey;
+import java.security.interfaces.RSAPublicKey;
+import java.security.spec.InvalidKeySpecException;
+import java.security.spec.PKCS8EncodedKeySpec;
+import java.security.spec.X509EncodedKeySpec;
+import java.util.Map;
+
+
+/**
+ * rsa 签名
+ * 利用genKeyPair ()方法来生成钥匙对。
+ 加密:RSAEncrypt.encryptBASE64(RSAEncrypt.encrypt(RSAEncrypt.loadPublicKeyByStr(RSAEncrypt.loadPublicKeyByFile(filepath)),"要加密的字符串".getBytes()))
+ 解密:RSAEncrypt.decrypt(RSAEncrypt.loadPrivateKeyByStr(RSAEncrypt.loadPrivateKeyByFile(filepath)), RSAEncrypt.decryptBASE64("要解密的字符串"))
+ */
+public class RSAEncrypt {
+    /**
+     * 字节数据转字符串专用集合
+     */
+    private static final char[] HEX_CHAR = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'};
+
+    /**
+     * 随机生成密钥对
+     */
+    public static void genKeyPair(String filePath) {
+        // KeyPairGenerator类用于生成公钥和私钥对,基于RSA算法生成对象
+        KeyPairGenerator keyPairGen = null;
+        try {
+            keyPairGen = KeyPairGenerator.getInstance("RSA");
+        } catch (NoSuchAlgorithmException e) {
+            e.printStackTrace();
+        }
+        // 初始化密钥对生成器,密钥大小为96-1024位
+        keyPairGen.initialize(1024, new SecureRandom());
+        // 生成一个密钥对,保存在keyPair中
+        KeyPair keyPair = keyPairGen.generateKeyPair();
+        // 得到私钥
+        RSAPrivateKey privateKey = (RSAPrivateKey) keyPair.getPrivate();
+        // 得到公钥
+        RSAPublicKey publicKey = (RSAPublicKey) keyPair.getPublic();
+        try {
+            // 得到公钥字符串
+            String publicKeyString = new String(encryptBASE64(publicKey.getEncoded()));
+            // 得到私钥字符串
+            String privateKeyString = new String(encryptBASE64(privateKey.getEncoded()));
+            // 将密钥对写入到文件
+            FileWriter pubfw = new FileWriter(filePath + "/publicKey.keystore");
+            FileWriter prifw = new FileWriter(filePath + "/privateKey.keystore");
+            BufferedWriter pubbw = new BufferedWriter(pubfw);
+            BufferedWriter pribw = new BufferedWriter(prifw);
+            pubbw.write(publicKeyString);
+            pribw.write(privateKeyString);
+            pubbw.flush();
+            pubbw.close();
+            pubfw.close();
+            pribw.flush();
+            pribw.close();
+            prifw.close();
+        } catch (Exception e) {
+            e.printStackTrace();
+        }
+    }
+
+    /**
+     * 从文件中输入流中加载公钥
+     *
+     * @param path 公钥路径
+     * @throws Exception 加载公钥时产生的异常
+     */
+    public static String loadPublicKeyByFile(String path) throws Exception {
+        try {
+            BufferedReader br = new BufferedReader(new FileReader(path + "/publicKey.keystore"));
+            String readLine = null;
+            StringBuilder sb = new StringBuilder();
+            while ((readLine = br.readLine()) != null) {
+                sb.append(readLine);
+            }
+            br.close();
+            return sb.toString();
+        } catch (IOException e) {
+            throw new Exception("公钥数据流读取错误");
+        } catch (NullPointerException e) {
+            throw new Exception("公钥输入流为空");
+        }
+    }
+
+    /**
+     * 从字符串中加载公钥
+     *
+     * @param publicKeyStr 公钥数据字符串
+     * @throws Exception 加载公钥时产生的异常
+     */
+    public static RSAPublicKey loadPublicKeyByStr(String publicKeyStr) throws Exception {
+        try {
+            byte[] buffer = decryptBASE64(publicKeyStr);
+            KeyFactory keyFactory = KeyFactory.getInstance("RSA");
+            X509EncodedKeySpec keySpec = new X509EncodedKeySpec(buffer);
+            return (RSAPublicKey) keyFactory.generatePublic(keySpec);
+        } catch (NoSuchAlgorithmException e) {
+            throw new Exception("无此算法");
+        } catch (InvalidKeySpecException e) {
+            throw new Exception("公钥非法");
+        } catch (NullPointerException e) {
+            throw new Exception("公钥数据为空");
+        }
+    }
+
+    /**
+     * 从文件中加载私钥
+     *
+     * @param path 私钥文件路径
+     * @return 是否成功
+     * @throws Exception
+     */
+    public static String loadPrivateKeyByFile(String path) throws Exception {
+        try {
+            BufferedReader br = new BufferedReader(new FileReader(path + "/privateKey.keystore"));
+            String readLine = null;
+            StringBuilder sb = new StringBuilder();
+            while ((readLine = br.readLine()) != null) {
+                sb.append(readLine);
+            }
+            br.close();
+            return sb.toString();
+        } catch (IOException e) {
+            throw new Exception("私钥数据读取错误");
+        } catch (NullPointerException e) {
+            throw new Exception("私钥输入流为空");
+        }
+    }
+
+    public static RSAPrivateKey loadPrivateKeyByStr(String privateKeyStr) throws Exception {
+        try {
+            byte[] buffer = decryptBASE64(privateKeyStr);
+            PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(buffer);
+            KeyFactory keyFactory = KeyFactory.getInstance("RSA");
+            return (RSAPrivateKey) keyFactory.generatePrivate(keySpec);
+        } catch (NoSuchAlgorithmException e) {
+            throw new Exception("无此算法");
+        } catch (InvalidKeySpecException e) {
+            throw new Exception("私钥非法");
+        } catch (NullPointerException e) {
+            throw new Exception("私钥数据为空");
+        }
+    }
+
+    /**
+     * 公钥加密过程
+     *
+     * @param publicKey     公钥
+     * @param plainTextData 明文数据
+     * @return
+     * @throws Exception 加密过程中的异常信息
+     */
+    public static byte[] encrypt(RSAPublicKey publicKey, byte[] plainTextData) throws Exception {
+        if (publicKey == null) {
+            throw new Exception("加密公钥为空, 请设置");
+        }
+        Cipher cipher = null;
+        try {
+            // 使用默认RSA
+            cipher = Cipher.getInstance("RSA");
+            // cipher= Cipher.getInstance("RSA", new BouncyCastleProvider());
+            cipher.init(Cipher.ENCRYPT_MODE, publicKey);
+            byte[] output = cipher.doFinal(plainTextData);
+            return output;
+        } catch (NoSuchAlgorithmException e) {
+            throw new Exception("无此加密算法");
+        } catch (NoSuchPaddingException e) {
+            e.printStackTrace();
+            return null;
+        } catch (InvalidKeyException e) {
+            throw new Exception("加密公钥非法,请检查");
+        } catch (IllegalBlockSizeException e) {
+            throw new Exception("明文长度非法");
+        } catch (BadPaddingException e) {
+            throw new Exception("明文数据已损坏");
+        }
+    }
+
+    /**
+     * 私钥加密过程
+     *
+     * @param privateKey    私钥
+     * @param plainTextData 明文数据
+     * @return
+     * @throws Exception 加密过程中的异常信息
+     */
+    public static byte[] encrypt(RSAPrivateKey privateKey, byte[] plainTextData) throws Exception {
+        if (privateKey == null) {
+            throw new Exception("加密私钥为空, 请设置");
+        }
+        Cipher cipher = null;
+        try {
+            // 使用默认RSA
+            cipher = Cipher.getInstance("RSA");
+            cipher.init(Cipher.ENCRYPT_MODE, privateKey);
+            byte[] output = cipher.doFinal(plainTextData);
+            return output;
+        } catch (NoSuchAlgorithmException e) {
+            throw new Exception("无此加密算法");
+        } catch (NoSuchPaddingException e) {
+            e.printStackTrace();
+            return null;
+        } catch (InvalidKeyException e) {
+            throw new Exception("加密私钥非法,请检查");
+        } catch (IllegalBlockSizeException e) {
+            throw new Exception("明文长度非法");
+        } catch (BadPaddingException e) {
+            throw new Exception("明文数据已损坏");
+        }
+    }
+
+    /**
+     * 私钥解密过程
+     *
+     * @param privateKey 私钥
+     * @param cipherData 密文数据
+     * @return 明文
+     * @throws Exception 解密过程中的异常信息
+     */
+    public static byte[] decrypt(RSAPrivateKey privateKey, byte[] cipherData) throws Exception {
+        if (privateKey == null) {
+            throw new Exception("解密私钥为空, 请设置");
+        }
+        Cipher cipher = null;
+        try {
+            // 使用默认RSA
+            cipher = Cipher.getInstance("RSA");
+            // cipher= Cipher.getInstance("RSA", new BouncyCastleProvider());
+            cipher.init(Cipher.DECRYPT_MODE, privateKey);
+            byte[] output = cipher.doFinal(cipherData);
+            return output;
+        } catch (NoSuchAlgorithmException e) {
+            throw new Exception("无此解密算法");
+        } catch (NoSuchPaddingException e) {
+            e.printStackTrace();
+            return null;
+        } catch (InvalidKeyException e) {
+            throw new Exception("解密私钥非法,请检查");
+        } catch (IllegalBlockSizeException e) {
+            throw new Exception("密文长度非法");
+        } catch (BadPaddingException e) {
+            throw new Exception("密文数据已损坏");
+        }
+    }
+
+    /**
+     * 公钥解密过程
+     *
+     * @param publicKey  公钥
+     * @param cipherData 密文数据
+     * @return 明文
+     * @throws Exception 解密过程中的异常信息
+     */
+    public static byte[] decrypt(RSAPublicKey publicKey, byte[] cipherData) throws Exception {
+        if (publicKey == null) {
+            throw new Exception("解密公钥为空, 请设置");
+        }
+        Cipher cipher = null;
+        try {
+            // 使用默认RSA
+            cipher = Cipher.getInstance("RSA");
+            // cipher= Cipher.getInstance("RSA", new BouncyCastleProvider());
+            cipher.init(Cipher.DECRYPT_MODE, publicKey);
+            byte[] output = cipher.doFinal(cipherData);
+            return output;
+        } catch (NoSuchAlgorithmException e) {
+            throw new Exception("无此解密算法");
+        } catch (NoSuchPaddingException e) {
+            e.printStackTrace();
+            return null;
+        } catch (InvalidKeyException e) {
+            throw new Exception("解密公钥非法,请检查");
+        } catch (IllegalBlockSizeException e) {
+            throw new Exception("密文长度非法");
+        } catch (BadPaddingException e) {
+            throw new Exception("密文数据已损坏");
+        }
+    }
+
+    /**
+     * 字节数据转十六进制字符串
+     *
+     * @param data 输入数据
+     * @return 十六进制内容
+     */
+    public static String byteArrayToString(byte[] data) {
+        StringBuilder stringBuilder = new StringBuilder();
+        for (int i = 0; i < data.length; i++) {
+            // 取出字节的高四位 作为索引得到相应的十六进制标识符 注意无符号右移
+            stringBuilder.append(HEX_CHAR[(data[i] & 0xf0) >>> 4]);
+            // 取出字节的低四位 作为索引得到相应的十六进制标识符
+            stringBuilder.append(HEX_CHAR[(data[i] & 0x0f)]);
+            if (i < data.length - 1) {
+                stringBuilder.append(' ');
+            }
+        }
+        return stringBuilder.toString();
+    }
+
+    public static String encryptBASE64(byte[] key) throws Exception {
+        return (new BASE64Encoder()).encodeBuffer(key);
+    }
+
+    public static byte[] decryptBASE64(String key) throws Exception {
+        return (new BASE64Decoder()).decodeBuffer(key);
+    }
+
+    /**
+     * 私钥加密(数字签名),用公钥进行验证
+     * @param args
+     */
+    public static void main(String[] args) {
+        String filepath = "/Users/cxd/Documents/Exercise/ideaDemo/src/main/resources";
+        
+        String privateKey = "";
+        String publicKey = "";
+        
+
+        String key = "123123123";
+        
+        //RSAEncrypt.genKeyPair(filepath);
+        System. out.println( "---------------私钥签名过程------------------" );
+        String content= "{\"addressType01\":\"01\",\"addressType02\":\"01\",\"addressType03\":\"01\"}";
+        String signstr= null;
+        try {
+
+       // String enData = EncryptUtil.encryptBASE64(EncryptUtil.encrypt(content.getBytes(), key.getBytes()));
+        	Map<String, Object> requestParam = (Map<String, Object>) JSON.parse(content);
+        	
+        	String signContent = RSASignature.getOrderContent(requestParam);
+        
+            signstr = RSASignature.encryptBASE64(RSASignature.sign(signContent, privateKey));
+            
+          //  System.out.println("加密后的数据" + enData);
+            System. out.println( "签名原串:" +signContent);
+            System. out.println( "签名串:"+signstr);
+            System. out.println();
+            //
+            System. out.println( "---------------公钥校验签名------------------" );
+            System. out.println( "签名原串:" +content);
+            System. out.println( "签名串:"+signstr);
+
+            System. out. println("验签结果:"+RSASignature.doCheck(signContent, signstr,publicKey ));
+
+
+           /* key = "123123121";
+            System.out.println("DES开始解密.....");
+            String deData = new String(EncryptUtil.decrypt(EncryptUtil.decryptBASE64(enData), key.getBytes()));
+            System.out.println("DES解密后的数据:" + deData);
+*/
+        	
+        	String enData1 = "pTrCotXethMaH3K7jiM3Eg==\r\n";
+        	String signstr1 = "RUPwD/bF/7Vgg203JQ/T3W4R1yHso1p6ZoUS8nysWand76fyB1+X1GdJNsBALQhajvaQHhTtWAaQ"
++"K7ezL2NASa7EYWC+H+jXhd98C6WgWFWga4ApjK2RjSWsTz1y30GJSxW++fbYYSuz8Owrx3iNLNyc"
++"E8Br0pdj40pL+OJs60A=";
+        	String publicKey1 = "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCOmsrFtFPTnEzfpJ/hDl5RODBxw4i9Ex3NmmG/N7A1+by032zZZgLLpdNh8y5otjFY0E37Nyr4FGKFRSSuDiTk8vfx3pv6ImS1Rxjjg4qdVHIfqhCeB0Z2ZPuBD3Gbj8hHFEtXZq8+msAFu/5ZQjiVhgs5WWBjh54LYWSum+d9+wIDAQAB";
+            System. out. println("验签结果1:"+RSASignature.doCheck(enData1, signstr1,publicKey1 ));
+            String desStr = "DFk3/UBtnjRh+b/S4EE3snSorVigDXmKIfWYap1PAlYNe5t5RNQnE9QoQzXOd9P8BKMa8Sld+ea4\nDWClWD1a7cZ6qrD29o7vDiaqM6md3FihHL+CuYJrwgOUzSHCbnGSjQNayKSxZ4ccXB4NKY+s4/8F\n8Q5p0wZ6H1jbYawv1qrUGV9Sdv2pVw5Q2nL1vhr5nws1plHxuTU0vQ8yVppYDt+Z42KkwDGs\n";
+            
+           // String deData = new String(EncryptUtil.decrypt(EncryptUtil.decryptBASE64(desStr), key.getBytes()));
+           // System.out.println("DES解密后的数据:" + deData);
+
+        } catch (Exception e) {
+            e.printStackTrace();
+        }
+    }
+}

+ 106 - 0
YijiaRestful/src/main/java/com/platform/yijia/utils/RSASignature.java

@@ -0,0 +1,106 @@
+package com.platform.yijia.utils;
+
+import java.security.KeyFactory;
+import java.security.PrivateKey;
+import java.security.PublicKey;
+import java.security.spec.PKCS8EncodedKeySpec;
+import java.security.spec.X509EncodedKeySpec;
+import java.util.*;
+
+
+/**
+ * RSA签名验签类
+ */
+public class RSASignature {
+
+    /**
+     * 签名算法
+     */
+    public static final String SIGN_ALGORITHMS = "SHA1WithRSA";
+    
+	/**
+	 * 针对参数进行排序拼装
+	 * @param
+	 * @return
+	 */
+	public static String getOrderContent(Map<String, Object> requestParam) {
+		Map<String, Object> sortedParams = new TreeMap<String, Object>();
+		if ((requestParam != null) && (requestParam.size() > 0)) {
+			sortedParams.putAll(requestParam);
+		}
+		StringBuffer content = new StringBuffer();
+		List<String> keys = new ArrayList<String>(sortedParams.keySet());
+		Collections.sort(keys);
+		int index = 0;
+		for (int i = 0; i < keys.size(); i++) {
+			String key = keys.get(i);
+			Object value = sortedParams.get(key);
+			if (key!=null &&!"".equals(key)&& value != null) {
+				content.append((index == 0 ? "" : "&") + key + "=" + value);
+				index++;
+			}
+		}
+		return content.toString();
+	}
+
+    /**
+     * rsa 签名
+     * @param content 待签名内容
+     * @param privateKey  私钥
+     * @return
+     */
+    public static byte[] sign(String content, String privateKey) {
+        try {
+            PKCS8EncodedKeySpec priPKCS8 = new PKCS8EncodedKeySpec(decryptBASE64(privateKey));
+            KeyFactory keyf = KeyFactory.getInstance("RSA");
+            PrivateKey priKey = keyf.generatePrivate(priPKCS8);
+            java.security.Signature signature = java.security.Signature.getInstance(SIGN_ALGORITHMS);
+            signature.initSign(priKey);
+            signature.update(content.getBytes("UTF-8"));
+            byte[] signed = signature.sign();
+            return signed;
+        } catch (Exception e) {
+        	e.printStackTrace();
+            return null;
+        }
+    }
+
+    /**
+     * RSA验签名检查
+     * @param content 待签名数据
+     * @param sign 签名值
+     * @param publicKey 分配给开发商公钥
+     * @return 布尔值
+     */
+    public static boolean doCheck(String content, String sign, String publicKey) {
+        try {
+            KeyFactory keyFactory = KeyFactory.getInstance("RSA");
+            byte[] encodedKey = decryptBASE64(publicKey);
+            PublicKey pubKey = keyFactory.generatePublic(new X509EncodedKeySpec(encodedKey));
+
+
+            java.security.Signature signature = java.security.Signature.getInstance(SIGN_ALGORITHMS);
+
+            signature.initVerify(pubKey);
+            signature.update(content.getBytes("UTF-8"));
+
+            boolean bverify = signature.verify(decryptBASE64(sign));
+            return bverify;
+
+        } catch (Exception e) {
+        	e.printStackTrace();
+            return false;
+        }
+    }
+
+    public static String encryptBASE64(byte[] key) throws Exception {
+        System.out.println("key:"+key);
+        String base64encodedString = Base64.getEncoder().encodeToString(key);
+        return base64encodedString.replaceAll("[\\s*\t\n\r]", "");
+    }
+    public static byte[] decryptBASE64(String key) throws Exception {
+        byte[] base64decodedBytes = Base64.getDecoder().decode(key.replaceAll("[\\s*\t\n\r]", ""));
+        return base64decodedBytes;
+    }
+
+}

+ 60 - 0
YijiaRestful/src/main/java/com/platform/yijia/utils/ResultData.java

@@ -0,0 +1,60 @@
+package com.platform.yijia.utils;
+
+public class ResultData<T> {
+    private String message;
+    private int retCode;
+    private T data;
+    private ResultData(T data) {
+        this.retCode = 0;
+        this.message = "成功";
+        this.data = data;
+    }
+    private ResultData(CodeMsg cm) {
+        if(cm == null){
+            return;
+        }
+        this.retCode = cm.getRetCode();
+        this.message = cm.getMessage();
+    }
+    /**
+     * 成功时候的调用
+     * @return
+     */
+    public static <T> ResultData<T> success(T data){
+        return new ResultData<T>(data);
+    }
+    /**
+     * 成功,不需要传入参数
+     * @return
+     */
+    @SuppressWarnings("unchecked")
+    public static <T> ResultData<T> success(){
+        return (ResultData<T>) success("");
+    }
+    /**
+     * 失败时候的调用
+     * @return
+     */
+    public static <T> ResultData<T> error(CodeMsg cm){
+        return new ResultData<T>(cm);
+    }
+    /**
+     * 失败时候的调用,扩展消息参数
+     * @param cm
+     * @param msg
+     * @return
+     */
+    public static <T> ResultData<T> error(CodeMsg cm,String msg){
+        cm.setMessage(cm.getMessage()+"--"+msg);
+        return new ResultData<T>(cm);
+    }
+    public T getData() {
+        return data;
+    }
+    public String getMessage() {
+        return message;
+    }
+    public int getRetCode() {
+        return retCode;
+    }
+}

+ 57 - 0
YijiaRestful/src/main/java/com/platform/yijia/utils/SXFPaySign.java

@@ -0,0 +1,57 @@
+package com.platform.yijia.utils;
+
+import com.alibaba.fastjson.JSON;
+import com.alibaba.fastjson.JSONObject;
+import com.alibaba.fastjson.parser.Feature;
+
+import java.text.SimpleDateFormat;
+import java.util.Date;
+import java.util.HashMap;
+import java.util.LinkedHashMap;
+import java.util.UUID;
+
+/**
+ * 随行付,公共方法
+ */
+public class SXFPaySign {
+    //合作方私钥(替换成自己的)
+    // public static final String privateKey = "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDM+4PMi2ZPqpeCQ1IIV8mWYmGubr3DoEEJ3W2oEu8bFMVVpK5Jx6WhQ9xR83OQW7lbMI+BbumilKXfHdHrW7gWvu7yB2dD50GbT6bZXXnuddui+BnS/Yc9QxFS+HLcOX8bsmgJ5P/4D1Klm4k3OOsGJ3CsLDuz8RwNlxwuhg8+lQIDAQAB";
+    public static final String privateKey = "MIICdgIBADANBgkqhkiG9w0BAQEFAASCAmAwggJcAgEAAoGBAMz7g8yLZk+ql4JDUghXyZZiYa5uvcOgQQndbagS7xsUxVWkrknHpaFD3FHzc5BbuVswj4Fu6aKUpd8d0etbuBa+7vIHZ0PnQZtPptldee5126L4GdL9hz1DEVL4ctw5fxuyaAnk//gPUqWbiTc46wYncKwsO7PxHA2XHC6GDz6VAgMBAAECgYEAgC2C1CQTPRvqk+0u3cKvbtdkR6Q+C5cpNFb/XAtC80dAwnYw+jfarYX2vlQi3pFMzeYGxqQpep3DP0qxWqBG8uu7Depw2HlWcw+6z68G3Vpkprx9FHnsy/ijCX/76HMmDmGN1r68FnDZXHKdaLZPQeNxDY3Hz83Quq04yav5Ah0CQQDoVoZZM6SyF+gz4/mg29UwkEXcn5uUARWo7QrO6vOsYzTEiNvNIlLFxd5xE2i9LAKKLWBtuaMovrdC4fHguQaLAkEA4dvINHcuehDHVzgS5I/6hB5PnQZOrnZFDZUd7woh9xUu9qQTxZpPcbfSpDFCKDbTknM1dn+7WpLk6Zd9YGyTXwJACXu2oh90gnxtUujkQIeYjRHmeBnfrMvaiXmbblSyu3+VIMyBRD85Z68q5CyposcQF3nArNnd6gTW0BkO2WBT/wJAUUGbA5UlOXEz5mMcGPLbtBCbn+iXAhk2uq49OLSyh4wtezqIinz7u/PgaoX2QTWIZJXiVCGcK/fRN2DzEG+/jQJAIQQFJNUX5i7aUS4By8xrffUpeTTiszu+WTU5Rz2jRoT8YwgqiqAWG9dNSggcfnJIz968a+Jg5s483y06mEEmjA==";
+    //随行付公钥
+    public static final String sxfPublic = "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCOmsrFtFPTnEzfpJ/hDl5RODBxw4i9Ex3NmmG/N7A1+by032zZZgLLpdNh8y5otjFY0E37Nyr4FGKFRSSuDiTk8vfx3pv6ImS1Rxjjg4qdVHIfqhCeB0Z2ZPuBD3Gbj8hHFEtXZq8+msAFu/5ZQjiVhgs5WWBjh54LYWSum+d9+wIDAQAB";
+
+    /**
+     * 封装传参信息,增加公共信息,增加业务信息
+     * @param reqData
+     * @return
+     */
+    public static String getSXFPay(JSONObject reqData ) {
+        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");//设置日期格式
+        String dataStr = df.format(new Date());
+        ApiRequestBean<JSONObject> reqBean = new ApiRequestBean<JSONObject>();
+        reqBean.setOrgId("77563944");//合作机构id
+        reqBean.setReqId(UUID.randomUUID().toString().replaceAll("-", ""));//请求id 订单号
+        reqBean.setSignType("RSA");//签名类型
+        reqBean.setTimestamp(dataStr);//请求时间
+        reqBean.setVersion("1.0");//版本
+        //将业务参数存放在 JSON 对象中
+        reqBean.setReqData(reqData);
+        String req = JSONObject.toJSONString(reqBean);
+        System.out.println("req:" + req);
+        return req;
+    }
+
+
+    /**
+     *封装组织加密串
+     */
+    public static String getSignContent(String req){
+        System.out.println("req:" + req);
+        //此处不要改变reqData里面值的顺序用LinkedHashMap
+        HashMap reqMap = JSON.parseObject(req, LinkedHashMap.class, Feature.OrderedField);
+        //组装加密串
+        String signContent = RSASignature.getOrderContent(reqMap);
+        return "";
+    }
+
+}