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