zoukankan      html  css  js  c++  java
  • PHP进行AES/ECB/PKCS7 padding加密的例子(openssl)

    利用openssl加密更简单,而且支持php7.1.x版本,基本可以用于所有版本的php程序。

    <?php
    
    class OpenSSLAES
    {
        /**
         * var string $method 加解密方法,可通过openssl_get_cipher_methods()获得
         */
        protected $method;
    
        /**
         * var string $secret_key 加解密的密钥
         */
        protected $secret_key;
    
        /**
         * var string $iv 加解密的向量,有些方法需要设置比如CBC
         */
        protected $iv;
    
        /**
         * var string $options (不知道怎么解释,目前设置为0没什么问题)
         */
        protected $options; 
    
        /**
         * 构造函数
         *
         * @param string $key 密钥
         * @param string $method 加密方式
         * @param string $iv iv向量
         * @param mixed $options 还不是很清楚 
         *
         */
        public function __construct($key, $method = 'AES-128-ECB', $iv = '', $options = 0)
        {
            // key是必须要设置的
            $this->secret_key = isset($key) ? $key : exit('key为必须项');
    
            $this->method = $method;
    
            $this->iv = $iv;
    
            $this->options = $options;
        }
    
        /**
         * 加密方法,对数据进行加密,返回加密后的数据
         *
         * @param string $data 要加密的数据
         * 
         * @return string 
         *
         */
        public function encrypt($data)
        {
            return openssl_encrypt($data, $this->method, $this->secret_key, $this->options, $this->iv);
        }
    
        /**
         * 解密方法,对数据进行解密,返回解密后的数据
         *
         * @param string $data 要解密的数据
         * 
         * @return string 
         *
         */
        public function decrypt($data)
        {
            return openssl_decrypt($data, $this->method, $this->secret_key, $this->options, $this->iv);
        }
    }
    
    $aes = new OpenSSLAES('12345678');
    
    $encrypted = $aes->encrypt('凭栏知潇雨');
    // KSGYvH0GOzQULoLouXqPJA==
    echo '要加密的字符串:凭栏知潇雨<br>加密后的字符串:', $encrypted, '<hr>';
    
    $decrypted = $aes->decrypt($encrypted);
    
    echo '要解密的字符串:', $encrypted, '<br>解密后的字符串:', $decrypted;
  • 相关阅读:
    数据结构与算法之“图”
    数据结构与算法之队列、栈
    数据结构与算法之二叉搜索树
    ue mobile GI
    ue ios 用xcode 断点debug手机 显示call stack的环境搭建 /instrument 显示线程名/stat filestart
    ue 后效里宏的设置
    ue上 sceneColorMobile 在android 和ios上表现不同的问题
    减少ue编译shader的时间
    ue 搭建android/ios联机 debug环境
    对曝光的理解 autoExposure
  • 原文地址:https://www.cnblogs.com/Im-Victor/p/15176122.html
Copyright © 2011-2022 走看看