AES encryption and decryption in the PHP interface request process application Example _php instance

Source: Internet
Author: User
Tags chr curl decrypt md5 ord pkcs7 urlencode

One of the issues that we often need to consider when PHP is requesting an interface is the security of the data, which is likely to be intercepted using fillder such as a grab tool. A better solution is to encrypt the data to be requested before the client request is initiated. The server API receives the request data, then decrypts the data, returns the result to the client and encrypts the data to be returned, and the client receives the data when it is returned to decrypt. Therefore, the security of the data in the whole API request process has been improved to a certain extent.

Today, a simple demo to share with you the AES encryption and decryption technology in the PHP interface request application.

First, prepare a base class for AES plus decryption:

<?php/** * Encryption base class/class Crypt_aes {protected $_cipher = "rijndael-128";
  protected $_mode = "CBC";
  protected $_key;
  protected $_iv = null;

  protected $_descriptor = null;

  /** * Whether to be populated according to the standard of a PKCS #7 * to no default will fill "" "" "" * @var Boolean/protected $_PKCS7 = false;
   /** * constructor, the key key should be distinguished from the 2-string and 16-in-system. * For compatible PKCS#7 standards, open PKCS7 with option settings, default off * @param string $key * @param mixed $iv vector value * @param array $options/P ublic 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 Status View, passing Boolean value to set * @param boolean $flag * @return Boolean/Public function ispkcs7padding ($flag = null)
    {if (null = = $flag) {return $this->_pkcs7;
  $this-&GT;_PKCS7 = (bool) $flag;
   /** * Unlock Encryption algorithm * @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;
    The 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 ());
  The Public Function GetMode () {return $this->_mode;
    The Public Function SetMode ($mode) {$this->_mode = $mode;
  return $this;
  The Public Function Getcipher () {return $this->_cipher;
    The Public Function Setcipher ($cipher) {$this->_cipher = $cipher;
  return $this;
  /** * Obtains key * @return String */Public Function Getkey () {return $this->_key;
    /** * settings can be * @param string $key/Public Function Setkey ($key) {$this->_key = $key;
  return $this;
    /** * Obtains an encryption vector block, if it is null append the current descriptor IV size * * @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, "the"); } return $this; _iv; /** * Obtains vector block * * @param string $iv * @return Crypt_aes $this/Public Function Setiv ($IV) {$t
    His->_iv = $iv;
  return $this; /** * Encryption * @param string $STR Encrypted text * @return string/Public function encrypt ($str) {$td = $thi
    S->getdescriptor ();
    $this->_genericinit ();
    $bin = Mcrypt_generic ($TD, $this->padding ($STR));

    $this->_genericdeinit ();
  return $bin; The Public Function padding ($dat) {if ($this->ispkcs7padding ()) {$block = Mcrypt_enc_get_block_size ($th
   
      Is->getdescriptor ());
      $len = strlen ($dat);
      $padding = $block-($len% $block);      
    $dat. = Str_repeat (Chr ($padding), $padding);
  return $dat;  The Public Function unpadding ($STR) {if ($this->ispkcs7padding ()) {$pad = Ord ($str [($len = strlen ($STR))
      -1]);
    $str = substr ($str, 0, strlen ($str)-$pad);
  return $str; /** * Decryption * @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 into 2 data * @param string $hexdata 16 String * @return string/public static function Hex2bin 
  ($hexdata)
  {return Pack ("h*", $hexdata); /** * String hexadecimal * @param string $hexdata 16 binary String * @return String */public static function Strtohex ($st
    Ring) {$hex = ';
    For ($i =0 $i <strlen ($string), $i + +) $hex. =dechex (Ord ($string [$i]));
    $hex =strtoupper ($hex);
  return $hex; /** * Hexadecimal Spin String * @param string $hexdata 16 String * @return string/function Hextostr ($hex) {$st
    Ring= ';
    For ($i =0 $i <strlen ($hex)-1; $i +=2) $string. =CHR (Hexdec ($hex [$i]. $hex [$i +1]));
  return $string;

 }
}

Client Request section:

<?php include ' aes.php ';               $MD 5Key = ' Thisisamd5key ';
Corresponding service end: $MD 5key = ' Thisisamd5key ';   $aesKey = Crypt_aes::strtohex (' 1QA2WS4RF3EDZXCV ');
Corresponding Service end: $aesKey = ' 3171613277733472663365647a786376 ';
$aesKey = Crypt_aes::hex2bin ($aesKey);       $aesIV = Crypt_aes::strtohex (' Dfg452ws ');
Corresponding Service end: $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 '] = ' I am a programmer during the day, I am a dream actor at night.

';
$content = Base64_encode ($aes->encrypt (Json_encode ($data));
$content = UrlEncode ($content);

$sign = MD5 ($content. $MD 5Key);
$url = ' http://localhost/aesdemo/api.php ';

$params = "version=1.0&sign= $sign &content= $content";

Request Interface Post ($url, $params);
  /** * Interface Request functions/function post ($url, $params) {$curlPost = $params;   $ch = Curl_init ();  Initialization of Curl curl_setopt ($ch, Curlopt_url, $url); Submit to the specified page curl_setopt ($ch, CurlOpt_header, 0);  Set Header curl_setopt ($ch, Curlopt_returntransfer, 1);  Requires the result to be a string and output to the screen curl_setopt ($ch, Curlopt_post, 1);
  Post Submission Method curl_setopt ($ch, Curlopt_postfields, $curlPost);
  $result = curl_exec ($ch);//Run Curl Curl_close ($ch);
Var_dump (Json_decode ($result, true));

 }

Interface processing logic:

<?php 


include ' aes.php ';

$data = $_post; The data $content of the interface request
= $data [' content '];
$sign = $data [' sign '];

$aesKey = ' 3171613277733472663365647a786376 ';
$aesIV = ' 6466673435327773 ';
$MD 5key = ' Thisisamd5key ';

Verify Data
if (STRCASECMP (MD5 (UrlEncode ($content). $MD 5key), $sign) = = 0) {
  //data validation success
  $key = Crypt_aes:: Hex2bin ($aesKey);
  $aes = new Crypt_aes ($key, $aesIV, Array (' PKCS7 ' =>true, ' mode ' => ' CBC '));

  $decrypt = $aes->decrypt (Base64_decode ($content));
  if (! $decrypt) {   //Decrypt failed
    echo Json_encode (' Can not decrypt the data ');
  } else {
    echo json_encode ($dec Rypt);   Decryption succeeded
  }
else{
  echo json_encode (' data is not integrity ');    Data checksum failure
}

The above interface request process has defined three encryption and decryption need to use the parameters: $aesKey, $aesIV, $md 5key, in the actual application process, as long as the client user agreed with the three parameters, client programmers use these parameters to the requested data encryption and then request the interface, The server programmer uses the same encryption and decryption parameters to decrypt the data after receiving the data, and the data in the entire API request process is secure.

The above is the entire content of this article, I hope to help you learn, but also hope that we support the cloud habitat community.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

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.