小程序登录和解密

微信官方参考文档:https://developers.weixin.qq.com/miniprogram/dev/api/open-api/login/wx.login.html

微信登录

/**
* 
* @param code          微信启示拿到的code
* @param wxName     微信昵称
* @param photo          微信头像
*/
@RequestMapping(method = RequestMethod.POST, value = "login")
@UserEvent(desc = "微信首次登录接口")
public ResultBean login(String code, String wxName, String photo) {
    ResultBean result = new ResultBean();
    // 小程序appID
    String appid = WechatConstants.APPID;
    // 小程序密钥
    String appsecret = WechatConstants.APPSECRET;
    // 授权(必填)
    String grant_type = "authorization_code";
    // URL
    String url = "https://api.weixin.qq.com/sns/jscode2session";
    // 请求参数
    String params = "appid=" + appid + "&secret=" + appsecret + "&js_code=" + code + "&grant_type=" + grant_type;
    // 发送请求
    String data = HttpUtil.get(url, params);
    // 解析相应内容(转换成json对象)
    JSONObject json = JSONObject.parseObject(data);
    System.out.println(json);
    System.out.println("传进来的wxname:" + wxName);
    try {
        // 将微信昵称转成base64存库,解决微信昵称含有表情问题
        wxName = Base64.encodeBase64String(wxName.getBytes("UTF-8"));
    } catch (Exception e) {
        e.printStackTrace();
    }
    System.out.println("登入成功");
    result.setMsg("登入成功");
    result.setStatus(ResultBean.SUCCESS);
    result.setObjs(new Object[] { json });
    return result;
}

httputil工具类

    public class HttpUtil {
        /**
        * 向指定URL发送GET方法的请求
        *
        * @param url
        * 发送请求的URL
        * @param param
        * 请求参数,请求参数应该是 name1=value1&name2=value2 的形式。
        * @return String 所代表远程资源的响应结果
        */
        public static String get(String url,String param){
            String result = "";
            BufferedReader in = null;
            try {
                String urlNameString = url + "?" + param;
                //System.out.println(urlNameString);
                URL realUrl = new URL(urlNameString);
                // 打开和URL之间的连接
                URLConnection connection = realUrl.openConnection();
                // 设置通用的请求属性
                connection.setRequestProperty("accept", "*/*");
                connection.setRequestProperty("connection", "Keep-Alive");
                connection.setRequestProperty("user-agent",
                "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
                // 建立实际的连接
                connection.connect();
                // 获取所有响应头字段
                //Map<String, List<String>> map = connection.getHeaderFields();
                // 遍历所有的响应头字段
                /*for (String key : map.keySet()) {
                    System.out.println(key + "--->" + map.get(key));
                }*/
                // 定义 BufferedReader输入流来读取URL的响应
                in = new BufferedReader(new InputStreamReader(
                connection.getInputStream()));
                String line;
                while ((line = in.readLine()) != null) {
                    result += line;
                }
            } catch (Exception e) {
                System.out.println("发送GET请求出现异常!" + e);
                e.printStackTrace();
            }
            // 使用finally块来关闭输入流
            finally {
                try {
                    if (in != null) {
                        in.close();
                    }
                } catch (Exception e2) {
                    e2.printStackTrace();
                }
            }
            return result;
        }
    
        private static void trustAllHttpsCertificates() throws Exception { 
            TrustManager[] trustAllCerts = new TrustManager[1]; 
            TrustManager tm = new miTM(); 
            trustAllCerts[0] = tm; 
            SSLContext sc = SSLContext.getInstance("SSL"); 
            sc.init(null, trustAllCerts, null); 
            HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory()); 
        } 
    
        static class miTM implements TrustManager,X509TrustManager { 
            public X509Certificate[] getAcceptedIssuers() { 
            return null; 
        } 
    
        public boolean isServerTrusted(X509Certificate[] certs) { 
            return true; 
        } 
    
        public boolean isClientTrusted(X509Certificate[] certs) { 
            return true; 
        } 
    
        public void checkServerTrusted(X509Certificate[] certs, String authType) 
    throws CertificateException { 
            return; 
        } 
    
        public void checkClientTrusted(X509Certificate[] certs, String authType) 
    throws CertificateException { 
            return; 
        } 
    } 

/** 
* 忽略HTTPS请求的SSL证书,必须在openConnection之前调用 
* @throws Exception 
*/ 
    public static void ignoreSsl() throws Exception{ 
        HostnameVerifier hv = new HostnameVerifier() { 
        public boolean verify(String urlHostName, SSLSession session) { 
        System.out.println("Warning: URL Host: " + urlHostName + " vs. " + session.getPeerHost()); 
        return true; 
        } 
    }; 
    trustAllHttpsCertificates(); 
    HttpsURLConnection.setDefaultHostnameVerifier(hv); 
    }
}

解密openId

@RequestMapping(method = RequestMethod.POST, value = "decrypt")
@UserEvent(desc = "微信解密openId")
public ResultBean decrypt(String encryptedData, String session_key, String iv) {
    /*
    * String encryptedData = request.getParameter("encryptedData"); String
    * session_key = request.getParameter("session_key"); String iv =
    * request.getParameter("iv");
    */
    ResultBean resultBean = new ResultBean();
    String result;
    try {
        result = AesCbcUtil.decrypt(encryptedData, session_key, iv, "UTF-8");
        if (null != result && result.length() > 0) {
            System.out.println("解密成功");
            JSONObject userInfoJSON = JSONObject.parseObject(result);
            resultBean.setStatus(ResultBean.SUCCESS);
            resultBean.setObjs(new Object[] { userInfoJSON });
        } else {
            System.out.println("解密失败");
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
    return resultBean;
}

解密工具类

public class AesCbcUtil {


    static {
    //BouncyCastle是一个开源的加解密解决方案,主页在http://www.bouncycastle.org/
    //Security.addProvider(new BouncyCastleProvider());
    }

    /**
    * AES解密
    *
    * @param data //密文,被加密的数据
    * @param key //秘钥
    * @param iv //偏移量
    * @param encodingFormat //解密后的结果需要进行的编码
    * @return
    * @throws Exception
    */
    public static String decrypt(String data, String key, String iv, String encodingFormat) throws Exception {
         // initialize();

        //被加密的数据
        byte[] dataByte = Base64.decodeBase64(data);
        //加密秘钥
        byte[] keyByte = Base64.decodeBase64(key);
        //偏移量
        byte[] ivByte = Base64.decodeBase64(iv);


        try {
            Cipher cipher = Cipher.getInstance("AES/CBC/PKCS7Padding");

            SecretKeySpec spec = new SecretKeySpec(keyByte, "AES");

            AlgorithmParameters parameters = AlgorithmParameters.getInstance("AES");
            parameters.init(new IvParameterSpec(ivByte));

            cipher.init(Cipher.DECRYPT_MODE, spec, parameters);// 初始化

            byte[] resultByte = cipher.doFinal(dataByte);
            if (null != resultByte && resultByte.length > 0) {
                String result = new String(resultByte, encodingFormat);
                return result;
            }
            return null;
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        } catch (NoSuchPaddingException e) {
            e.printStackTrace();
        } catch (InvalidParameterSpecException e) {
            e.printStackTrace();
        } catch (InvalidKeyException e) {
            e.printStackTrace();
        } catch (InvalidAlgorithmParameterException e) {
            e.printStackTrace();
        } catch (IllegalBlockSizeException e) {
            e.printStackTrace();
        } catch (BadPaddingException e) {
            e.printStackTrace();
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }

        return null;
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值