AES加解密在php介面請求過程中的應用樣本_php執行個體

來源:互聯網
上載者:User

在php請求介面的時候,我們經常需要考慮的一個問題就是資料的安全性,因為資料轉送過程中很有可能會被用fillder這樣的抓包工具進行截獲。一種比較好的解決方案就是在用戶端請求發起之前先對要請求的資料進行加密,服務端api接收到請求資料後再對資料進行解密處理,返回結果給用戶端的時候也對要返回的資料進行加密,用戶端接收到返回資料的時候再解密。因此整個api請求過程中資料的安全性有了一定程度的提高。

今天結合一個簡單的demo給大家分享一下AES加解密技術在php介面請求中的應用。

首先,準備一個AES加解密的基礎類:

<?php/** * 加密基礎類 */class Crypt_AES{  protected $_cipher = "rijndael-128";  protected $_mode = "cbc";  protected $_key;  protected $_iv = null;  protected $_descriptor = null;  /**   * 是否按照PKCS #7 的標準進行填充   * 為否預設將填充“\0”補位   * @var boolean   */  protected $_PKCS7 = false;  /**   * 建構函式,對於密鑰key應區分2進位字串和16進位的。   * 如需相容PKCS#7標準,應選項設定開啟PKCS7,預設關閉   * @param string $key    * @param mixed $iv   向量值   * @param array $options   */  public function __construct($key = null, $iv = null, $options = null)  {    if (null !== $key) {      $this->setKey($key);    }    if (null !== $iv) {      $this->setIv($iv);    }    if (null !== $options) {      if (isset($options['chipher'])) {        $this->setCipher($options['chipher']);      }      if (isset($options['PKCS7'])) {        $this->isPKCS7Padding($options['PKCS7']);      }      if (isset($options['mode'])) {        $this->setMode($options['mode']);      }    }  }  /**   * PKCS#7狀態查看,傳入Boolean值進行設定   * @param boolean $flag   * @return boolean   */  public function isPKCS7Padding($flag = null)  {    if (null === $flag) {      return $this->_PKCS7;    }    $this->_PKCS7 = (bool) $flag;  }  /**   * 開啟密碼編譯演算法   * @param string $algorithm_directory locate the encryption    * @param string $mode_directory   * @return Crypt_AES   */  public function _openMode($algorithm_directory = "" , $mode_directory = "")   {    $this->_descriptor = mcrypt_module_open($this->_cipher,                         $algorithm_directory,                         $this->_mode,                        $mode_directory);    return $this;  }  public function getDescriptor()  {    if (null === $this->_descriptor) {      $this->_openMode();    }    return $this->_descriptor;  }  protected function _genericInit()  {    return mcrypt_generic_init($this->getDescriptor(), $this->getKey(), $this->getIv());  }  protected function _genericDeinit()  {    return mcrypt_generic_deinit($this->getDescriptor());  }  public function getMode()  {    return $this->_mode;  }    public function setMode($mode)  {    $this->_mode = $mode;    return $this;  }  public function getCipher()  {    return $this->_cipher;  }    public function setCipher($cipher)  {    $this->_cipher = $cipher;    return $this;  }    /**   * 獲得key   * @return string   */  public function getKey()  {    return $this->_key;  }    /**   * 設定可以   * @param string $key   */  public function setKey($key)  {    $this->_key = $key;    return $this;  }    /**   * 獲得加密向量塊,如果其為null時將追加當前Descriptor的IV大小長度   *   * @return string   */  public function getIv()  {    if (null === $this->_iv && in_array($this->_mode, array( "cbc", "cfb", "ofb", ))) {      $size = mcrypt_enc_get_iv_size($this->getDescriptor());      $this->_iv = str_pad("", 16, "\0");    }    return $this->_iv;  }  /**   * 獲得向量塊   *   * @param string $iv   * @return Crypt_AES $this   */  public function setIv($iv)  {    $this->_iv = $iv;    return $this;  }    /**   * 加密   * @param string $str 被加密文本   * @return string   */  public function encrypt($str){    $td = $this->getDescriptor();    $this->_genericInit();    $bin = mcrypt_generic($td, $this->padding($str));    $this->_genericDeinit();    return $bin;  }   public function padding($dat)  {    if ($this->isPKCS7Padding()) {      $block = mcrypt_enc_get_block_size($this->getDescriptor());         $len = strlen($dat);      $padding = $block - ($len % $block);      $dat .= str_repeat(chr($padding),$padding);          }    return $dat;  }  public function unpadding($str)  {    if ($this->isPKCS7Padding()) {      $pad = ord($str[($len = strlen($str)) - 1]);      $str = substr($str, 0, strlen($str) - $pad);    }    return $str;  }  /**   * 解密   * @param string $str    * @return string   */  public function decrypt($str){    $td = $this->getDescriptor();    $this->_genericInit();    $text = mdecrypt_generic($td, $str);    $this->_genericDeinit();    return $this->unpadding($text);  }    /**   * 16進位轉成2進位資料   * @param string $hexdata 16進位字串   * @return string   */  public static function hex2bin($hexdata)   {    return pack("H*" , $hexdata);  }  /**   * 字串轉十六進位   * @param string $hexdata 16進位字串   * @return string   */  public static function strToHex($string)  {    $hex='';    for($i=0;$i<strlen($string);$i++)      $hex.=dechex(ord($string[$i]));    $hex=strtoupper($hex);    return $hex;  }  /**   * 十六進位轉字串   * @param string $hexdata 16進位字串   * @return string   */  function hexToStr($hex)  {    $string='';    for($i=0;$i<strlen($hex)-1;$i+=2)      $string.=chr(hexdec($hex[$i].$hex[$i+1]));    return $string;  }}

用戶端請求部分:

<?php include 'AES.php';$md5Key = 'ThisIsAMd5Key';               // 對應服務端:$md5key = 'ThisIsAMd5Key';$aesKey = Crypt_AES::strToHex('1qa2ws4rf3edzxcv');   // 對應服務端:$aesKey = '3171613277733472663365647A786376';$aesKey = Crypt_AES::hex2bin($aesKey);$aesIV = Crypt_AES::strToHex('dfg452ws');       // 對應服務端:$aesIV = '6466673435327773';$aes = new Crypt_AES($aesKey,$aesIV,array('PKCS7'=>true, 'mode'=>'cbc'));// var_dump($aes);$data['name'] = 'idoubi';$data['sex']= 'male';$data['age'] = 23;$data['signature'] = '白天我是一個程式員,晚上我就是一個有夢想的演員。';$content = base64_encode($aes->encrypt(json_encode($data)));$content = urlencode($content);$sign = md5($content.$md5Key);$url = 'http://localhost/aesdemo/api.php';$params = "version=1.0&sign=$sign&content=$content";// 請求介面post($url, $params);/** * 介面請求函數 */function post($url, $params) {  $curlPost= $params;  $ch = curl_init();   //初始化curl  curl_setopt($ch, CURLOPT_URL, $url);  //提交到指定網頁  curl_setopt($ch, CURLOPT_HEADER, 0);  //設定header  curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);  //要求結果為字串且輸出到螢幕上  curl_setopt($ch, CURLOPT_POST, 1);  //post提交方式  curl_setopt($ch, CURLOPT_POSTFIELDS, $curlPost);  $result = curl_exec($ch);//運行curl  curl_close($ch);  var_dump(json_decode($result, true));}

介面處理邏輯:

<?php include 'AES.php';$data = $_POST; // 介面請求得到的資料$content = $data['content'];$sign = $data['sign'];$aesKey = '3171613277733472663365647A786376';$aesIV = '6466673435327773';$md5key = 'ThisIsAMd5Key';// 校正資料if(strcasecmp(md5(urlencode($content).$md5key),$sign) == 0) {  // 資料校正成功  $key = Crypt_AES::hex2bin($aesKey);  $aes = new Crypt_AES($key, $aesIV, array('PKCS7'=>true, 'mode'=>'cbc'));  $decrypt = $aes->decrypt(base64_decode($content));  if (!$decrypt) {   // 解密失敗    echo json_encode('can not decrypt the data');  } else {    echo json_encode($decrypt);   // 解密成功  }} else{  echo json_encode('data is not integrity');    // 資料校正失敗}

上述介面請求過程中定義了三個加解密需要用到的參數:$aesKey、$aesIV、$md5key,在實際應用過程中,只要與用戶端使用者約定好這三個參數,用戶端程式員利用這幾個參數對要請求的資料進行加密後再請求介面,服務端程式員在接收到資料後利用同樣的加解密參數對資料進行解密,整個api請求過程中的資料就很安全了。

以上就是本文的全部內容,希望對大家的學習有所協助,也希望大家多多支援雲棲社區。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.