search
HomeBackend DevelopmentPHP TutorialPHP symmetric encryption algorithm (DES/AES) code

  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 '
    '; 
  4. //////////////////////////////////////
  5. $a = isset($_GET['a']) ? $_GET['a'] : '测试123';
  6. //密钥
  7. $key = '12345678123456781234567812345678'; //256 bit
  8. $key = '1234567812345678'; //128 bit
  9. $key = '12345678'; //64 bit
  10. //设置模式和IV
  11. $m = new Xcrypt($key, 'cbc', 'auto');
  12. //获取向量值
  13. echo '向量:';
  14. var_dump($m->getIV());
  15. //加密
  16. $b = $m->encrypt($a, 'base64');
  17. //解密
  18. $c = $m->decrypt($b, 'base64');
  19. echo '加密后:';
  20. var_dump($b);
  21. echo '解密后:';
  22. var_dump($c);
  23. /////////////////////////////////////////
  24. echo '';
复制代码


php, DES, AES


Statement
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
The Continued Use of PHP: Reasons for Its EnduranceThe Continued Use of PHP: Reasons for Its EnduranceApr 19, 2025 am 12:23 AM

What’s still popular is the ease of use, flexibility and a strong ecosystem. 1) Ease of use and simple syntax make it the first choice for beginners. 2) Closely integrated with web development, excellent interaction with HTTP requests and database. 3) The huge ecosystem provides a wealth of tools and libraries. 4) Active community and open source nature adapts them to new needs and technology trends.

PHP and Python: Exploring Their Similarities and DifferencesPHP and Python: Exploring Their Similarities and DifferencesApr 19, 2025 am 12:21 AM

PHP and Python are both high-level programming languages ​​that are widely used in web development, data processing and automation tasks. 1.PHP is often used to build dynamic websites and content management systems, while Python is often used to build web frameworks and data science. 2.PHP uses echo to output content, Python uses print. 3. Both support object-oriented programming, but the syntax and keywords are different. 4. PHP supports weak type conversion, while Python is more stringent. 5. PHP performance optimization includes using OPcache and asynchronous programming, while Python uses cProfile and asynchronous programming.

PHP and Python: Different Paradigms ExplainedPHP and Python: Different Paradigms ExplainedApr 18, 2025 am 12:26 AM

PHP is mainly procedural programming, but also supports object-oriented programming (OOP); Python supports a variety of paradigms, including OOP, functional and procedural programming. PHP is suitable for web development, and Python is suitable for a variety of applications such as data analysis and machine learning.

PHP and Python: A Deep Dive into Their HistoryPHP and Python: A Deep Dive into Their HistoryApr 18, 2025 am 12:25 AM

PHP originated in 1994 and was developed by RasmusLerdorf. It was originally used to track website visitors and gradually evolved into a server-side scripting language and was widely used in web development. Python was developed by Guidovan Rossum in the late 1980s and was first released in 1991. It emphasizes code readability and simplicity, and is suitable for scientific computing, data analysis and other fields.

Choosing Between PHP and Python: A GuideChoosing Between PHP and Python: A GuideApr 18, 2025 am 12:24 AM

PHP is suitable for web development and rapid prototyping, and Python is suitable for data science and machine learning. 1.PHP is used for dynamic web development, with simple syntax and suitable for rapid development. 2. Python has concise syntax, is suitable for multiple fields, and has a strong library ecosystem.

PHP and Frameworks: Modernizing the LanguagePHP and Frameworks: Modernizing the LanguageApr 18, 2025 am 12:14 AM

PHP remains important in the modernization process because it supports a large number of websites and applications and adapts to development needs through frameworks. 1.PHP7 improves performance and introduces new features. 2. Modern frameworks such as Laravel, Symfony and CodeIgniter simplify development and improve code quality. 3. Performance optimization and best practices further improve application efficiency.

PHP's Impact: Web Development and BeyondPHP's Impact: Web Development and BeyondApr 18, 2025 am 12:10 AM

PHPhassignificantlyimpactedwebdevelopmentandextendsbeyondit.1)ItpowersmajorplatformslikeWordPressandexcelsindatabaseinteractions.2)PHP'sadaptabilityallowsittoscaleforlargeapplicationsusingframeworkslikeLaravel.3)Beyondweb,PHPisusedincommand-linescrip

How does PHP type hinting work, including scalar types, return types, union types, and nullable types?How does PHP type hinting work, including scalar types, return types, union types, and nullable types?Apr 17, 2025 am 12:25 AM

PHP type prompts to improve code quality and readability. 1) Scalar type tips: Since PHP7.0, basic data types are allowed to be specified in function parameters, such as int, float, etc. 2) Return type prompt: Ensure the consistency of the function return value type. 3) Union type prompt: Since PHP8.0, multiple types are allowed to be specified in function parameters or return values. 4) Nullable type prompt: Allows to include null values ​​and handle functions that may return null values.

See all articles

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

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment