Merge branch 'master' of https://gitee.com/huoxiong/hx_common
| | |
| | | <artifactId>spring-boot-starter-forest</artifactId> |
| | | <version>1.5.0-RC2</version> |
| | | </dependency> |
| | | |
| | | <!-- redis --> |
| | | <dependency> |
| | | <groupId>org.springframework.boot</groupId> |
| | | <artifactId>spring-boot-starter-data-redis</artifactId> |
| | | </dependency> |
| | | </dependencies> |
| | | |
| | | <build> |
| | | <finalName>hx-demoboot</finalName> |
| | | <finalName>hx-common</finalName> |
| | | <resources> |
| | | <resource> |
| | | <directory>src/main/java</directory> |
New file |
| | |
| | | package com.hx.redis; |
| | | |
| | | import com.fasterxml.jackson.annotation.JsonAutoDetect; |
| | | import com.fasterxml.jackson.annotation.PropertyAccessor; |
| | | import com.fasterxml.jackson.databind.ObjectMapper; |
| | | import org.springframework.cache.annotation.EnableCaching; |
| | | import org.springframework.context.annotation.Bean; |
| | | import org.springframework.context.annotation.Configuration; |
| | | import org.springframework.data.redis.connection.RedisConnectionFactory; |
| | | import org.springframework.data.redis.core.RedisTemplate; |
| | | import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer; |
| | | import org.springframework.data.redis.serializer.StringRedisSerializer; |
| | | |
| | | @Configuration |
| | | @EnableCaching |
| | | public class RedisConfig { |
| | | @Bean |
| | | public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory factory) { |
| | | RedisTemplate<String, Object> template = new RedisTemplate<String, Object>(); |
| | | template.setConnectionFactory(factory); |
| | | Jackson2JsonRedisSerializer jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer(Object.class); |
| | | ObjectMapper om = new ObjectMapper(); |
| | | om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY); |
| | | om.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL); |
| | | jackson2JsonRedisSerializer.setObjectMapper(om); |
| | | StringRedisSerializer stringRedisSerializer = new StringRedisSerializer(); |
| | | template.setKeySerializer(stringRedisSerializer); |
| | | template.setHashKeySerializer(stringRedisSerializer); |
| | | template.setValueSerializer(jackson2JsonRedisSerializer); |
| | | template.setHashValueSerializer(jackson2JsonRedisSerializer); |
| | | template.afterPropertiesSet(); |
| | | return template; |
| | | } |
| | | } |
New file |
| | |
| | | package com.hx.redis; |
| | | |
| | | import org.springframework.data.redis.core.RedisTemplate; |
| | | import org.springframework.stereotype.Component; |
| | | |
| | | import javax.annotation.Resource; |
| | | import java.util.Date; |
| | | import java.util.concurrent.TimeUnit; |
| | | |
| | | |
| | | /** |
| | | * 文件处理工具 |
| | | * |
| | | * @author wangrenhuang |
| | | * @Date 2021-10-19 |
| | | */ |
| | | @Component |
| | | public class RedisUtil { |
| | | /** |
| | | * [redis] |
| | | */ |
| | | @Resource |
| | | private RedisTemplate<String, Object> redisTemplate; |
| | | |
| | | |
| | | /** |
| | | * [判断key是否存在] |
| | | * |
| | | * @param key 键 |
| | | * @return true 存在 false不存在 |
| | | */ |
| | | public boolean hasKey(String key) { |
| | | try { |
| | | return redisTemplate.hasKey(key); |
| | | } catch (Exception e) { |
| | | return false; |
| | | } |
| | | } |
| | | |
| | | /** |
| | | * [普通缓存获取] |
| | | * |
| | | * @param key 键 |
| | | * @return 值 |
| | | */ |
| | | public Object get(String key) { |
| | | return key == null ? null : redisTemplate.opsForValue().get(key); |
| | | } |
| | | |
| | | /** |
| | | * [普通缓存删除] |
| | | * |
| | | * @param key 键 |
| | | * @return 值 |
| | | */ |
| | | public boolean delete(String key) { |
| | | try { |
| | | Boolean aBoolean = redisTemplate.hasKey(key); |
| | | return aBoolean == false ? true : redisTemplate.delete(key); |
| | | } catch (Exception e) { |
| | | return false; |
| | | } |
| | | } |
| | | |
| | | /** |
| | | * [普通缓存放入] |
| | | * |
| | | * @param key 键 |
| | | * @param value 值 |
| | | * @return true成功 false失败 |
| | | */ |
| | | public boolean set(String key, Object value) { |
| | | try { |
| | | redisTemplate.opsForValue().set(key, value); |
| | | return true; |
| | | } catch (Exception e) { |
| | | return false; |
| | | } |
| | | } |
| | | |
| | | |
| | | /** |
| | | * 普通缓存放入并设置时间 |
| | | * |
| | | * @param key 键 |
| | | * @param value 值 |
| | | * @param time 时间(秒) time要大于0 如果time小于等于0 将设置无限期 |
| | | * @return true成功 false 失败 |
| | | */ |
| | | public boolean set(String key, Object value, long time) { |
| | | try { |
| | | if (time > 0) { |
| | | redisTemplate.opsForValue().set(key, value, time, TimeUnit.SECONDS); |
| | | } else { |
| | | set(key, value); |
| | | } |
| | | return true; |
| | | } catch (Exception e) { |
| | | e.printStackTrace(); |
| | | return false; |
| | | } |
| | | } |
| | | |
| | | /** |
| | | * 26 |
| | | * 指定缓存失效时间 |
| | | * 27 |
| | | * |
| | | * @param key 键 |
| | | * 28 |
| | | * @param time 时间(秒) |
| | | * 29 |
| | | * @return 30 |
| | | */ |
| | | |
| | | public boolean expire(String key, long time) { |
| | | try { |
| | | if (time > 0) { |
| | | redisTemplate.expire(key, time, TimeUnit.SECONDS); |
| | | } |
| | | return true; |
| | | } catch (Exception e) { |
| | | e.printStackTrace(); |
| | | return false; |
| | | |
| | | } |
| | | |
| | | } |
| | | |
| | | } |
| | | |
| | |
| | | * @Data: 2020-06-20 |
| | | */ |
| | | public final class ResponseCode { |
| | | |
| | | /*成功*/ |
| | | public static final String SUCCESS = "100"; |
| | | /*错误提示,前端根据这个码弹出提示*/ |
| | |
| | | public static final String ERROR_LOGIN="603"; |
| | | /*系统异常*/ |
| | | public static final String ERROR_SYSTEM = "999"; |
| | | /*签名错误*/ |
| | | public static final String ERROR_SIGN = "203"; |
| | | |
| | | |
| | | |
New file |
| | |
| | | package com.hx.util; |
| | | |
| | | import org.apache.commons.lang.StringUtils; |
| | | |
| | | /** |
| | | * 数据脱敏工具类 |
| | | * |
| | | */ |
| | | public class BlurDataUtil { |
| | | |
| | | /** |
| | | * 手机号脱敏处理 |
| | | * 脱敏规则: 保留前三后四, 比如 18738291234 置换为 187****1234 |
| | | * @param phone |
| | | * @return |
| | | */ |
| | | public static final String blurPhone(String phone) { |
| | | if (StringUtils.isEmpty(phone) || (phone.length() != 11)) { |
| | | return phone; |
| | | } |
| | | return phone.replaceAll("(\\d{3})\\d{4}(\\d{4})", "$1****$2"); |
| | | } |
| | | |
| | | /** |
| | | * 身份证号脱敏处理 |
| | | * 原身份证号:500222202110275699,脱敏后:132****99308084911 |
| | | * @param idCard |
| | | * @return |
| | | */ |
| | | public static String blurIdCard(String idCard) { |
| | | if (StringUtils.isEmpty(idCard)) { |
| | | return ""; |
| | | } |
| | | /* |
| | | * 参数1:证件号,参数2(OVERLAY):替换后的字符串, |
| | | * 参数3(START):替换的起始下标,参数4(END):替换的结束下标(不包含) |
| | | */ |
| | | return StringUtils.overlay(idCard, "****", 3, 7); |
| | | } |
| | | |
| | | /** |
| | | * 身份证号脱敏处理 |
| | | * 展示 前6位和后6位 |
| | | * @param idCard |
| | | * @return |
| | | */ |
| | | public static String hiddenIdCard(String idCard) {//身份证 |
| | | if (StringUtils.isBlank(idCard)) { |
| | | return ""; |
| | | } |
| | | return StringUtils.left(idCard, 6).concat(StringUtils.removeStart(StringUtils.leftPad(StringUtils.right(idCard, 4), StringUtils.length(idCard), "*"), "***")); |
| | | } |
| | | |
| | | /** |
| | | * 邮箱脱敏处理 |
| | | * 原邮箱:zhangsan@qq.com,脱敏后:zhang***@qq.com |
| | | * @param email |
| | | * @return |
| | | */ |
| | | public static String blurEmail(String email) { |
| | | if (StringUtils.isEmpty(email)) { |
| | | return email; |
| | | } |
| | | String encrypt = email.replaceAll("(\\w+)\\w{3}@(\\w+)", "$1***@$2"); |
| | | if(StringUtils.equalsIgnoreCase(email, encrypt)){ |
| | | encrypt = email.replaceAll("(\\w*)\\w{1}@(\\w+)", "$1*@$2"); |
| | | } |
| | | return encrypt; |
| | | } |
| | | |
| | | /** |
| | | * 护照脱敏处理 |
| | | * 脱敏规则:护照前2后3位脱敏,护照一般为8或9位 |
| | | * @param passport |
| | | * @return |
| | | */ |
| | | public static String blurPassport(String passport) { |
| | | if (StringUtils.isEmpty(passport) || (passport.length() < 8)) { |
| | | return passport; |
| | | } |
| | | return passport.substring(0, 2) + new String(new char[passport.length() - 5]).replace("\0", "*") + passport.substring(passport.length() - 3); |
| | | } |
| | | |
| | | /** |
| | | * 字段信息脱敏 |
| | | * 脱敏规则:如果字符长度大于3位,则隐藏最后三位,否则隐藏最后1位 |
| | | * @param field |
| | | * @return |
| | | */ |
| | | public static String blurField(String field) { |
| | | if (StringUtils.isEmpty(field)) { |
| | | return field; |
| | | } |
| | | String encrypt = field.replaceAll("(\\w+)\\w{3}", "$1***"); |
| | | if(StringUtils.equalsIgnoreCase(field, encrypt)){ |
| | | encrypt = field.replaceAll("(\\w*)\\w{1}", "$1*"); |
| | | } |
| | | return encrypt; |
| | | } |
| | | |
| | | public static void main(String[] args) { |
| | | System.out.println(blurPhone("18738291234")); // 187****1234 |
| | | System.out.println(blurIdCard("500222202110275699")); // 500****99410275467 |
| | | System.out.println(blurEmail("zhangsan@qq.com")); // zhang***@qq.com |
| | | System.out.println(blurPassport("12345678")); // 12***678 |
| | | System.out.println(blurField("I feel so good")); // I f*** so g*** |
| | | } |
| | | |
| | | /* |
| | | * 备注: |
| | | * 1、String.replaceAll(第1个参数是脱敏筛选的正则,第2个参数是脱敏替换的正则) |
| | | * 2、需要引入commons-lang3,这个基本每个项目都用到 |
| | | * <dependency> |
| | | * <groupId>org.apache.commons</groupId> |
| | | * <artifactId>commons-lang3</artifactId> |
| | | * <version>3.7</version> |
| | | * </dependency> |
| | | */ |
| | | } |
| | |
| | | private static SimpleDateFormat Format_16 = new SimpleDateFormat("yyyy/MM/dd HH:mm"); |
| | | private static SimpleDateFormat Format_17 = new SimpleDateFormat("HH:mm"); |
| | | |
| | | /**时间格式转化iso8601 |
| | | * @param date 时间 |
| | | * @return 返回的时间格式字符串 |
| | | */ |
| | | public static String dateFormatISO8601(Date date) { |
| | | if(!SimpleTool.checkNotNull(date)){ |
| | | return ""; |
| | | } |
| | | SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssXXX");//设置日期格式 |
| | | return df.format(date); |
| | | } |
| | | |
| | | /**时间格式转化 |
| | | * @param date 时间 |
| | | * @param format 时间格式 |
| | |
| | | return df.format(date); |
| | | } |
| | | |
| | | /**时间戳转时间 |
| | | * @param timestamp 时间戳 |
| | | * @param format 时间格式 |
| | | * @return 返回的时间格式字符串 |
| | | */ |
| | | public static Date timestampToDate(long timestamp, String format) { |
| | | SimpleDateFormat sdf= new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); |
| | | String sd = sdf.format(new Date(timestamp)); // 时间戳转换成时间 |
| | | return DateUtil.parseString(sd,"yyyy-MM-dd HH:mm:ss"); |
| | | } |
| | | |
| | | /** |
| | | * 转换成yyyyMMdd格式的日期字符串 |
| | | * |
New file |
| | |
| | | package com.hx.util; |
| | | |
| | | import org.apache.commons.io.IOUtils; |
| | | |
| | | import java.io.OutputStream; |
| | | import java.net.HttpURLConnection; |
| | | import java.net.URL; |
| | | import java.util.Map; |
| | | |
| | | /** |
| | | * http 工具类 |
| | | */ |
| | | public class HttpMethodUtil { |
| | | |
| | | /** 请求http协议 获取信息工具 |
| | | * @param url 请求链接 |
| | | * @param data 请求数据(body) |
| | | * @param keyValues form表单数据 key参数名称,value参数值 |
| | | * @param header 请求头 |
| | | * @param requestMethod 请求头方法,默认POST |
| | | * @return |
| | | */ |
| | | public static String HttpURLUtilJson(String url, String data,Map<String,Object> keyValues,Map<String,String> header,String requestMethod) { |
| | | HttpURLConnection con = null; |
| | | URL u = null; |
| | | String wxMsgXml = null; |
| | | try { |
| | | StringBuilder dataP = new StringBuilder(); |
| | | if (keyValues != null && !keyValues.isEmpty()) { |
| | | for (Map.Entry<String, Object> entry : keyValues.entrySet()) { |
| | | dataP.append((String)entry.getKey()).append("="); |
| | | dataP.append(entry.getValue()); |
| | | dataP.append("&"); |
| | | } |
| | | System.out.println("dataP:"+dataP.toString()); |
| | | dataP.deleteCharAt(dataP.length() - 1); |
| | | url = url+"?"+dataP; |
| | | } |
| | | |
| | | if(StringUtils.isEmpty(requestMethod)){ |
| | | requestMethod = "POST"; |
| | | } |
| | | u = new URL(url); |
| | | con = (HttpURLConnection) u.openConnection(); |
| | | con.setRequestMethod(requestMethod); |
| | | con.setDoOutput(true); |
| | | con.setDoInput(true); |
| | | con.setUseCaches(false); |
| | | con.setReadTimeout(5000); |
| | | con.setRequestProperty("Charset", "UTF-8"); |
| | | con.setRequestProperty("Content-Type", "application/json"); |
| | | if(header != null){ |
| | | for (Map.Entry<String, String> entry : header.entrySet()) { |
| | | con.setRequestProperty(entry.getKey(),entry.getValue()); |
| | | } |
| | | } |
| | | |
| | | if (data != null) { |
| | | OutputStream os = con.getOutputStream(); |
| | | os.write(data.getBytes("utf-8")); |
| | | } |
| | | |
| | | if (con.getResponseCode() != 200){ |
| | | throw new RuntimeException("请求url失败:"+con.getResponseCode()); |
| | | } |
| | | // 读取返回内容 |
| | | wxMsgXml = IOUtils.toString(con.getInputStream(), "utf-8"); |
| | | // //System.out.println("HttpURLUtil:"+wxMsgXml); |
| | | } catch (Exception e) { |
| | | e.printStackTrace(); |
| | | } finally { |
| | | if (con != null) { |
| | | con.disconnect(); |
| | | } |
| | | } |
| | | return wxMsgXml; |
| | | } |
| | | |
| | | } |
New file |
| | |
| | | package com.hx.util; |
| | | |
| | | import org.apache.commons.io.IOUtils; |
| | | |
| | | import javax.servlet.http.HttpServletRequest; |
| | | import java.io.BufferedReader; |
| | | import java.io.IOException; |
| | | import java.util.Enumeration; |
| | | import java.util.HashMap; |
| | | import java.util.Map; |
| | | |
| | | /** HttpServletRequestUtil 获取请求中的body |
| | | * @author wangrenhuang |
| | | * @Date 2021-10-19 |
| | | */ |
| | | public class HttpServletRequestUtil { |
| | | |
| | | /** |
| | | * 获取bady |
| | | * */ |
| | | public static String getBody(HttpServletRequest request) { |
| | | String wxMsgXml = null; |
| | | if(request == null){ |
| | | return wxMsgXml; |
| | | } |
| | | try{ |
| | | wxMsgXml = IOUtils.toString(request.getInputStream(), |
| | | "utf-8"); |
| | | return wxMsgXml; |
| | | }catch (Exception e){ |
| | | wxMsgXml = null; |
| | | } |
| | | return wxMsgXml; |
| | | } |
| | | |
| | | |
| | | /** |
| | | * |
| | | * 获取请求头 |
| | | * */ |
| | | public static Map<String,String> getHeader(HttpServletRequest request) { |
| | | Enumeration<String> enumeration = request.getHeaderNames(); |
| | | Map<String,String> map = new HashMap<>(16); |
| | | StringBuffer headers = new StringBuffer(); |
| | | while (enumeration.hasMoreElements()) { |
| | | String name = enumeration.nextElement(); |
| | | String value = request.getHeader(name); |
| | | map.put(name,value); |
| | | } |
| | | |
| | | return map; |
| | | } |
| | | } |
New file |
| | |
| | | package com.hx.util.corp; |
| | | |
| | | import com.alibaba.fastjson.JSONObject; |
| | | import com.hx.util.HttpMethodUtil; |
| | | import com.hx.util.corp.entity.OpenIdAUserId; |
| | | import com.hx.util.corp.entity.WeiXinInfo; |
| | | import org.slf4j.Logger; |
| | | import org.slf4j.LoggerFactory; |
| | | |
| | | import java.util.HashMap; |
| | | import java.util.Map; |
| | | |
| | | /** 企业微信工具类 |
| | | * @author wangrenhuang |
| | | * @Date 2021-10-19 |
| | | */ |
| | | public class CorpMpUtil { |
| | | |
| | | //log4j日志 |
| | | private static Logger logger = LoggerFactory.getLogger(CorpMpUtil.class.getName()); |
| | | |
| | | /**链接-获取应用accessToken*/ |
| | | public static final String URL_GET_USER_INFO = "https://qyapi.weixin.qq.com/cgi-bin/user/get"; |
| | | |
| | | /**openid转userid*/ |
| | | public static final String URL_OPENID_TO_USERID = "https://qyapi.weixin.qq.com/cgi-bin/user/convert_to_userid"; |
| | | |
| | | /**userid转openid*/ |
| | | public static final String URL_USERID_TO_OPENID = "https://qyapi.weixin.qq.com/cgi-bin/user/convert_to_openid"; |
| | | |
| | | /**获取小程序链接*/ |
| | | public static final String URL_USERID_TO_APPLET = "https://api.weixin.qq.com/wxa/generate_urllink"; |
| | | |
| | | |
| | | /** |
| | | * openId获取userId |
| | | * @param openId 用户openId |
| | | * @return 返回 |
| | | */ |
| | | public static OpenIdAUserId openIdToUserId(String openId, String token) { |
| | | Map<String,Object> map=new HashMap<>(); |
| | | map.put("access_token",token); |
| | | |
| | | JSONObject data = new JSONObject(); |
| | | data.put("openid",openId); |
| | | |
| | | String datas = HttpMethodUtil.HttpURLUtilJson(URL_OPENID_TO_USERID, data.toString(), map, null, "GET"); |
| | | OpenIdAUserId openIdAUserId = JSONObject.parseObject(datas, OpenIdAUserId.class); |
| | | return openIdAUserId; |
| | | } |
| | | |
| | | |
| | | /** |
| | | * userId获取openId |
| | | * @param userid 企业员工id |
| | | * @return 返回 |
| | | */ |
| | | public static OpenIdAUserId userIdToOpenId(String userid, String token) { |
| | | Map<String,Object> map=new HashMap<>(); |
| | | map.put("access_token",token); |
| | | |
| | | JSONObject data = new JSONObject(); |
| | | data.put("userid",userid); |
| | | |
| | | String datas = HttpMethodUtil.HttpURLUtilJson(URL_USERID_TO_OPENID, data.toString(), map, null, "GET"); |
| | | OpenIdAUserId openIdAUserId = JSONObject.parseObject(datas, OpenIdAUserId.class); |
| | | return openIdAUserId; |
| | | } |
| | | |
| | | |
| | | |
| | | /** |
| | | * 获取企业微信员工信息 |
| | | * @param userId 用户id |
| | | * @return 返回 |
| | | */ |
| | | public static WeiXinInfo userInfo(String userId, String token) { |
| | | Map<String,Object> map=new HashMap<>(); |
| | | map.put("access_token",token); |
| | | map.put("userid",userId); |
| | | String datas = HttpMethodUtil.HttpURLUtilJson(URL_GET_USER_INFO, null, map, null, "GET"); |
| | | WeiXinInfo weiXinInfo = JSONObject.parseObject(datas, WeiXinInfo.class); |
| | | return weiXinInfo; |
| | | } |
| | | |
| | | } |
New file |
| | |
| | | package com.hx.util.corp.entity; |
| | | |
| | | /**openId转userid或者userid转openId接收实体 |
| | | * |
| | | */ |
| | | public class OpenIdAUserId { |
| | | |
| | | /**返回码,0表示成功*/ |
| | | private Integer errcode; |
| | | /**对返回码的文本描述内容*/ |
| | | private String errmsg; |
| | | /**企业员工userid*/ |
| | | private String userid; |
| | | /**用户openid*/ |
| | | private String openid; |
| | | |
| | | |
| | | /**状态码-成功*/ |
| | | public static final int CODE_SUCCESS = 0; |
| | | |
| | | public Integer getErrcode() { |
| | | return errcode; |
| | | } |
| | | |
| | | public void setErrcode(Integer errcode) { |
| | | this.errcode = errcode; |
| | | } |
| | | |
| | | public String getErrmsg() { |
| | | return errmsg; |
| | | } |
| | | |
| | | public void setErrmsg(String errmsg) { |
| | | this.errmsg = errmsg; |
| | | } |
| | | |
| | | public String getUserid() { |
| | | return userid; |
| | | } |
| | | |
| | | public void setUserid(String userid) { |
| | | this.userid = userid; |
| | | } |
| | | |
| | | public String getOpenid() { |
| | | return openid; |
| | | } |
| | | |
| | | public void setOpenid(String openid) { |
| | | this.openid = openid; |
| | | } |
| | | |
| | | @Override |
| | | public String toString() { |
| | | return "OpenIdAUserId{" + |
| | | "errcode=" + errcode + |
| | | ", errmsg='" + errmsg + '\'' + |
| | | ", userid='" + userid + '\'' + |
| | | ", openid='" + openid + '\'' + |
| | | '}'; |
| | | } |
| | | } |
New file |
| | |
| | | package com.hx.util.corp.entity; |
| | | |
| | | import java.io.Serializable; |
| | | |
| | | public class WeiXinInfo implements Serializable { |
| | | |
| | | //返回码 |
| | | private Integer errcode; |
| | | //对返回码的文本描述内容 |
| | | private String errmsg; |
| | | //成员UserID。对应管理端的帐号,企业内必须唯一。不区分大小写,长度为1~64个字节 |
| | | private String userid; |
| | | //成员名称;第三方不可获取,调用时返回userid以代替name;代开发自建应用需要管理员授权才返回;对于非第三方创建的成员,第三方通讯录应用也不可获取;未返回name的情况需要通过通讯录展示组件来展示名字 |
| | | private String name; |
| | | //手机号码, |
| | | private String mobile; |
| | | //职务信息; |
| | | private String position; |
| | | //性别。0表示未定义,1表示男性,2表示女性 |
| | | private Integer gender; |
| | | //邮箱, |
| | | private String email; |
| | | // 激活状态: 1=已激活,2=已禁用,4=未激活,5=退出企业。 |
| | | private Integer status; |
| | | |
| | | |
| | | public Integer getErrcode() { |
| | | return errcode; |
| | | } |
| | | |
| | | public void setErrcode(Integer errcode) { |
| | | this.errcode = errcode; |
| | | } |
| | | |
| | | public String getErrmsg() { |
| | | return errmsg; |
| | | } |
| | | |
| | | public void setErrmsg(String errmsg) { |
| | | this.errmsg = errmsg; |
| | | } |
| | | |
| | | public String getUserid() { |
| | | return userid; |
| | | } |
| | | |
| | | public void setUserid(String userid) { |
| | | this.userid = userid; |
| | | } |
| | | |
| | | public String getName() { |
| | | return name; |
| | | } |
| | | |
| | | public void setName(String name) { |
| | | this.name = name; |
| | | } |
| | | |
| | | public String getMobile() { |
| | | return mobile; |
| | | } |
| | | |
| | | public void setMobile(String mobile) { |
| | | this.mobile = mobile; |
| | | } |
| | | |
| | | public String getPosition() { |
| | | return position; |
| | | } |
| | | |
| | | public void setPosition(String position) { |
| | | this.position = position; |
| | | } |
| | | |
| | | public Integer getGender() { |
| | | return gender; |
| | | } |
| | | |
| | | public void setGender(Integer gender) { |
| | | this.gender = gender; |
| | | } |
| | | |
| | | public String getEmail() { |
| | | return email; |
| | | } |
| | | |
| | | public void setEmail(String email) { |
| | | this.email = email; |
| | | } |
| | | |
| | | public Integer getStatus() { |
| | | return status; |
| | | } |
| | | |
| | | public void setStatus(Integer status) { |
| | | this.status = status; |
| | | } |
| | | |
| | | @Override |
| | | public String toString() { |
| | | return "WeiXinInfo{" + |
| | | "errcode=" + errcode + |
| | | ", errmsg='" + errmsg + '\'' + |
| | | ", userid='" + userid + '\'' + |
| | | ", name='" + name + '\'' + |
| | | ", mobile='" + mobile + '\'' + |
| | | ", position='" + position + '\'' + |
| | | ", gender=" + gender + |
| | | ", email='" + email + '\'' + |
| | | ", status=" + status + |
| | | '}'; |
| | | } |
| | | } |
New file |
| | |
| | | package com.hx.util.rsa; |
| | | |
| | | import org.slf4j.Logger; |
| | | import org.slf4j.LoggerFactory; |
| | | import sun.misc.BASE64Decoder; |
| | | import sun.misc.BASE64Encoder; |
| | | |
| | | import javax.crypto.Cipher; |
| | | import java.io.IOException; |
| | | import java.security.*; |
| | | import java.security.spec.PKCS8EncodedKeySpec; |
| | | import java.security.spec.X509EncodedKeySpec; |
| | | |
| | | public class RSAUtil { |
| | | |
| | | //log4j日志 |
| | | private static Logger logger = LoggerFactory.getLogger(RSAUtil.class.getName()); |
| | | |
| | | /**生成秘钥对*/ |
| | | public static KeyPair getKeyPair() throws Exception { |
| | | KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA"); |
| | | keyPairGenerator.initialize(2048); |
| | | KeyPair keyPair = keyPairGenerator.generateKeyPair(); |
| | | return keyPair; |
| | | } |
| | | |
| | | /**获取公钥(Base64编码)*/ |
| | | public static String getPublicKey(KeyPair keyPair) { |
| | | PublicKey publicKey = keyPair.getPublic(); |
| | | byte[] bytes = publicKey.getEncoded(); |
| | | return byte2Base64(bytes); |
| | | } |
| | | |
| | | /**获取私钥(Base64编码)*/ |
| | | public static String getPrivateKey(KeyPair keyPair) { |
| | | PrivateKey privateKey = keyPair.getPrivate(); |
| | | byte[] bytes = privateKey.getEncoded(); |
| | | return byte2Base64(bytes); |
| | | } |
| | | |
| | | /**将Base64编码后的公钥转换成PublicKey对象*/ |
| | | public static PublicKey string2PublicKey(String pubStr) throws Exception { |
| | | byte[] keyBytes = base642Byte(pubStr); |
| | | X509EncodedKeySpec keySpec = new X509EncodedKeySpec(keyBytes); |
| | | KeyFactory keyFactory = KeyFactory.getInstance("RSA"); |
| | | PublicKey publicKey = keyFactory.generatePublic(keySpec); |
| | | return publicKey; |
| | | } |
| | | |
| | | /**将Base64编码后的私钥转换成PrivateKey对象*/ |
| | | public static PrivateKey string2PrivateKey(String priStr) throws Exception { |
| | | byte[] keyBytes = base642Byte(priStr); |
| | | PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(keyBytes); |
| | | KeyFactory keyFactory = KeyFactory.getInstance("RSA"); |
| | | PrivateKey privateKey = keyFactory.generatePrivate(keySpec); |
| | | return privateKey; |
| | | } |
| | | |
| | | /**公钥加密*/ |
| | | public static String publicEncrypt(String content, String publicKey) { |
| | | try { |
| | | Cipher cipher = Cipher.getInstance("RSA"); |
| | | cipher.init(Cipher.ENCRYPT_MODE, string2PublicKey(publicKey)); |
| | | byte[] bytes = cipher.doFinal(content.getBytes()); |
| | | return byte2Base64(bytes); |
| | | } catch (Exception e) { |
| | | //logger.error("公钥加密失败{}", e); |
| | | } |
| | | return null; |
| | | } |
| | | |
| | | /**私钥解密*/ |
| | | public static String privateDecrypt(String content, String privateKey) { |
| | | try { |
| | | Cipher cipher = Cipher.getInstance("RSA"); |
| | | cipher.init(Cipher.DECRYPT_MODE, string2PrivateKey(privateKey)); |
| | | byte[] bytes = cipher.doFinal(base642Byte(content)); |
| | | return new String(bytes); |
| | | } catch (Exception e) { |
| | | //logger.error("私钥解密失败{}", e); |
| | | } |
| | | return null; |
| | | } |
| | | |
| | | //字节数组转Base64编码 |
| | | public static String byte2Base64(byte[] bytes) { |
| | | BASE64Encoder encoder = new BASE64Encoder(); |
| | | return encoder.encode(bytes); |
| | | } |
| | | |
| | | //Base64编码转字节数组 |
| | | public static byte[] base642Byte(String base64Key) throws IOException { |
| | | BASE64Decoder decoder = new BASE64Decoder(); |
| | | return decoder.decodeBuffer(base64Key); |
| | | } |
| | | |
| | | public static void main(String[] args) { |
| | | try { |
| | | |
| | | KeyPair keyPair = getKeyPair(); |
| | | String publicKeyStr = getPublicKey(keyPair); |
| | | String privateKeyStr = getPrivateKey(keyPair); |
| | | System.out.println("publicKey:"+publicKeyStr); |
| | | System.out.println("privateKey:"+privateKeyStr); |
| | | |
| | | //String publicKeyStr = "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCWY1VKIXGStXOMtSkb2nqV9A4V6MqlTPv8Dg9Sdxm8TZgOYJJxFAjpUOwt0au6q5JDTrslZngg9um1IhNJlRLEySbTvN7Bzeq6XOpZx5w6XRZ+7/o0Ui4YvcYwIHB5DgS5XJnLa3vLqWOk4NAtY0lqC20170mHi5Fmjdak63OTzwIDAQAB"; |
| | | //=================客户端================= |
| | | String message = "jia_he"; |
| | | //用公钥加密 |
| | | String byte2Base64 = RSAUtil.publicEncrypt(message, publicKeyStr); |
| | | System.out.println("公钥加密并Base64编码的结果:" + byte2Base64); |
| | | //===================服务端================ |
| | | //String privateKeyStr = "MIICdgIBADANBgkqhkiG9w0BAQEFAASCAmAwggJcAgEAAoGBAJZjVUohcZK1c4y1KRvaepX0DhXoyqVM+/wOD1J3GbxNmA5gknEUCOlQ7C3Rq7qrkkNOuyVmeCD26bUiE0mVEsTJJtO83sHN6rpc6lnHnDpdFn7v+jRSLhi9xjAgcHkOBLlcmctre8upY6Tg0C1jSWoLbTXvSYeLkWaN1qTrc5PPAgMBAAECgYAJuQBRm5npHzwKM8glmdllCnNCrVs0lqaP5CTPcw3B485Z15qAHwh4dRff2ndcySzalyN4RoirsOrpH/vZPP8KinIhOT9zcHInWMKEPqGH+twB+c0hS6x2YZFuJqW3+zy56jnUMn3MDjNF5A5N9hD6taP1V+UOqgZvYwwMSCFLkQJBANZtQS2AqahHNjPgjkWcuaG8zXzgbu0VeU+wXDjxR81aLLJBOK6AGe7w5yJnip2w/FqGxPfORcn/bLxyDHOhpQcCQQCzi5zeeiXt1cxeGGqVxNvC51PuSna9YnPs+phiwwGVdAqVdMOJzsThs5EDVhX4eQYIeA4B6PItiPLHsw+6AXD5AkAp/ac/4+xVeeyRaC40T6bCl5ieFc1jPEtPYbgNpqJrAneySLdy5L8vXZnF0QUCMICasb2s0YY1MoH2vVbW5hbNAkEAsCxD5oFQikiI2aN3ojGhuWMnFeB3Fmlueo+ByxaxjSZp5DDIVYZP5W8+0Vk9Aawu4Ux74h/i0g9Yud7XhZo4cQJARyq8WJGDawo65CVcQQ2opbL8LqApr7Co4CAKmV4YFDraY00q9h1Dbj7WO+urJz7XUqbEYG0Yga+37jQAnQHUUQ=="; |
| | | //解密后的明文 |
| | | System.out.println("解密后的明文: " +RSAUtil.privateDecrypt(byte2Base64, privateKeyStr)); |
| | | } catch (Exception e) { |
| | | e.printStackTrace(); |
| | | } |
| | | } |
| | | } |