微信小程序 Java 服务端 获取手机号

本文介绍了如何使用Java实现微信小程序中encryptedData、iv和sessionKey的解密过程,以获取用户手机号。通过调用微信提供的API获取encryptedData和iv,然后结合sessionKey,利用AES/CBC/NoPadding算法进行解密。示例代码详细展示了解密步骤,对于微信小程序的后端开发具有参考价值。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

获取encryptedData和iv请参考:

https://developers.weixin.qq.com/miniprogram/dev/framework/open-ability/getPhoneNumber.html

获取微信sessionKey请参考:

https://developers.weixin.qq.com/miniprogram/dev/api-backend/open-api/login/auth.code2Session.html

后台根据encryptedData\iv\sessionKey解密获取手机号

import org.apache.commons.codec.binary.Base64;
import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.security.AlgorithmParameters;
import java.util.Arrays;

public class Main {
    private static final Charset UTF_8 =  StandardCharsets.UTF_8;

    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);
    }

    public static String decrypt(String sessionKey, String encryptedData, String iv) {
        try {
            AlgorithmParameters params = AlgorithmParameters.getInstance("AES");
            params.init(new IvParameterSpec(Base64.decodeBase64(iv)));
            Cipher cipher = Cipher.getInstance("AES/CBC/NoPadding");
            cipher.init(2, new SecretKeySpec(Base64.decodeBase64(sessionKey), "AES"), params);
            return new String(decode(cipher.doFinal(Base64.decodeBase64(encryptedData))), UTF_8);
        } catch (Exception e) {
            throw new RuntimeException("AES解密失败!", e);
        }
    }

    public static void main(String[] args) {
        String sessionKey = "xxxxx";
        String encryptedData = "xxxxx";
        String iv = "xxxxxx";
        System.out.println(decrypt(sessionKey,encryptedData,iv));
    }

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值