作者 王智

daima

  1 +<?php
  2 +
  3 +include_once "wxBizDataCrypt.php";
  4 +
  5 +
  6 +$appid = 'wx55afbe753b153a68';
  7 +$sessionKey = $_REQUEST['session_key'];
  8 +$encryptedData = $_REQUEST['encryptedData'];
  9 +$iv = $_REQUEST['iv'];
  10 +
  11 +$pc = new WXBizDataCrypt($appid, $sessionKey);
  12 +$errCode = $pc->decryptData($encryptedData, $iv, $data);
  13 +
  14 +if ($errCode == 0) {
  15 + print($data . "\n");
  16 +} else {
  17 + print($errCode . "\n");
  18 +}
  1 +<?php
  2 +
  3 +/**
  4 + * error code 说明.
  5 + * <ul>
  6 +
  7 + * <li>-41001: encodingAesKey 非法</li>
  8 + * <li>-41003: aes 解密失败</li>
  9 + * <li>-41004: 解密后得到的buffer非法</li>
  10 + * <li>-41005: base64加密失败</li>
  11 + * <li>-41016: base64解密失败</li>
  12 + * </ul>
  13 + */
  14 +class ErrorCode
  15 +{
  16 + public static $OK = 0;
  17 + public static $IllegalAesKey = -41001;
  18 + public static $IllegalIv = -41002;
  19 + public static $IllegalBuffer = -41003;
  20 + public static $DecodeBase64Error = -41004;
  21 +}
  22 +
  23 +?>
  1 +<?php
  2 +
  3 +/**
  4 + * 对微信小程序用户加密数据的解密示例代码.
  5 + *
  6 + * @copyright Copyright (c) 1998-2014 Tencent Inc.
  7 + */
  8 +
  9 +
  10 +include_once "errorCode.php";
  11 +
  12 +
  13 +class WXBizDataCrypt
  14 +{
  15 + private $appid;
  16 + private $sessionKey;
  17 +
  18 + /**
  19 + * 构造函数
  20 + * @param $sessionKey string 用户在小程序登录后获取的会话密钥
  21 + * @param $appid string 小程序的appid
  22 + */
  23 + public function __construct( $appid, $sessionKey)
  24 + {
  25 + $this->sessionKey = $sessionKey;
  26 + $this->appid = $appid;
  27 + }
  28 +
  29 +
  30 + /**
  31 + * 检验数据的真实性,并且获取解密后的明文.
  32 + * @param $encryptedData string 加密的用户数据
  33 + * @param $iv string 与用户数据一同返回的初始向量
  34 + * @param $data string 解密后的原文
  35 + *
  36 + * @return int 成功0,失败返回对应的错误码
  37 + */
  38 + public function decryptData( $encryptedData, $iv, &$data )
  39 + {
  40 + if (strlen($this->sessionKey) != 24) {
  41 + return ErrorCode::$IllegalAesKey;
  42 + }
  43 + $aesKey=base64_decode($this->sessionKey);
  44 +
  45 +
  46 + if (strlen($iv) != 24) {
  47 + return ErrorCode::$IllegalIv;
  48 + }
  49 + $aesIV=base64_decode($iv);
  50 +
  51 + $aesCipher=base64_decode($encryptedData);
  52 +
  53 + $result=openssl_decrypt( $aesCipher, "AES-128-CBC", $aesKey, 1, $aesIV);
  54 +
  55 + $dataObj=json_decode( $result );
  56 + if( $dataObj == NULL )
  57 + {
  58 + return ErrorCode::$IllegalBuffer;
  59 + }
  60 + if( $dataObj->watermark->appid != $this->appid )
  61 + {
  62 + return ErrorCode::$IllegalBuffer;
  63 + }
  64 + $data = $result;
  65 + return ErrorCode::$OK;
  66 + }
  67 +
  68 +}
  69 +