微信用户信息解密获取UnionID

使用背景:如果开发者拥有多个移动应用、网站应用、和公众帐号(包括小程序),可通过 UnionID 来区分用户的唯一性,因为只要是同一个微信开放平台帐号下的移动应用、网站应用和公众帐号(包括小程序),用户的 UnionID 是唯一的。换句话说,同一用户,对同一个微信开放平台下的不同应用,unionid是相同的。 

微信官方文档说明:

 解密方法:

/**
   * AES解密
   *
   * @param encryptedData 消息密文
   * @param ivStr         iv字符串
   */
  public static String decrypt(String sessionKey, String encryptedData, String ivStr) {
    try {
      AlgorithmParameters params = AlgorithmParameters.getInstance("AES");
      params.init(new IvParameterSpec(Base64.decodeBase64(ivStr)));

      Cipher cipher = Cipher.getInstance("AES/CBC/NoPadding");
      cipher.init(Cipher.DECRYPT_MODE, new SecretKeySpec(Base64.decodeBase64(sessionKey), "AES"), params);

      return new String(PKCS7Encoder.decode(cipher.doFinal(Base64.decodeBase64(encryptedData))), StandardCharsets.UTF_8);
    } catch (Exception e) {
      throw new RuntimeException("AES解密失败", e);
    }
  }
/**
 * 对公众平台发送给公众账号的消息加解密示例代码.
 *
 * @copyright Copyright (c) 1998-2014 Tencent Inc.
 */

// ------------------------------------------------------------------------

package me.chanjar.weixin.common.util.crypto;

import java.nio.charset.Charset;
import java.util.Arrays;

/**
 * 提供基于PKCS7算法的加解
 */
public class PKCS7Encoder {

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

}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

写代码也写生活

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值