微信小程序数据加解密

package com.chenpi;

import cn.hutool.crypto.Mode;
import cn.hutool.crypto.Padding;
import cn.hutool.crypto.symmetric.AES;
import java.nio.charset.StandardCharsets;
import java.security.AlgorithmParameters;
import java.security.Security;
import java.util.Arrays;
import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.codec.binary.Base64;
import org.bouncycastle.jce.provider.BouncyCastleProvider;

/*
 * @description 微信相关工具类
 * @author 
 * @date 2021/11/22
 * @version 1.0
 */
@Slf4j
public class WxUtils {

  /**
   * 解密微信加密数据,对称解密使用的算法为 AES-128-CBC,数据采用PKCS#7填充。
   *
   * @param encryptedData 加密串
   * @param sessionKey    会话密钥
   * @param iv            解密算法初始向量
   * @return 解密后的数据
   */
  public static String decryptWxData(String encryptedData, String sessionKey, String iv) {
    try {
      // 初始化
      Security.addProvider(new BouncyCastleProvider());
      SecretKeySpec spec = new SecretKeySpec(Base64.decodeBase64(sessionKey), "AES");
      AlgorithmParameters parameters = AlgorithmParameters.getInstance("AES");
      parameters.init(new IvParameterSpec(Base64.decodeBase64(iv)));
      Cipher cipher = Cipher.getInstance("AES/CBC/PKCS7Padding", "BC");
      cipher.init(Cipher.DECRYPT_MODE, spec, parameters);
      byte[] resultByte = cipher.doFinal(Base64.decodeBase64(encryptedData));
      if (null != resultByte && resultByte.length > 0) {
        String result = new String(resultByte, StandardCharsets.UTF_8);
        log.info(">>>>> 微信加密数据解析结果:{}", result);
        return result;
      }
    } catch (Exception e) {
      log.error(">>>>> 微信加密数据解析失败:", e);
    }
    return null;
  }

  /**
   * 解密微信加密数据,对称解密使用的算法为 AES-128-CBC,数据采用PKCS#7填充。
   *
   * @param encryptedData 加密串
   * @param sessionKey    会话密钥
   * @param iv            解密算法初始向量
   * @return 解密后的数据
   */
  public static String decryptWxDataOfHutool(String encryptedData, String sessionKey, String iv) {
    AES aes = new AES(Mode.CBC, Padding.NoPadding, Base64.decodeBase64(sessionKey),
        Base64.decodeBase64(iv));
    byte[] resultByte = aes.decrypt(Base64.decodeBase64(encryptedData));
    if (null != resultByte && resultByte.length > 0) {
      // 删除解密后明文的补位字符
      int padNum = resultByte[resultByte.length - 1];
      if (padNum < 1 || padNum > 32) {
        padNum = 0;
      }
      resultByte = Arrays.copyOfRange(resultByte, 0, resultByte.length - padNum);
      String result = new String(resultByte, StandardCharsets.UTF_8);
      log.info(">>>>> 微信加密数据解析结果:{}", result);
      return result;
    }
    return null;
  }

  public static void main(String[] args) {
    String encryptedData = "9d9sSqhjoZI9DgxC7f+wAnciEhgHv0WVitr6UAF8Wf7mS7PJniGsnaYE6I8oRnhpc10VDUuiHPm685NW0SbRVokaH9CDkVZnrezVQw8HR4RaFpgu/HNT1JchLKxRN4n+nqg7dlgGfwArPc8zBAMVrEXbE7QNuyu1oUBdX9wFuFAaBhijg2kPDwcJuwfrBLl+CB/D9O//3Z8e7O07Cdn5/TaETkpfm/Ep82efZIhOQ3h3iumF+YhkVcpi/anc1EMwEr5G2aJyA1XebGT7PsTT6j9gZJbTlOGUJGYM5Ny4SJSU3nRwLE0YZXwX7prR/JQGCg/VhwxWPMAPLgSIFJf2mbpcog4jzxARK8pQNrWXyCJfA+rUWrCzfXFatpj4Qw6xq9KomawpPWFvdOJdULHig8G3e9WaR/Rtq+S3hWRxf+U9MGvlx0hQf3gJVLpOFkqtL0gy9r3vIMbDbRjK1dbqF4rQP+Xu9HREJaU1s+EUY7DEnjPU1PC3F32T1fo9ZWnf/Hyk2+xGYAQjoUXJv/gzlrv05dYDOr+phvWVYJ4Bgw5WbzAc/v4hlI4fy4cPg2P2xjJzopeyXaT1HiZNbkFiTtun7DoE6neXs2zUnXaVpkANmGQqQI2AtYsBUKJ1GIgXgh4n5s2uw3lFTFQrq80lvoXmH+1r9oPaHOYwHwkzocOdgTBLMdiBzNVUVT49wswfUFZUMcAKkqUCRDWdNr8gVgkEdHDUmnt4SfLsrMBuB81UZLTKGfd6c9NzDNlwYy9JzAbpKlr62ppilYM4sgh1HQy0d25FGJQ+TcJDy+RHSdJMY+8S+EpLCylXedAsXtRzpTU/BwgkDYmeizM86vbVq1h9qgmU0Emv8JJtKQhS7CtyXrL880eQ/ze/eLSEs6RC8s0B016xd1vXQvOrovbyqlB+j+fWEyzoSrTlUwATdepkiXle21YDYSy6nf6fi7hYjfh/3WFLwfYqXp7xuP1ndp5TuuhU9ye485G+kpViMpWVo69MOvFIQhUGXewfmW3U6GrwK1dBaNxk6UNquqosOBQ6ufmt6u9Y6pHqiRxKKA3N/aMrOd1A81p87JOmX3bCp3tgU8k5w+de3Ual4hdDcHK8AJUfrT8H5BDtY5LP2Ny/rD3X6VuO9//WQpszEFprosDZcb0SBTG3dxeIr4lb1I9MHVtJoEOfwLV8WtUN6Rdn/kGZ1nInSAuMyqZLBRfAX2603lv91SkghnY+FT3PCuqaDPDEDUgd/ozM9DWfaI9eaC/OC5NU+WqW9s17Q3+cLaWF7VZswloRuS/8LMrahxmTcDnIFRV+S1SeyV+Bdm79qseeQEdsSVDdLO2aJ1iViLxzbebb8pUIhx10JMacUrOBFVB+J76lLR4AiVT8rydLRA6uq5fFCMlg2GDXVBkbgqUoBVuiozGLKjPPSmfbk5s9JMxa8zSTZ6Vq4EefAeWoSKiWKHtBkFWcUEbp6I2+YycS3kqP8kC069csssGcHqDA6ouP+wEkpoDVS3vFi4fVkpjBtpY5Fu+NIQYUfiC54EA2JMyBS3lHGv01oPW54o4uSZoglcb2S6Yf9fkgS48ft0xE7Yi0YTQBct2jVTOSq5jjwxb26pjAhfkkccdvjZD3wHZSl/dNEsOWdKrdhE6H93Rvqny/nvQFX0DDzZPs1O2rbRAGxgHtKSDfxjWC6g==";
    String sessionKey = "VrgQ9xkONam93c+ULD0yLA==";
    String iv = "W4ND0KBskxNNnSRCuapaqQ==";

    decryptWxDataOfHutool(encryptedData, sessionKey, iv);

    decryptWxData(encryptedData, sessionKey, iv);
  }
}

你可能感兴趣的:(工具类,微信小程序,小程序)