6-2
Monday
标签
梦涛笔记

由ECIES加密算法引发编写了RSAIES加密方法

PHP 发布时间:2025-05-28 20:54:36

ECDSA (Elliptic Curve Digital Signature Algorithm,椭圆曲线数字签名算法)

相比RSA算法密钥更短安全性更高,验签速度也更快,使用场景也得到广泛应用。

因为ECDSA算法只能做签名,不能做加解密,所以产生了ECIES(Elliptic Curve Integrated Encryption Scheme,椭圆曲线集成加密方案)。

ECIES 其中用到的 ECDH算法生成共享密钥,因平台兼容问题一些旧系统还无法支持。

所以依照ECIES的加密思路设计了自己的RSAIES加密方法:

RSAIES 加密方式详解
  • 生成随机AES密钥,使用 RSA 加密方法对其加密
  • 生成随机AES密钥iv值
  • 用随机AES密钥对数据进行AES-128-CFB加密,参数 OPENSSL_RAW_DATA
  • 密文和iv值进行base64处理(支持HEX)
  • 使用SHA256计算哈希值(mac),用于接收者验证数据完整性
  • 把 加密的随机AES密钥 cipher 向量 iv 编码方式 code 密文哈希值 mac 加密类型 RSAIES 放入 encryption 字段
RSAIES 解密方式详解
  • 把接收到的密文使用SHA256计算哈希值,验证mac值是否相同,判定数据是否完整
  • 把接收到的 加密的随机AES密钥 cipher 编码还原 base64_decode 后,使用 RSA 解密方法对其解密得到AES密钥原文
  • 用得到的随机AES密钥和收到的向量 iv 采用 aes-128-cfb 进行解密, 参数 OPENSSL_RAW_DATA
  • 得到原文


示例代码: https://github.com/unntech/encrypt/blob/main/src/RSA.php
    /**
     * RASIES加密
     * 生成随机AES密钥,使用 RSA 加密方法对其加密
     * 使用AES-128-CFB加密文本,参数选 OPENSSL_RAW_DATA
     * @param string $plaintext 明文数据
     * @param string $code 密文编码支持 base64 | hex | bin
     * @return false | array 
     *     [ 'cipher' => '加密的AES密钥', 
     *       'iv'     => 'iv',  
     *       'code'   => 'base64', 
     *       'ciphertext' => '密文', 
     *       'mac'    => '密文SHA256哈希' 
     *     ]
     * 
     */
    public function encrypt_ies(string $plaintext, string $code = 'base64', int $padding = OPENSSL_PKCS1_PADDING )
    {
        $publicKey = $this->third_public_key;
        // 生成随机对称密钥
        $cipher_method = 'aes-128-cfb';
        $symmetricKey = openssl_random_pseudo_bytes(16); // 使用 AES-128 密钥长度
        $iv = openssl_random_pseudo_bytes(openssl_cipher_iv_length($cipher_method));
        // 使用公钥加密对称密钥(使用 RASIES 过程)
        openssl_public_encrypt( $symmetricKey, $encryptedKey, $publicKey, $padding );
        // 使用对称密钥加密消息(AES-128-CFB)
        $encryptedMessage = openssl_encrypt($plaintext, $cipher_method, $symmetricKey, OPENSSL_RAW_DATA, $iv);
        $ciphertext = Encode::encode($encryptedMessage, $code );
        //使用SHA256计算密文哈希值
        $mac = strtoupper(hash("sha256", $ciphertext));

        // AES密钥cipher、向量iv、密文及哈希值
        return [
            'cipher_method' => $cipher_method,
            'cipher'        => Encode::encode($encryptedKey, $code),
            'iv'            => Encode::encode($iv, $code),
            'code'          => $code,
            'ciphertext'    => $ciphertext,
            'mac'           => $mac,
        ];
    }

    /**
     * RASIES 解密
     * 使用RSA解密方法对 $cipher 解密,得到AES密钥
     * 使用AES-128-CFB解密密文,参数选 OPENSSL_RAW_DATA,得到明文
     * @param string $ciphertext 密文
     * @param string $cipher 加密的AES密钥
     * @param string $iv AES加密向量
     * @param string|null $mac 密文哈希值
     * @param string $code 编码
     * @param int $padding 填充方式(OPENSSL_PKCS1_PADDING / OPENSSL_NO_PADDING)
     * @return string|null
     */
    public function decrypt_ies(string $ciphertext, string $cipher = '', string $iv = '', ?string $mac = null, string $code = 'base64', int $padding = OPENSSL_PKCS1_PADDING): ?string
    {
        // 解密对称密钥
        openssl_private_decrypt(Encode::decode($cipher, $code), $symmetricKey, $this->private_key, $padding);
        if(empty($symmetricKey)){
            return null;
        }
        // 2. 验证 MAC
        if(!is_null($mac)){
            $_mac = strtoupper(hash("sha256", $ciphertext));
            if($mac != $_mac){
                return null;
            }
        }
        // 3. 解密密文
        $plaintext = openssl_decrypt(Encode::decode($ciphertext, $code), 'aes-128-cfb', $symmetricKey, OPENSSL_RAW_DATA, Encode::decode($iv, $code));

        return $plaintext;
    }


RSAIES Integrated Encryption Scheme)RSA集成加密方案,采取了RSA使用广泛及跨平台兼容性高的优点,方案中只用RSA加解密随机AES密钥。

然后用AES进行对称加密数据,相比RSA加密快,又不用处理长文本RSA加密复杂的缺点。


Libsodium 加密库

PHP 发布时间:2025-05-26 10:38:36

Libsodium 是一个现代化、易用且高度安全的密码学库,旨在简化加密操作并避免常见的安全错误。它是 NaCl(Networking and Cryptography Library)的一个分支,由 Frank Denis 和社区维护。

安全设计哲学

  • 无脑安全默认配置:所有 API 默认使用当前最安全的算法和参数组合(如 XChaCha20-Poly1305、Argon2)。
  • 防误用设计:避免开发者因组合错误算法导致漏洞(如用 ECB 模式或弱哈希)。

现代密码学算法

  • 加密:XChaCha20-Poly1305, AES-GCM
  • 密钥交换:X25519(椭圆曲线 Diffie-Hellman)
  • 签名:Ed25519(EdDSA 签名)
  • 哈希:BLAKE2b
  • 密码哈希:Argon2(抗 GPU/ASIC 攻击)

跨平台支持

   提供 C 库及多种语言绑定(如 PHP、Python、Java)。

活跃维护与审计

   代码经过多次独立安全审计,社区活跃,及时修复漏洞。

PHP 7.2+ 已内置 Sodium 扩展(无需额外安装),通过函数前缀 sodium_* 调用。

官方文档: https://www.php.net/manual/zh/book.sodium.php

Libsodium 是开发者的“密码学瑞士军刀”,强烈推荐在安全敏感项目中替代 OpenSSL 等传统库。其设计目标正是让安全变得简单,让开发者专注于业务逻辑而非密码学细节。


配置mpdf导出PDF支持中文

PHP 发布时间:2025-05-19 18:14:03

修改配置文件:vendor/mpdf/mpdf/src/Config/ConfigVariables.php

'useAdobeCJK' => true,
'autoScriptToLang' => true,
'autoLangToFont' => true,
'useSubstitutions' => true,


Composer常用配置优化

PHP 发布时间:2025-05-16 10:34:31
  • 全局配置:作用范围:对所有项目生效;
  • 文件路径:~/.composer/config.json(Linux/macOS)或%APPDATA%\Composer\config.json(Windows)
composer config --global 配置项 值
  • 项目级配置:作用范围:仅对当前项目生效;
  • 文件路径:项目根目录下的composer.json
composer config 配置项 值
  • 修改包源(国内镜像源加速)
composer config --global repo.packagist composer https://mirrors.aliyun.com/composer/
  • 恢复官方源
composer config --global --unset repos.packagist
  • 修改缓存路径:解决网络盘和下载慢,已下载的库缓存至本地
composer config --global cache-dir /本地路径/cache
  • 查看当前缓存路径
composer config cache-dir
  • 查看当前配置
composer config --list --global    # 查看全局配置
composer config --list                  
# 查看项目级配置
  • 重置配置项
composer config --global --unset 配置项   # 删除全局配置项
  • ---

PHP OPcache 配置参数优化方案

PHP 发布时间:2025-03-19 18:45:14
vim /etc/php.d/10-opcache.ini
; Enable Zend OPcache extension module
zend_extension=opcache

; Determines if Zend OPCache is enabled
opcache.enable=1

; Determines if Zend OPCache is enabled for the CLI version of PHP
opcache.enable_cli=1

; The OPcache shared memory storage size.
opcache.memory_consumption=512

; The amount of memory for interned strings in Mbytes.
opcache.interned_strings_buffer=16

; The maximum number of keys (scripts) in the OPcache hash table.
; Only numbers between 200 and 1000000 are allowed.
opcache.max_accelerated_files=300000

; The maximum percentage of "wasted" memory until a restart is scheduled.
;opcache.max_wasted_percentage=5

; When this directive is enabled, the OPcache appends the current working
; directory to the script key, thus eliminating possible collisions between
; files with the same name (basename). Disabling the directive improves
; performance, but may break existing applications.
;opcache.use_cwd=1

; When disabled, you must reset the OPcache manually or restart the
; webserver for changes to the filesystem to take effect.
opcache.validate_timestamps=1

; How often (in seconds) to check file timestamps for changes to the shared
; memory storage allocation. ("1" means validate once per second, but only
; once per request. "0" means always validate)
opcache.revalidate_freq=10

; Enables or disables file search in include_path optimization
;opcache.revalidate_path=0

; If disabled, all PHPDoc comments are dropped from the code to reduce the
; size of the optimized code.
;opcache.save_comments=1

; If enabled, compilation warnings (including notices and deprecations) will
; be recorded and replayed each time a file is included. Otherwise, compilation
; warnings will only be emitted when the file is first cached.
;opcache.record_warnings=0

; Allow file existence override (file_exists, etc.) performance feature.
;opcache.enable_file_override=0

; A bitmask, where each bit enables or disables the appropriate OPcache
; passes
;opcache.optimization_level=0x7FFFBFFF

; This hack should only be enabled to work around "Cannot redeclare class"
; errors.
;opcache.dups_fix=0

; The location of the OPcache blacklist file (wildcards allowed).
; Each OPcache blacklist file is a text file that holds the names of files
; that should not be accelerated.
opcache.blacklist_filename=/etc/php.d/opcache*.blacklist

; Allows exclusion of large files from being cached. By default all files
; are cached.
;opcache.max_file_size=0

; Check the cache checksum each N requests.
; The default value of "0" means that the checks are disabled.
;opcache.consistency_checks=0

; How long to wait (in seconds) for a scheduled restart to begin if the cache
; is not being accessed.
;opcache.force_restart_timeout=180

; OPcache error_log file name. Empty string assumes "stderr".
;opcache.error_log=

; All OPcache errors go to the Web server log.
; By default, only fatal errors (level 0) or errors (level 1) are logged.
; You can also enable warnings (level 2), info messages (level 3) or
; debug messages (level 4).
;opcache.log_verbosity_level=1

; Preferred Shared Memory back-end. Leave empty and let the system decide.
;opcache.preferred_memory_model=

; Protect the shared memory from unexpected writing during script execution.
; Useful for internal debugging only.
;opcache.protect_memory=0

; Allows calling OPcache API functions only from PHP scripts which path is
; started from specified string. The default "" means no restriction
;opcache.restrict_api=

; Enables and sets the second level cache directory.
; It should improve performance when SHM memory is full, at server restart or
; SHM reset. The default "" disables file based caching.
; RPM note : file cache directory must be owned by process owner
;   for mod_php, see /etc/httpd/conf.d/php.conf
;   for php-fpm, see /etc/php-fpm.d/*conf
opcache.file_cache=/tmp

; Enables or disables opcode caching in shared memory.
;opcache.file_cache_only=0

; Enables or disables checksum validation when script loaded from file cache.
;opcache.file_cache_consistency_checks=1

; Implies opcache.file_cache_only=1 for a certain process that failed to
; reattach to the shared memory (for Windows only). Explicitly enabled file
; cache is required.
;opcache.file_cache_fallback=1

; Enables or disables copying of PHP code (text segment) into HUGE PAGES.
; Under certain circumstances (if only a single global PHP process is
; started from which all others fork), this can increase performance
; by a tiny amount because TLB misses are reduced.  On the other hand, this
; delays PHP startup, increases memory usage and degrades performance
; under memory pressure - use with care.
; Requires appropriate OS configuration.
opcache.huge_code_pages=1

; Validate cached file permissions.
; Leads OPcache to check file readability on each access to cached file.
; This directive should be enabled in shared hosting environment, when few
; users (PHP-FPM pools) reuse the common OPcache shared memory.
;opcache.validate_permission=0

; Prevent name collisions in chroot'ed environment.
; This directive prevents file name collisions in different "chroot"
; environments. It should be enabled for sites that may serve requests in
; different "chroot" environments.
;opcache.validate_root=0

; If specified, it produces opcode dumps for debugging different stages of
; optimizations.
;opcache.opt_debug_level=0

; Specifies a PHP script that is going to be compiled and executed at server
; start-up.
; https://php.net/opcache.preload
;opcache.preload=

; Preloading code as root is not allowed for security reasons. This directive
; facilitates to let the preloading to be run as another user.
; https://php.net/opcache.preload_user
;opcache.preload_user=

; Prevents caching files that are less than this number of seconds old. It
; protects from caching of incompletely updated files. In case all file updates
; on your site are atomic, you may increase performance by setting it to "0".
;opcache.file_update_protection=2

; Absolute path used to store shared lockfiles (for *nix only).
;opcache.lockfile_path=/tmp
;
;JIT
opcache.jit=tracing
opcache.jit_buffer_size=256M


WordPress 打开很慢的原因及解决

PHP 发布时间:2025-03-14 14:47:07

WordPress 打开很慢,检查下是不是有调用google的JS或CSS,搜“googleapis.com”,改到其它的共公库,或是本地的库就OK了。

ECShop 上传图中图没有缩略

PHP 发布时间:2025-03-14 14:42:49

修改/admin/goods.php #691行

if (!copy(‘../’ . $goods_img, ‘../’ . $newname)) //Edit by DreamboyMT $img change to $goods_img;

修改/admin/includes/lib_goods.php #358行,加水印之后 添加

//产品相册缩放 Edit by DreamboyMT ADD
$img_url = $GLOBALS[‘image’]->make_thumb(‘../’.$img_url , $GLOBALS[‘_CFG’][‘image_width’], $GLOBALS[‘_CFG’][‘image_height’]);
if ($proc_thumb && gd_version() > 0){ @unlink(‘../’.$newname); }

批量生成图 /admin/picture_batch.php #433行处

copy(ROOT_PATH . $row[‘img_original’], $dir . $file_name);

换成:

$img_url = $GLOBALS[‘image’]->make_thumb( ‘../’.$row[‘img_original’] , $GLOBALS[‘_CFG’][‘image_width’], $GLOBALS[‘_CFG’][‘image_height’]);
rename(ROOT_PATH .$img_url, $dir . $file_name);

改完之后,中图就会按后台设置的尺寸缩略,不同比例会留白。
因为产品展示时系统调用的是goods_img(相册中图),这里就需要改为调用原图,要不图太小了。
修改/admin/includes/lib_goods.php #726行 function get_goods_gallery

SQL 语句里添加 img_original, 字段

在 foreach 里添加一行赋值:

$row[$key][‘img_original’] = get_image_path($goods_id, $gallery_img[‘img_original’], false, ‘gallery’);   //Edit by DreamboyMT ADD

完成后就可以在模版里调用 img_original 原图变量了
修改模版里的 /library/goods_gallery.lbi #9,16行

href=”{$picture.img_original}”

修改模版里的 goods.dwt #59行

href="{$pictures.0.img_original}"

ECShop商品显示时的相册图只能显示5张

PHP 发布时间:2025-03-14 14:28:19

默认情况下,商品相册图只会显示5张,查看代码后看到是读取数据库ecs_shop_config的表

记录 goods_gallery_number 的值,那只需修改下这个数值就可以了。改到更大的一个数就行了。

因为这里的数字为最大值,意思是多于几张只显示几张。

在includes\lib_common.php  #594行

$arr[‘goods_gallery_number’] = intval($arr[‘goods_gallery_number’]) ? intval($arr[‘goods_gallery_number’]) : 5;

这个意为如果未设置goods_gallery_number值,就取默认值5。也就是如果数据库里有goods_gallery_number值,这里的修改是无作用的。

PHP 判断字符串是否为全英文,英汉混合,纯汉字方法

PHP 发布时间:2025-03-14 14:23:43

方法一:

function is_chinese($s)
{
    $allen = preg_match("/^[^\x80-\xff]+$/", $s);   //判断是否是英文
    $allcn = preg_match("/^[" . chr(0xa1) . "-" . chr(0xff) . "]+$/", $s);  //是否是中文
    if ($allen) {
        return 'allen';
    } else {
        if ($allcn) {
            return 'allcn';
        } else {
            return 'encn';
        }
    }
}

方法二:
利用Php的mb_strlen和strlen函数就可以轻松得知字符串的构成是全英文、英汉混合、还是纯汉字。简要说明如下(以上示例程序)
1、如果strlen返回的字符长度和mb_strlen以当前编码计算的长度一致,可以判断是纯英文字符串。
2、如果strlen返回的字符长度和mb_strlen以当前编码计算的长度不一致,且strlen返回值同mb_strlen的返回值求余后得0可以判断为是全汉字的字符串。
3、如果strlen返回的字符长度和mb_strlen以当前编码计算的长度不一致,且strlen返回值同mb_strlen的返回值求余后不为0,可以判断为是英汉混合的字符串。

function Check_stringType($str1)
{
    $strA = trim($str1);
    $lenA = strlen($strA);
    $lenB = mb_strlen($strA, "utf-8");
    if ($lenA === $lenB) {
        return "1"; //全英文
    } else {
        if ($lenA % $lenB == 0) {
            return "2"; //全中文
        } else {
            return "3"; //中英混合
        }
    }
}


Deprecated: Function ereg() is deprecated的解决方法

PHP 发布时间:2025-03-14 14:22:11

这个问题是因为你用的php版本过高。

在php5.3中,正则函数ereg_replace已经废弃,而dedecms还继续用。有两个方案可以解决以上问题:

1、把php版本换到v5.3下。

2、继续使用v5.3,修改php.ini文件

;extension=php_mbstring.dll

改为

extension=php_mbstring.dll

;mbstring.func_overload = 0

修改为:

mbstring.func_overload = 7

或者使用其他的函数:

define(‘DEDEADMIN’, ereg_replace(“[/\\]{1,}”, ‘/’, dirname(__FILE__) ) );
//改为
define(‘DEDEADMIN’, preg_replace(“/[\/\\\\]{1,}/”, ‘/’, dirname(__FILE__) ) );

注:因为preg_replace比ereg_replace的执行速度快,PHP推荐使用preg_replace.