Home Backend Development PHP Tutorial PHP symmetric encryption algorithm (DES/AES) code

PHP symmetric encryption algorithm (DES/AES) code

Jul 25, 2016 am 08:43 AM

  1. /**
  2. * Commonly used symmetric encryption algorithms
  3. * Supported keys: 64/128/256 bit (byte length 8/16/32)
  4. * Supported algorithms: DES/AES (automatically matched according to key length: DES: 64bit AES :128/256bit)
  5. * Supported modes: CBC/ECB/OFB/CFB
  6. * Ciphertext encoding: base64 string/hex string/binary string stream
  7. * Padding method: PKCS5Padding (DES)
  8. *
  9. * @author: linvo
  10. * @version: 1.0.0
  11. * @date: 2013/1/10
  12. */
  13. class Xcrypt{
  14. private $mcrypt;
  15. private $key;
  16. private $mode;
  17. private $iv;
  18. private $blocksize;
  19. /**
  20. * Constructor
  21. *
  22. * @param string key
  23. * @param string mode
  24. * @param string vector ("off": not used / "auto": automatic / other: specified value, the same length as the key)
  25. */
  26. public function __construct($key, $mode = 'cbc', $iv = "off"){
  27. switch (strlen($key)){
  28. case 8:
  29. $this->mcrypt = MCRYPT_DES;
  30. break;
  31. case 16:
  32. $this->mcrypt = MCRYPT_RIJNDAEL_128;
  33. break;
  34. case 32:
  35. $this->mcrypt = MCRYPT_RIJNDAEL_256;
  36. break;
  37. default:
  38. die("Key size must be 8/16/32");
  39. }
  40. $this->key = $key;
  41. switch (strtolower($mode)){
  42. case 'ofb':
  43. $this->mode = MCRYPT_MODE_OFB;
  44. if ($iv == 'off') die('OFB must give a IV'); //OFB必须有向量
  45. break;
  46. case 'cfb':
  47. $this->mode = MCRYPT_MODE_CFB;
  48. if ($iv == 'off') die('CFB must give a IV'); //CFB必须有向量
  49. break;
  50. case 'ecb':
  51. $this->mode = MCRYPT_MODE_ECB;
  52. $iv = 'off'; //ECB不需要向量
  53. break;
  54. case 'cbc':
  55. default:
  56. $this->mode = MCRYPT_MODE_CBC;
  57. }
  58. switch (strtolower($iv)){
  59. case "off":
  60. $this->iv = null;
  61. break;
  62. case "auto":
  63. $source = PHP_OS=='WINNT' ? MCRYPT_RAND : MCRYPT_DEV_RANDOM;
  64. $this->iv = mcrypt_create_iv(mcrypt_get_block_size($this->mcrypt, $this->mode), $source);
  65. break;
  66. default:
  67. $this->iv = $iv;
  68. }
  69. }
  70. /**
  71. * Get vector value
  72. * @param string vector value encoding (base64/hex/bin)
  73. * @return string vector value
  74. */
  75. public function getIV($code = 'base64'){
  76. switch ($code){
  77. case 'base64':
  78. $ret = base64_encode($this->iv);
  79. break;
  80. case 'hex':
  81. $ret = bin2hex($this->iv);
  82. break;
  83. case 'bin':
  84. default:
  85. $ret = $this->iv;
  86. }
  87. return $ret;
  88. }
  89. /**
  90. * Encryption
  91. * @param string plain text
  92. * @param string cipher text encoding (base64/hex/bin)
  93. * @return string cipher text
  94. */
  95. public function encrypt($str, $code = 'base64'){
  96. if ($this->mcrypt == MCRYPT_DES) $str = $this->_pkcs5Pad($str);
  97. if (isset($this->iv)) {
  98. $result = mcrypt_encrypt($this->mcrypt, $this->key, $str, $this->mode, $this->iv);
  99. } else {
  100. @$result = mcrypt_encrypt($this->mcrypt, $this->key, $str, $this->mode);
  101. }
  102. switch ($code){
  103. case 'base64':
  104. $ret = base64_encode($result);
  105. break;
  106. case 'hex':
  107. $ret = bin2hex($result);
  108. break;
  109. case 'bin':
  110. default:
  111. $ret = $result;
  112. }
  113. return $ret;
  114. }
  115. /**
  116. * Decryption
  117. * @param string ciphertext
  118. * @param string ciphertext encoding (base64/hex/bin)
  119. * @return string plaintext
  120. */
  121. public function decrypt($str, $code = "base64"){
  122. $ret = false;
  123. switch ($code){
  124. case 'base64':
  125. $str = base64_decode($str);
  126. break;
  127. case 'hex':
  128. $str = $this->_hex2bin($str);
  129. break;
  130. case 'bin':
  131. default:
  132. }
  133. if ($str !== false){
  134. if (isset($this->iv)) {
  135. $ret = mcrypt_decrypt($this->mcrypt, $this->key, $str, $this->mode, $this->iv);
  136. } else {
  137. @$ret = mcrypt_decrypt($this->mcrypt, $this->key, $str, $this->mode);
  138. }
  139. if ($this->mcrypt == MCRYPT_DES) $ret = $this->_pkcs5Unpad($ret);
  140. }
  141. return $ret;
  142. }
  143. private function _pkcs5Pad($text){
  144. $this->blocksize = mcrypt_get_block_size($this->mcrypt, $this->mode);
  145. $pad = $this->blocksize - (strlen($text) % $this->blocksize);
  146. return $text . str_repeat(chr($pad), $pad);
  147. }
  148. private function _pkcs5Unpad($text){
  149. $pad = ord($text{strlen($text) - 1});
  150. if ($pad > strlen($text)) return false;
  151. if (strspn($text, chr($pad), strlen($text) - $pad) != $pad) return false;
  152. $ret = substr($text, 0, -1 * $pad);
  153. return $ret;
  154. }
  155. private function _hex2bin($hex = false){
  156. $ret = $hex !== false && preg_match('/^[0-9a-fA-F]+$/i', $hex) ? pack("H*", $hex) : false;
  157. return $ret;
  158. }
  159. }
复制代码
使用示例:
  1. header('Content-Type:text/html;Charset=utf-8;');
  2. include "xcrypt.php";
  3. echo '
    '; </li>
    <li>////////////////////////////////////// </li>
    <li>$a = isset($_GET['a']) ? $_GET['a'] : '测试123'; </li>
    <li>   </li>
    <li>//密钥 </li>
    <li>$key = '12345678123456781234567812345678'; //256 bit </li>
    <li>$key = '1234567812345678'; //128 bit </li>
    <li>$key = '12345678'; //64 bit </li>
    <li>   </li>
    <li>//设置模式和IV </li>
    <li>$m = new Xcrypt($key, 'cbc', 'auto'); </li>
    <li>   </li>
    <li>//获取向量值 </li>
    <li>echo '向量:'; </li>
    <li>var_dump($m->getIV()); </li>
    <li>   </li>
    <li>//加密 </li>
    <li>$b = $m->encrypt($a, 'base64'); </li>
    <li>//解密 </li>
    <li>$c = $m->decrypt($b, 'base64'); </li>
    <li>   </li>
    <li>echo '加密后:'; </li>
    <li>var_dump($b); </li>
    <li>echo '解密后:'; </li>
    <li>var_dump($c); </li>
    <li>   </li>
    <li>   </li>
    <li>///////////////////////////////////////// </li>
    <li>echo '
    ';
复制代码


php, DES, AES


Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Apr 05, 2025 am 12:04 AM

JWT is an open standard based on JSON, used to securely transmit information between parties, mainly for identity authentication and information exchange. 1. JWT consists of three parts: Header, Payload and Signature. 2. The working principle of JWT includes three steps: generating JWT, verifying JWT and parsing Payload. 3. When using JWT for authentication in PHP, JWT can be generated and verified, and user role and permission information can be included in advanced usage. 4. Common errors include signature verification failure, token expiration, and payload oversized. Debugging skills include using debugging tools and logging. 5. Performance optimization and best practices include using appropriate signature algorithms, setting validity periods reasonably,

How does session hijacking work and how can you mitigate it in PHP? How does session hijacking work and how can you mitigate it in PHP? Apr 06, 2025 am 12:02 AM

Session hijacking can be achieved through the following steps: 1. Obtain the session ID, 2. Use the session ID, 3. Keep the session active. The methods to prevent session hijacking in PHP include: 1. Use the session_regenerate_id() function to regenerate the session ID, 2. Store session data through the database, 3. Ensure that all session data is transmitted through HTTPS.

Describe the SOLID principles and how they apply to PHP development. Describe the SOLID principles and how they apply to PHP development. Apr 03, 2025 am 12:04 AM

The application of SOLID principle in PHP development includes: 1. Single responsibility principle (SRP): Each class is responsible for only one function. 2. Open and close principle (OCP): Changes are achieved through extension rather than modification. 3. Lisch's Substitution Principle (LSP): Subclasses can replace base classes without affecting program accuracy. 4. Interface isolation principle (ISP): Use fine-grained interfaces to avoid dependencies and unused methods. 5. Dependency inversion principle (DIP): High and low-level modules rely on abstraction and are implemented through dependency injection.

How to debug CLI mode in PHPStorm? How to debug CLI mode in PHPStorm? Apr 01, 2025 pm 02:57 PM

How to debug CLI mode in PHPStorm? When developing with PHPStorm, sometimes we need to debug PHP in command line interface (CLI) mode...

How to automatically set permissions of unixsocket after system restart? How to automatically set permissions of unixsocket after system restart? Mar 31, 2025 pm 11:54 PM

How to automatically set the permissions of unixsocket after the system restarts. Every time the system restarts, we need to execute the following command to modify the permissions of unixsocket: sudo...

Explain late static binding in PHP (static::). Explain late static binding in PHP (static::). Apr 03, 2025 am 12:04 AM

Static binding (static::) implements late static binding (LSB) in PHP, allowing calling classes to be referenced in static contexts rather than defining classes. 1) The parsing process is performed at runtime, 2) Look up the call class in the inheritance relationship, 3) It may bring performance overhead.

How to send a POST request containing JSON data using PHP's cURL library? How to send a POST request containing JSON data using PHP's cURL library? Apr 01, 2025 pm 03:12 PM

Sending JSON data using PHP's cURL library In PHP development, it is often necessary to interact with external APIs. One of the common ways is to use cURL library to send POST�...

See all articles