搜索
首页微信小程序小程序开发微信小程序java实现AES解密并获取unionId

如果大家使用小程序的同时还在使用公众号的话,可能会用到unionId这种功能,由于公司业务需要,我们需要使用unionId,具体使用方法,请参考微信开放平台的说明,但是在微信小程序的文档中只给出了部分语言实现的源码,竟然没有java的,小程序的开发人员是有多么懒。难道大家都不用java写后台???


什么鬼,然后开始了各种AES踩坑之路,其实参考了很多的网上的教程,再次不能一一列出来给大家了,(因为我写这篇文章的时候,已经是解决问题一周以后了),也收到管理员的很多帮助,再次写个帖子回馈大家吧,在此只列出unionId的解密方式,如果有什么问题,联系我或者回帖都可以。


另外稍加吐槽一下, 

https 不要用startcom提供的免费证书! 

https 不要用startcom提供的免费证书! 

https 不要用startcom提供的免费证书!


重要的事情说三遍!!!!


AES.java

import org.apache.commons.codec.binary.Base64;import org.bouncycastle.jce.provider.BouncyCastleProvider;import javax.crypto.BadPaddingException;import javax.crypto.Cipher;import javax.crypto.IllegalBlockSizeException;import javax.crypto.NoSuchPaddingException;import javax.crypto.spec.IvParameterSpec;import javax.crypto.spec.SecretKeySpec;import java.security.*;public class AES {    public static boolean initialized = false;    /**
     * AES解密
     * @param content 密文
     * @return
     * @throws InvalidAlgorithmParameterException
     * @throws NoSuchProviderException
     */
    public byte[] decrypt(byte[] content, byte[] keyByte, byte[] ivByte) throws InvalidAlgorithmParameterException {
        initialize();        try {
            Cipher cipher = Cipher.getInstance("AES/CBC/PKCS7Padding");
            Key sKeySpec = new SecretKeySpec(keyByte, "AES");
            cipher.init(Cipher.DECRYPT_MODE, sKeySpec, generateIV(ivByte));// 初始化
            byte[] result = cipher.doFinal(content);            return result;
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        } catch (NoSuchPaddingException e) {
            e.printStackTrace();
        } catch (InvalidKeyException e) {
            e.printStackTrace();
        } catch (IllegalBlockSizeException e) {
            e.printStackTrace();
        } catch (BadPaddingException e) {
            e.printStackTrace();
        } catch (NoSuchProviderException e) {            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (Exception e) {            // TODO Auto-generated catch block
            e.printStackTrace();
        }        return null;
    }    public static void initialize(){        if (initialized) return;
        Security.addProvider(new BouncyCastleProvider());
        initialized = true;
    }    //生成iv
    public static AlgorithmParameters generateIV(byte[] iv) throws Exception{
        AlgorithmParameters params = AlgorithmParameters.getInstance("AES");
        params.init(new IvParameterSpec(iv));        return params;
    }
}

WxPKCS7Encoder.java

import java.nio.charset.Charset;import java.util.Arrays;/**
* Created by Kevin Dong on 2017/1/5.
*/public class WxPKCS7Encoder {    private static final Charset CHARSET = Charset.forName("utf-8");    private static final int BLOCK_SIZE = 32;    /**
     * 获得对明文进行补位填充的字节.
     *
     * @param count 需要进行填充补位操作的明文字节个数
     * @return 补齐用的字节数组
     */
    public static byte[] encode(int count) {        // 计算需要填充的位数
        int amountToPad = BLOCK_SIZE - (count % BLOCK_SIZE);        if (amountToPad == 0) {
            amountToPad = BLOCK_SIZE;
        }        // 获得补位所用的字符
        char padChr = chr(amountToPad);
        String tmp = new String();        for (int index = 0; index < amountToPad; index++) {
            tmp += padChr;
        }        return tmp.getBytes(CHARSET);
    }    /**
     * 删除解密后明文的补位字符
     *
     * @param decrypted 解密后的明文
     * @return 删除补位字符后的明文
     */
    public static byte[] decode(byte[] decrypted) {        int pad = decrypted[decrypted.length - 1];        if (pad < 1 || pad > 32) {
            pad = 0;
        }        return Arrays.copyOfRange(decrypted, 0, decrypted.length - pad);
    }    /**
     * 将数字转化成ASCII码对应的字符,用于对明文进行补码
     *
     * @param a 需要转化的数字
     * @return 转化得到的字符
     */
    public static char chr(int a) {        byte target = (byte) (a & 0xFF);        return (char) target;
    }
}

调用方法解密如下:

WechatOpenIdRes wechatInfo  = getWehatInfoByCode(code);        if(wechatInfo != null && wechatInfo.isOk()){            boolean isNew = true;            try {
                AES aes = new AES();                byte[] resultByte = aes.decrypt(Base64.decodeBase64(encryptedData), Base64.decodeBase64(wechatInfo.getSession_key()), Base64.decodeBase64(iv));                if(null != resultByte && resultByte.length > 0){
                    String userInfo = new String(WxPKCS7Encoder.decode(resultByte));
                    WxInfo wxInfo = GsonUtil.fromGson(userInfo, WxInfo.class);                    if(wxInfo != null) {
                        logger.debug("xxxxxunionid===="+wxInfo.getUnionId());
                    }
                }
            } catch (InvalidAlgorithmParameterException e) {
                e.printStackTrace();
            } catch (Exception e) {
                e.printStackTrace();
            }

编译环境为java1.8 

另外我引入的support 包为 

bcprov-jdk16-139.jar 此包已上传附件, 

顺带附上我试用的小程序js中的代码吧,

var code ="";
wechat.login()
      .then(function(res){
        code = res.code;        
      })
      .then(function(){        return wechat.getUserInfo();
      })
      .then(function(res){var encryptedData = res.encryptedDatavar iv = res.iv;return userservice.getUserToken(code,encryptedData,iv);
      })

上面的代码使用了promise,其中最后一句userservice.getUserToken为请求服务器的方法,参数为获取到的code+加密内容+初始化向量

更多微信小程序java实现AES解密并获取unionId相关文章请关注PHP中文网!

声明
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn

热AI工具

Undresser.AI Undress

Undresser.AI Undress

人工智能驱动的应用程序,用于创建逼真的裸体照片

AI Clothes Remover

AI Clothes Remover

用于从照片中去除衣服的在线人工智能工具。

Undress AI Tool

Undress AI Tool

免费脱衣服图片

Clothoff.io

Clothoff.io

AI脱衣机

Video Face Swap

Video Face Swap

使用我们完全免费的人工智能换脸工具轻松在任何视频中换脸!

热门文章

热工具

螳螂BT

螳螂BT

Mantis是一个易于部署的基于Web的缺陷跟踪工具,用于帮助产品缺陷跟踪。它需要PHP、MySQL和一个Web服务器。请查看我们的演示和托管服务。

SublimeText3 英文版

SublimeText3 英文版

推荐:为Win版本,支持代码提示!

MinGW - 适用于 Windows 的极简 GNU

MinGW - 适用于 Windows 的极简 GNU

这个项目正在迁移到osdn.net/projects/mingw的过程中,你可以继续在那里关注我们。MinGW:GNU编译器集合(GCC)的本地Windows移植版本,可自由分发的导入库和用于构建本地Windows应用程序的头文件;包括对MSVC运行时的扩展,以支持C99功能。MinGW的所有软件都可以在64位Windows平台上运行。

DVWA

DVWA

Damn Vulnerable Web App (DVWA) 是一个PHP/MySQL的Web应用程序,非常容易受到攻击。它的主要目标是成为安全专业人员在合法环境中测试自己的技能和工具的辅助工具,帮助Web开发人员更好地理解保护Web应用程序的过程,并帮助教师/学生在课堂环境中教授/学习Web应用程序安全。DVWA的目标是通过简单直接的界面练习一些最常见的Web漏洞,难度各不相同。请注意,该软件中

EditPlus 中文破解版

EditPlus 中文破解版

体积小,语法高亮,不支持代码提示功能