微信小程序传参到后端解析出手机号(java实现)

需要的Maven依赖


<dependency>
    <groupId>com.alibaba</groupId>
    <artifactId>fastjson</artifactId>
    <version>1.2.15</version>
</dependency>

<dependency>
    <groupId>org.bouncycastle</groupId>
    <artifactId>bcprov-jdk15on</artifactId>
    <version>1.54</version>
</dependency>

Controller层 接受小程序端的传参 data / iv / session_key 进行解析

@PostMapping("/miniGetPhone")
@ResponseBody
public ResultMap miniGetPhone(HttpServletRequest request, String encryptedData, String iv, String session_key)
{
    JSONObject obj=getPhoneNumber(session_key,encryptedData,iv);//解密电话号码
    String sphone=obj.get("phoneNumber").toString();
    if(obj.isEmpty() && sphone==null){
        return ResultMap.error().put("手机号解密失败!",400);
    }else {
        return ResultMap.ok().put("uphone",sphone);
    }
}

//解析电话号码
public JSONObject getPhoneNumber(String session_key, String encryptedData, String iv) {
   byte[] dataByte = Base64.decode(encryptedData);
    byte[] keyByte = Base64.decode(session_key);
    byte[] ivByte = Base64.decode(iv);
    try {
        int base = 16;
        if (keyByte.length % base != 0) {
            int groups = keyByte.length / base + (keyByte.length % base != 0 ? 1 : 0);
            byte[] temp = new byte[groups * base];
            Arrays.fill(temp, (byte) 0);
            System.arraycopy(keyByte, 0, temp, 0, keyByte.length);
            keyByte = temp;
        }
        // 初始化
        Security.addProvider(new BouncyCastleProvider());
        Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
        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, "UTF-8");
            return JSONObject.parseObject(result);
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
    return null;

}

以上为java后端解析手机号的简单实现。好记性不如烂笔头~

你可能感兴趣的:(微信小程序传参到后端解析出手机号(java实现))