小程序获取实名+身份证加密解密方法

文档中(保密)提供了php的加解密方法,这里就不重复描述,java方法类型提供如下

小程序前端:

  

前端需要注意的是行业目录坐标category-id,具体不重复。

后端加密解密java代码

/**
	 * 私钥加密
	 */
	public static String sign(String request, String privateKey) throws Exception {
		byte[] data = request.getBytes("UTF-8");
		byte[] keyBytes = Base64Util.decode(privateKey);
		PKCS8EncodedKeySpec pkcs8KeySpec = new PKCS8EncodedKeySpec(keyBytes);
		KeyFactory keyFactory = KeyFactory.getInstance("RSA");
		PrivateKey privateK = keyFactory.generatePrivate(pkcs8KeySpec);
		Signature signature = Signature.getInstance("SHA256WithRSA");
		signature.initSign(privateK);
		signature.update(data);
		return Base64Util.encode(signature.sign());
	}

	// 私钥解密
	public static String decryptByPrivateKey(String content, String Key) throws Exception {
		// 将base64编码后的私钥字符串转成PrivateKey实例
		byte[] keyBytes = Base64.getDecoder().decode(Key.getBytes());
		PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(keyBytes);
		KeyFactory keyFactory = KeyFactory.getInstance("RSA");
		PrivateKey privateKey = keyFactory.generatePrivate(keySpec);
		// 获取私钥
		Cipher cipher = Cipher.getInstance("RSA");
		cipher.init(Cipher.DECRYPT_MODE, privateKey);
		byte[] cipherText = Base64.getDecoder().decode(content);
		byte[] decryptText = cipher.doFinal(cipherText);
		return new String(decryptText, "gbk");
	}

由于接口为高级接口,不能公开,提供java后端加密解密方法,仅供参考

 

续:

有人私底下问我是不是少个类,我现在给补上。这个类很简单的。

 

package com.app.wii.util;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;

import it.sauronsoftware.base64.Base64;

/**
 * 

* BASE64编码解码工具包 *

*

* 依赖javabase64-1.3.1.jar *

* * @author IceWee * @date 2012-5-19 * @version 1.0 */ public class Base64Utils { /** * 文件读取缓冲区大小 */ private static final int CACHE_SIZE = 1024; /** *

* BASE64字符串解码为二进制数据 *

* * @param base64 * @return * @throws Exception */ public static byte[] decode(String base64) throws Exception { return Base64.decode(base64.getBytes()); } /** *

* 二进制数据编码为BASE64字符串 *

* * @param bytes * @return * @throws Exception */ public static String encode(byte[] bytes) throws Exception { return new String(Base64.encode(bytes)); } /** *

* 将文件编码为BASE64字符串 *

*

* 大文件慎用,可能会导致内存溢出 *

* * @param filePath 文件绝对路径 * @return * @throws Exception */ public static String encodeFile(String filePath) throws Exception { byte[] bytes = fileToByte(filePath); return encode(bytes); } /** *

* BASE64字符串转回文件 *

* * @param filePath 文件绝对路径 * @param base64 编码字符串 * @throws Exception */ public static void decodeToFile(String filePath, String base64) throws Exception { byte[] bytes = decode(base64); byteArrayToFile(bytes, filePath); } /** *

* 文件转换为二进制数组 *

* * @param filePath 文件路径 * @return * @throws Exception */ public static byte[] fileToByte(String filePath) throws Exception { byte[] data = new byte[0]; File file = new File(filePath); if (file.exists()) { FileInputStream in = new FileInputStream(file); ByteArrayOutputStream out = new ByteArrayOutputStream(2048); byte[] cache = new byte[CACHE_SIZE]; int nRead = 0; while ((nRead = in.read(cache)) != -1) { out.write(cache, 0, nRead); out.flush(); } out.close(); in.close(); data = out.toByteArray(); } return data; } /** *

* 二进制数据写文件 *

* * @param bytes 二进制数据 * @param filePath 文件生成目录 */ public static void byteArrayToFile(byte[] bytes, String filePath) throws Exception { InputStream in = new ByteArrayInputStream(bytes); File destFile = new File(filePath); if (!destFile.getParentFile().exists()) { destFile.getParentFile().mkdirs(); } destFile.createNewFile(); OutputStream out = new FileOutputStream(destFile); byte[] cache = new byte[CACHE_SIZE]; int nRead = 0; while ((nRead = in.read(cache)) != -1) { out.write(cache, 0, nRead); out.flush(); } out.close(); in.close(); } }

调用demo

/**
     * 
     * @param appid  小程序id
     * @param secret 小程序secret
     * @param key  私钥
     * @param paramMap
     * @param i 防止token失效,递归处理,通常为3
     * @return 返回map  key分别为:encrytedname :姓名,encrytedid:身份证
     * @throws Exception 
     * @author pangxianhe
     * @date 2018年11月21日
     */
	public static Map queryRealName(String appid, String secret, String key, Map paramMap, int i)
			throws Exception {
		access_token = StringUtil.isNotEmpty(access_token) ? access_token : queryToken(appid, secret);
		String getrealnameinfo = "https://api.weixin.qq.com/cgi-bin/wxopen/getrealnameinfo?access_token=ACCESS_TOKEN"
				.replaceAll("ACCESS_TOKEN", access_token);
		String categoryreturn = HttpUtil.sendPost(getrealnameinfo, JSONObject.fromObject(paramMap).toString());
		Map returnMap = null;
		if (StringUtil.isNotEmpty(categoryreturn)) {
			JSONObject jsonObject = JSONObject.fromObject(categoryreturn);
			Object errcode = jsonObject.get("errcode");
			//token失效重新获取
			if ("40001".equals(errcode.toString())) {
				if (i > 0) {
					i = i - 1;
					access_token = queryToken(appid, secret);
					//递归处理,i通常为3
					return queryRealName(appid, secret, key, paramMap, i);
				}
			} else if ("0".equals(errcode.toString())) {
				String encryted_real_name = (String) jsonObject.get("encryted_real_name");
				String encryted_credential_id = (String) jsonObject.get("encryted_credential_id");
				String encrytedname = decryptByPrivateKey(encryted_real_name, key);
				String encrytedid = decryptByPrivateKey(encryted_credential_id, key);
				if (StringUtil.isNotEmpty(encrytedname) && StringUtil.isNotEmpty(encrytedid)) {
					returnMap = new HashMap();
					returnMap.put("encrytedname", encrytedname);
					returnMap.put("encrytedid", encrytedid);

				}
			} else {
				// 获取失败
			}
		}
		return returnMap;
	}

调用的action

/**
	 * 返回实名信息
	 * 
	 * @return
	 * @throws Exception
	 */
	public String queryrealnameinfo() throws Exception {
		Map returnMap = new HashMap();
		String userid = (String) requestMap.get("userid");
		String auth_token = (String) requestMap.get("auth_token");
		String orderid = (String) requestMap.get("orderid");
		boolean flag = false;
		DatabaseContextHolder.setCustomerType(MappingConstant.DTS);
		DtsSystemManagePojo dtsSystemManagePojo = dtsSystemManageService.queryPojo("car_real_name_auth_info");
		String key = dtsSystemManagePojo.getServiceprivatekey();// 私钥
		String mch_id = dtsSystemManagePojo.getServiceaccount();
		String cert_serialno = dtsSystemManagePojo.getServicepublickey(); //
		Date date = new Date();
		String timestamp = Long.toString(date.getTime()).substring(0, 10);

		try {
			Map paramMap = new HashMap();
			paramMap.put("auth_token", auth_token);
			paramMap.put("mch_id", mch_id);// 商户号
			paramMap.put("cert_serialno", cert_serialno);
			paramMap.put("timestamp", timestamp);
			String ori_content = "cert_serialno=" + cert_serialno + "×tamp=" + timestamp;
			String valuersa = ProcTokenUtil.sign(ori_content, key);
			paramMap.put("sign", valuersa);
			Map backMap = ProcTokenUtil.queryRealName(appid, appsecret, key, paramMap, 3);
			if (StringUtil.isNotEmpty(backMap)) {
				String username = (String) backMap.get("encrytedname");
				String idcard = (String) backMap.get("encrytedid");
				returnMap.put("idcard", idcard);
				DatabaseContextHolder.setCustomerType(MappingConstant.WII);
				wiiUserService.saveUserRealname(userid, username, idcard);
				// 根据orderid查询订单id身份证姓名是否一样
				WiiInsuranceCollectPojo orderPoJo = wiiCarOrderflowService.queryOrderflowPojo(orderid);
				if (StringUtil.isNotEmpty(orderPoJo)) {
					String customername = orderPoJo.getCustomername();
					String certificatecode = orderPoJo.getCertificatecode();
					if (username.equalsIgnoreCase(customername) && idcard.equalsIgnoreCase(certificatecode)) {
						flag = true;
					}
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		returnMap.put("flag", flag);
		write(JSONObject.fromObject(returnMap).toString());
		return SUCCESS;
	}

 

你可能感兴趣的:(小程序)