具体思路为:小程序前端点击按钮,弹出授权手机号窗口,用户允许后,js得到加密数据,加密向量,session_key,将这些信息传递到java后台解密,最终拿到电话号码。(直接通过js只能获取到加密数据,需要后台解密)
官方文档:获取手机号
java后台解密代码如下:
/**所需的maven依赖包
<!-- 阿里JSON解析器 -->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>${fastjson.version}</version>
</dependency>
<!-- bouncycastle-->
<dependency>
<groupId>org.bouncycastle</groupId>
<artifactId>bcprov-jdk15on</artifactId>
<version>1.54</version>
</dependency>
**/
/**
* 解密获取手机号
* @param encryptedData
* @param iv
* @param session_key
* @return
*/
@PostMapping("/getPhone")
@ResponseBody
public ResultPO mini_getPhone(@Param("encryptedData") String encryptedData, @Param("iv")String iv, @Param("session_key")String session_key)
{
ResultPO resultPO = ResultPO.success();
JSONObject obj=getPhoneNumber(session_key,encryptedData,iv);//解密电话号码
//System.out.println(obj);
String sphone=obj.get("phoneNumber").toString();
Map<String, Object> map = new HashMap<>(2);
map.put("phone",sphone);
resultPO.setData(map);
return resultPO;
}
//解析电话号码
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;
}