From a0fc599f93eeeeb678514492d72bce6b9f47c48e Mon Sep 17 00:00:00 2001 From: ChenJiaHe <763432473@qq.com> Date: 星期日, 26 十二月 2021 16:23:49 +0800 Subject: [PATCH] Merge branch 'master' of https://gitee.com/huoxiong/hx_common --- src/main/java/com/hx/util/corp/entity/OpenIdAUserId.java | 62 ++++ src/main/java/com/hx/util/BlurDataUtil.java | 119 ++++++++ src/main/java/com/hx/util/HttpMethodUtil.java | 79 +++++ pom.xml | 8 src/main/java/com/hx/redis/RedisConfig.java | 34 ++ src/main/java/com/hx/util/HttpServletRequestUtil.java | 53 +++ src/main/java/com/hx/util/HttpUtil.java | 1 src/main/java/com/hx/util/DateUtil.java | 23 + src/main/java/com/hx/util/corp/entity/WeiXinInfo.java | 113 ++++++++ src/main/java/com/hx/redis/RedisUtil.java | 131 +++++++++ src/main/java/com/hx/resultTool/ResponseCode.java | 3 src/main/java/com/hx/util/rsa/RSAUtil.java | 120 ++++++++ src/main/java/com/hx/util/corp/CorpMpUtil.java | 86 ++++++ 13 files changed, 831 insertions(+), 1 deletions(-) diff --git a/pom.xml b/pom.xml index 852c3fe..8cc4bb0 100644 --- a/pom.xml +++ b/pom.xml @@ -278,10 +278,16 @@ <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> diff --git a/src/main/java/com/hx/redis/RedisConfig.java b/src/main/java/com/hx/redis/RedisConfig.java new file mode 100644 index 0000000..834af2f --- /dev/null +++ b/src/main/java/com/hx/redis/RedisConfig.java @@ -0,0 +1,34 @@ +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; + } +} diff --git a/src/main/java/com/hx/redis/RedisUtil.java b/src/main/java/com/hx/redis/RedisUtil.java new file mode 100644 index 0000000..0861d12 --- /dev/null +++ b/src/main/java/com/hx/redis/RedisUtil.java @@ -0,0 +1,131 @@ +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; + + } + + } + +} + diff --git a/src/main/java/com/hx/resultTool/ResponseCode.java b/src/main/java/com/hx/resultTool/ResponseCode.java index 303bf2d..73e2f9a 100644 --- a/src/main/java/com/hx/resultTool/ResponseCode.java +++ b/src/main/java/com/hx/resultTool/ResponseCode.java @@ -6,6 +6,7 @@ * @Data: 2020-06-20 */ public final class ResponseCode { + /*鎴愬姛*/ public static final String SUCCESS = "100"; /*閿欒鎻愮ず锛屽墠绔牴鎹繖涓爜寮瑰嚭鎻愮ず*/ @@ -20,6 +21,8 @@ public static final String ERROR_LOGIN="603"; /*绯荤粺寮傚父*/ public static final String ERROR_SYSTEM = "999"; + /*绛惧悕閿欒*/ + public static final String ERROR_SIGN = "203"; diff --git a/src/main/java/com/hx/util/BlurDataUtil.java b/src/main/java/com/hx/util/BlurDataUtil.java new file mode 100644 index 0000000..bef9fd0 --- /dev/null +++ b/src/main/java/com/hx/util/BlurDataUtil.java @@ -0,0 +1,119 @@ +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锛圤VERLAY锛夛細鏇挎崲鍚庣殑瀛楃涓诧紝 + * 鍙傛暟3锛圫TART锛夛細鏇挎崲鐨勮捣濮嬩笅鏍囷紝鍙傛暟4锛圗ND锛夛細鏇挎崲鐨勭粨鏉熶笅鏍囷紙涓嶅寘鍚級 + */ + 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锛岃劚鏁忓悗锛歾hang***@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銆丼tring.replaceAll(绗�1涓弬鏁版槸鑴辨晱绛涢�夌殑姝e垯锛岀2涓弬鏁版槸鑴辨晱鏇挎崲鐨勬鍒�) + * 2銆侀渶瑕佸紩鍏ommons-lang3锛岃繖涓熀鏈瘡涓」鐩兘鐢ㄥ埌 + * <dependency> + * <groupId>org.apache.commons</groupId> + * <artifactId>commons-lang3</artifactId> + * <version>3.7</version> + * </dependency> + */ +} \ No newline at end of file diff --git a/src/main/java/com/hx/util/DateUtil.java b/src/main/java/com/hx/util/DateUtil.java index 60e7d19..9669b94 100644 --- a/src/main/java/com/hx/util/DateUtil.java +++ b/src/main/java/com/hx/util/DateUtil.java @@ -26,6 +26,18 @@ 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 鏃堕棿鏍煎紡 @@ -39,6 +51,17 @@ 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"); + } + /** * 杞崲鎴恲yyyMMdd鏍煎紡鐨勬棩鏈熷瓧绗︿覆 * diff --git a/src/main/java/com/hx/util/HttpMethodUtil.java b/src/main/java/com/hx/util/HttpMethodUtil.java new file mode 100644 index 0000000..0ce4fea --- /dev/null +++ b/src/main/java/com/hx/util/HttpMethodUtil.java @@ -0,0 +1,79 @@ +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鍙傛暟鍚嶇О锛寁alue鍙傛暟鍊� + * @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; + } + +} diff --git a/src/main/java/com/hx/util/HttpServletRequestUtil.java b/src/main/java/com/hx/util/HttpServletRequestUtil.java new file mode 100644 index 0000000..ded443f --- /dev/null +++ b/src/main/java/com/hx/util/HttpServletRequestUtil.java @@ -0,0 +1,53 @@ +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; + } +} diff --git a/src/main/java/com/hx/util/HttpUtil.java b/src/main/java/com/hx/util/HttpUtil.java index a043cf0..64b77f6 100644 --- a/src/main/java/com/hx/util/HttpUtil.java +++ b/src/main/java/com/hx/util/HttpUtil.java @@ -654,4 +654,5 @@ } return res; } + } diff --git a/src/main/java/com/hx/util/corp/CorpMpUtil.java b/src/main/java/com/hx/util/corp/CorpMpUtil.java new file mode 100644 index 0000000..a10a8dd --- /dev/null +++ b/src/main/java/com/hx/util/corp/CorpMpUtil.java @@ -0,0 +1,86 @@ +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杞瑄serid*/ + public static final String URL_OPENID_TO_USERID = "https://qyapi.weixin.qq.com/cgi-bin/user/convert_to_userid"; + + /**userid杞琽penid*/ + 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; + } + +} diff --git a/src/main/java/com/hx/util/corp/entity/OpenIdAUserId.java b/src/main/java/com/hx/util/corp/entity/OpenIdAUserId.java new file mode 100644 index 0000000..07cc69b --- /dev/null +++ b/src/main/java/com/hx/util/corp/entity/OpenIdAUserId.java @@ -0,0 +1,62 @@ +package com.hx.util.corp.entity; + +/**openId杞瑄serid鎴栬�卽serid杞琽penId鎺ユ敹瀹炰綋 + * + */ +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 + '\'' + + '}'; + } +} diff --git a/src/main/java/com/hx/util/corp/entity/WeiXinInfo.java b/src/main/java/com/hx/util/corp/entity/WeiXinInfo.java new file mode 100644 index 0000000..702977c --- /dev/null +++ b/src/main/java/com/hx/util/corp/entity/WeiXinInfo.java @@ -0,0 +1,113 @@ +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浠ヤ唬鏇縩ame锛涗唬寮�鍙戣嚜寤哄簲鐢ㄩ渶瑕佺鐞嗗憳鎺堟潈鎵嶈繑鍥烇紱瀵逛簬闈炵涓夋柟鍒涘缓鐨勬垚鍛橈紝绗笁鏂归�氳褰曞簲鐢ㄤ篃涓嶅彲鑾峰彇锛涙湭杩斿洖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 + + '}'; + } +} diff --git a/src/main/java/com/hx/util/rsa/RSAUtil.java b/src/main/java/com/hx/util/rsa/RSAUtil.java new file mode 100644 index 0000000..20bb3f0 --- /dev/null +++ b/src/main/java/com/hx/util/rsa/RSAUtil.java @@ -0,0 +1,120 @@ +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); + } + + /**灏咮ase64缂栫爜鍚庣殑鍏挜杞崲鎴怭ublicKey瀵硅薄*/ + 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; + } + + /**灏咮ase64缂栫爜鍚庣殑绉侀挜杞崲鎴怭rivateKey瀵硅薄*/ + 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; + } + + /**绉侀挜瑙e瘑*/ + 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瘑澶辫触{}", e); + } + return null; + } + + //瀛楄妭鏁扮粍杞珺ase64缂栫爜 + 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("鍏挜鍔犲瘑骞禕ase64缂栫爜鐨勭粨鏋滐細" + byte2Base64); + //===================鏈嶅姟绔�================ + //String privateKeyStr = "MIICdgIBADANBgkqhkiG9w0BAQEFAASCAmAwggJcAgEAAoGBAJZjVUohcZK1c4y1KRvaepX0DhXoyqVM+/wOD1J3GbxNmA5gknEUCOlQ7C3Rq7qrkkNOuyVmeCD26bUiE0mVEsTJJtO83sHN6rpc6lnHnDpdFn7v+jRSLhi9xjAgcHkOBLlcmctre8upY6Tg0C1jSWoLbTXvSYeLkWaN1qTrc5PPAgMBAAECgYAJuQBRm5npHzwKM8glmdllCnNCrVs0lqaP5CTPcw3B485Z15qAHwh4dRff2ndcySzalyN4RoirsOrpH/vZPP8KinIhOT9zcHInWMKEPqGH+twB+c0hS6x2YZFuJqW3+zy56jnUMn3MDjNF5A5N9hD6taP1V+UOqgZvYwwMSCFLkQJBANZtQS2AqahHNjPgjkWcuaG8zXzgbu0VeU+wXDjxR81aLLJBOK6AGe7w5yJnip2w/FqGxPfORcn/bLxyDHOhpQcCQQCzi5zeeiXt1cxeGGqVxNvC51PuSna9YnPs+phiwwGVdAqVdMOJzsThs5EDVhX4eQYIeA4B6PItiPLHsw+6AXD5AkAp/ac/4+xVeeyRaC40T6bCl5ieFc1jPEtPYbgNpqJrAneySLdy5L8vXZnF0QUCMICasb2s0YY1MoH2vVbW5hbNAkEAsCxD5oFQikiI2aN3ojGhuWMnFeB3Fmlueo+ByxaxjSZp5DDIVYZP5W8+0Vk9Aawu4Ux74h/i0g9Yud7XhZo4cQJARyq8WJGDawo65CVcQQ2opbL8LqApr7Co4CAKmV4YFDraY00q9h1Dbj7WO+urJz7XUqbEYG0Yga+37jQAnQHUUQ=="; + //瑙e瘑鍚庣殑鏄庢枃 + System.out.println("瑙e瘑鍚庣殑鏄庢枃: " +RSAUtil.privateDecrypt(byte2Base64, privateKeyStr)); + } catch (Exception e) { + e.printStackTrace(); + } + } +} -- Gitblit v1.8.0