php中加密解密DES类的简单使用方法示例

本文实例讲述了php中加密解密DES类的简单使用方法,分享给大家供大家参考,具体如下:

在平时的开发工作中,我们经常会对关键字符进行加密,可能为了安全 也可能为了规范,所以要正确使用DES加密解密

在这里插入图片描述

代码1:

  1. class DES
  2. {
  3. var $key; // 密钥
  4. var $iv; // 偏移量
  5. function __construct( $key, $iv=0 ) {
  6. $this->key = $key;
  7. if( $iv == 0 ) {
  8. $this->iv = $key;
  9. } else {
  10. $this->iv = $iv;
  11. // 创建初始向量, 并且检测密钥长度, Windows 平台请使用 MCRYPT_RAND
  12. // mcrypt_create_iv ( mcrypt_get_block_size (MCRYPT_DES, MCRYPT_MODE_CBC), MCRYPT_DEV_RANDOM );
  13. }
  14. }
  15. function encrypt($str) {
  16. //加密,返回大写十六进制字符串
  17. $size = mcrypt_get_block_size ( MCRYPT_DES, MCRYPT_MODE_CBC );
  18. $str = $this->pkcs5Pad ( $str, $size );
  19. // bin2hex 把 ASCII 字符的字符串转换为十六进制值
  20. return strtoupper( bin2hex( mcrypt_cbc(MCRYPT_DES, $this->key, $str, MCRYPT_ENCRYPT, $this->iv ) ) );
  21. }
  22. function decrypt($str) {
  23. //解密
  24. $strBin = $this->hex2bin( strtolower( $str ) );
  25. $str = mcrypt_cbc( MCRYPT_DES, $this->key, $strBin, MCRYPT_DECRYPT, $this->iv );
  26. $str = $this->pkcs5Unpad( $str );
  27. return $str;
  28. }
  29. function hex2bin($hexData) {
  30. $binData = "";
  31. for($i = 0; $i < strlen ( $hexData ); $i += 2) {
  32. $binData .= chr ( hexdec ( substr ( $hexData, $i, 2 ) ) );
  33. }
  34. return $binData;
  35. }
  36. function pkcs5Pad($text, $blocksize) {
  37. $pad = $blocksize - (strlen ( $text ) % $blocksize);
  38. return $text . str_repeat ( chr ( $pad ), $pad );
  39. }
  40. function pkcs5Unpad($text) {
  41. $pad = ord ( $text {strlen ( $text ) - 1} );
  42. if ($pad > strlen ( $text ))
  43. return false;
  44. if (strspn ( $text, chr ( $pad ), strlen ( $text ) - $pad ) != $pad)
  45. return false;
  46. return substr ( $text, 0, - 1 * $pad );
  47. }
  48. }

Deprecated: Methods with the same name as their class will not be constructors in a future version of PHP; DES5 has a deprecated constructor in D:\phpstudy_pro\WWW\des\DES5.php on line 2

Fatal error: Uncaught Error: Call to undefined function mcrypt_get_block_size() in D:\phpstudy_pro\WWW\des\DES5.php:19 Stack trace: #0 D:\phpstudy_pro\WWW\des\1.php(10): DES5->encrypt('podsmia') #1 {main} thrown in D:\phpstudy_pro\WWW\des\DES5.php on line 19

mcrypt_cbc 以 CBC 模式加解密数据, 在PHP 5.5.0+被弃用, PHP 7.0.0被移除

mcrypt_encrypt / mcrypt_decrypt 使用给定参数加密 / 解密, 在PHP 7.1.0+被弃用, 在PHP 7.2.0+被移除

代码2:

  1. class DES7
  2. {
  3. //要改的加密, 使用 openssl
  4. public function desEncrypt($str,$key) {
  5. $iv = $key;
  6. $data = openssl_encrypt($str,"DES-CBC",$key,OPENSSL_RAW_DATA,$iv);
  7. $data = strtolower(bin2hex($data));
  8. return $data;
  9. }
  10. //要改的解密
  11. public function desDecrypt($str,$key) {
  12. $iv = $key;
  13. return openssl_decrypt (hex2bin($str), 'DES-CBC', $key, OPENSSL_RAW_DATA,$iv);
  14. }
  15. }