欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

微信授权

程序员文章站 2024-02-18 18:17:40
...

项目场景:微信授权

问题描述:根据code值获取手机号

步骤一:
String result = “”;
WxMaJscode2SessionResult session = null;
try {
session = wxMaService.getUserService().getSessionInfo(dto.getCode());//code是前端给的code,可以配置多个小程序
} catch (WxErrorException e) {
throw new RuntimeException(“获取微信 Session 异常”);
}
String openId = session.getOpenid();
String sessionKey = session.getSessionKey();

	String decrypt = WXCore.decrypt(dto.getAppid(), dto.getEncryptedData(), sessionKey, dto.getIv());
 	JSONObject jsonObject = JSON.parseObject(decrypt);
    String phoneNumber1 = jsonObject.getString("phoneNumber");//获取微信授权的手机号

步骤二:
try {
AES aes = new AES();
result = aes.decryptNew(encryptedData, sessionKey, iv);
} catch (Exception e) {
result = “”;
e.printStackTrace();
}

步骤三: AES 工具
public byte[] decrypt(byte[] content, byte[] keyByte, byte[] ivByte) throws InvalidAlgorithmParameterException {
initialize();
try {
Cipher cipher = Cipher.getInstance(“AES/CBC/PKCS7Padding”);
SecretKeySpec 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;
}
public  String decryptNew(String encryptedData, String sessionKey, String iv)  {
    String result = "";
    // 被加密的数据
    byte[] dataByte = Base64.decodeBase64(encryptedData);
    // 加密秘钥
    byte[] keyByte = Base64.decodeBase64(sessionKey);
    // 偏移量
    byte[] ivByte = Base64.decodeBase64(iv);
    try {
        // 如果**不足16位,那么就补足. 这个if 中的内容很重要
        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/PKCS7Padding", "BC");
        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) {
            result = new String(resultByte, "UTF-8");
        }
    } catch (NoSuchAlgorithmException e) {
        log.error(e.getMessage(), e);
    } catch (NoSuchPaddingException e) {
        log.error(e.getMessage(), e);
    } catch (InvalidParameterSpecException e) {
        log.error(e.getMessage(), e);
    } catch (IllegalBlockSizeException e) {
        log.error(e.getMessage(), e);
    } catch (BadPaddingException e) {
        log.error(e.getMessage(), e);
    } catch (UnsupportedEncodingException e) {
        log.error(e.getMessage(), e);
    } catch (InvalidKeyException e) {
        log.error(e.getMessage(), e);
    } catch (InvalidAlgorithmParameterException e) {
        log.error(e.getMessage(), e);
    } catch (NoSuchProviderException e) {
        log.error(e.getMessage(), e);
    }
    return result;
}

步骤四: WxPKCS7Encoder工具
private static final Charset CHARSET = Charset.forName(“utf-8”);
private static final int BLOCK_SIZE = 32;

/**
 * 获得对明文进行补位填充的字节.
 *
 * @param count
 *            需要进行填充补位操作的明文字节个数
 * @return 补齐用的字节数组
 */
public static byte[] encode(int count) {
    // 计算需要填充的位数
    int amountToPad = BLOCK_SIZE - (count % BLOCK_SIZE);
    if (amountToPad == 0) {
        amountToPad = BLOCK_SIZE;
    }
    // 获得补位所用的字符
    char padChr = chr(amountToPad);
    String tmp = new String();
    for (int index = 0; index < amountToPad; index++) {
        tmp += padChr;
    }
    return tmp.getBytes(CHARSET);
}

/**
 * 删除解密后明文的补位字符
 *
 * @param decrypted
 *            解密后的明文
 * @return 删除补位字符后的明文
 */
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);
}

/**
 * 将数字转化成ASCII码对应的字符,用于对明文进行补码
 *
 * @param a
 *            需要转化的数字
 * @return 转化得到的字符
 */
public static char chr(int a) {
    byte target = (byte) (a & 0xFF);
    return (char) target;
}
相关标签: 微信授权 java