微信小程序加密数据解密的java实现

首先借鉴了两篇文章:

http://www.cnblogs.com/nosqlcoco/p/6105749.html

http://blog.csdn.net/sinat_29519243/article/details/70186622


首先吐槽一下,微信小程序这个设计,其实密文中包含的用于开发的有用信息并不是很多。...

解密后的类似:

{"openId":"oy9H90Nqxxxxxxxxxxx0BJmuw",

"nickName":"xxxxxxxxx",

"gender":1,

"language":"zh_CN",

"city":"city",

"province":"province",

"country":"country",

"avatarUrl":"https://wx.qlogo.cn/mmopen/vi_32/xxxxxxxxOcvbibeJxx0",

"watermark":{"timestamp":timestamp,"appid":"wx58b6xxxxxxxxx627"

}



解密需要登录的时候 提供的几个参数:

1. 密文:encryptedData

2. session_key

3. 偏移向量 iv


登录的几个东西如何获取这里简单说下:

1. session_ID的获取:wx.login()函数的返回里面包含了CODE.利用这个CODE,到这个地址去交换:

https://api.weixin.qq.com/sns/jscode2session?grant_type=authorization_code&js_code=CODE&appid=APPID&secret=APP_SRCRET。

2. iv和encryptedData的获取:wx.getUserInfo()的调用的时候,同时设置属性withCredentials: true,


wx.getUserInfo({ withCredentials: true, success: function(res) { console.log(res) that.globalData.userInfo = res.userInfo typeof cb == "function" && cb(that.globalData.userInfo) } })


就可以获取到所有的参数。


============================= 分割线 ========================================


java侧实现解密需要如下的包:

1. bcprov-jdk15on-157.jar ----主要是AES解码

2. commons-codec-1.10.jar ----主要是base64编码


核心代码:

 

Map map = new HashMap();  
       try {  
               byte[] resultByte  = AES.decrypt(Base64.decodeBase64(encryptedData),  
                       Base64.decodeBase64(session_key),
                       Base64.decodeBase64(iv));  
                   if(null != resultByte && resultByte.length > 0){  
                       String userInfo = new String(resultByte, "UTF-8");                 
                       map.put("status", "1");  
                       map.put("msg", "解密成功");                 
                       map.put("userInfo", userInfo);  
                   }else{  
                       map.put("status", "0");  
                       map.put("msg", "解密失败");  
                   }  
           }catch (InvalidAlgorithmParameterException e) {  
                   e.printStackTrace();  
           } catch (UnsupportedEncodingException e) {  
                   e.printStackTrace();  
           }                
           Gson gson = new Gson();  
           String decodeJSON = gson.toJson(map);  
           System.out.println(decodeJSON); 



其中

AES代码:

package com.aes;


import org.bouncycastle.jce.provider.BouncyCastleProvider;  
import java.security.AlgorithmParameters;
import java.security.InvalidAlgorithmParameterException;
import java.security.InvalidKeyException;
import java.security.Key;
import java.security.NoSuchAlgorithmException;
import java.security.NoSuchProviderException;
import java.security.Security;


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;


public class AES {
public static boolean initialized = false;    
    
    /** 
     * AES解密 
     * @param content 密文 
     * @return 
     * @throws InvalidAlgorithmParameterException  
     * @throws NoSuchProviderException  
     */  
    public static 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;    
    }     


}



  • 4
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 9
    评论
微信小程序解密并获取手机号的过程可以通过以下步骤实现: 1. 在小程序端,用户点击授权获取手机号的按钮,触发相应的事件。 2. 小程序调用`wx.login`接口获取临时登录凭证code。 3. 小程序调用`wx.getUserInfo`接口获取用户信息,其中包括加密的手机号信息。 4. 小程序将获取到的code和加密的手机号信息发送给后端服务器。 5. 后端服务器使用微信提供的解密算法对加密的手机号进行解密。在Java中,可以使用`javax.crypto`包下的相关类来实现解密操作。 6. 解密后的手机号可以用于后续的业务逻辑处理。 下面是一个示例代码,演示了如何在Java解密微信小程序的手机号: ```java import javax.crypto.Cipher; import javax.crypto.spec.IvParameterSpec; import javax.crypto.spec.SecretKeySpec; import java.util.Base64; public class WeChatPhoneNumberDecryptor { public static String decryptPhoneNumber(String sessionKey, String encryptedData, String iv) throws Exception { byte[] sessionKeyBytes = Base64.getDecoder().decode(sessionKey); byte[] encryptedDataBytes = Base64.getDecoder().decode(encryptedData); byte[] ivBytes = Base64.getDecoder().decode(iv); SecretKeySpec secretKeySpec = new SecretKeySpec(sessionKeyBytes, "AES"); Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding"); IvParameterSpec ivParameterSpec = new IvParameterSpec(ivBytes); cipher.init(Cipher.DECRYPT_MODE, secretKeySpec, ivParameterSpec); byte[] decryptedDataBytes = cipher.doFinal(encryptedDataBytes); return new String(decryptedDataBytes); } public static void main(String[] args) { String sessionKey = "xxxxxxxxxxxxxxxxxxxxxxxxxxxx"; String encryptedData = "xxxxxxxxxxxxxxxxxxxxxxxxxxxx"; String iv = "xxxxxxxxxxxxxxxxxxxxxxxxxxxx"; try { String phoneNumber = decryptPhoneNumber(sessionKey, encryptedData, iv); System.out.println("Decrypted phone number: " + phoneNumber); } catch (Exception e) { e.printStackTrace(); } } } ``` 请注意,上述代码中的`sessionKey`、`encryptedData`和`iv`需要替换为实际的值。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值