PHP 加解密工具类

wen PHP项目 2

我来提供一个功能完整的PHP加解密工具类,包含多种常用的加密方法:

PHP 加解密工具类

<?php
/**
 * PHP 加解密工具类
 * 支持 AES、DES、RSA 等常用加密算法
 */
class Encryption {
    /**
     * AES加密
     * @param string $data 待加密数据
     * @param string $key 密钥(16/24/32位)
     * @param string $iv 偏移量
     * @param string $method 加密方法
     * @return string base64编码的密文
     */
    public static function aesEncrypt($data, $key, $iv = '', $method = 'AES-128-CBC') {
        // 自动根据密钥长度选择加密方法
        if ($method == 'AUTO') {
            $keyLen = strlen($key);
            if ($keyLen == 16) {
                $method = 'AES-128-CBC';
            } elseif ($keyLen == 24) {
                $method = 'AES-192-CBC';
            } elseif ($keyLen == 32) {
                $method = 'AES-256-CBC';
            } else {
                throw new Exception('密钥长度必须是16、24或32位');
            }
        }
        // 如果未指定IV,默认使用密钥的前16位
        if (empty($iv)) {
            $iv = substr($key, 0, 16);
        }
        $encrypted = openssl_encrypt($data, $method, $key, OPENSSL_RAW_DATA, $iv);
        return base64_encode($encrypted);
    }
    /**
     * AES解密
     * @param string $encrypted base64编码的密文
     * @param string $key 密钥
     * @param string $iv 偏移量
     * @param string $method 解密方法
     * @return string 解密后的明文
     */
    public static function aesDecrypt($encrypted, $key, $iv = '', $method = 'AES-128-CBC') {
        if ($method == 'AUTO') {
            $keyLen = strlen($key);
            if ($keyLen == 16) {
                $method = 'AES-128-CBC';
            } elseif ($keyLen == 24) {
                $method = 'AES-192-CBC';
            } elseif ($keyLen == 32) {
                $method = 'AES-256-CBC';
            } else {
                throw new Exception('密钥长度必须是16、24或32位');
            }
        }
        if (empty($iv)) {
            $iv = substr($key, 0, 16);
        }
        $decrypted = openssl_decrypt(base64_decode($encrypted), $method, $key, OPENSSL_RAW_DATA, $iv);
        return $decrypted;
    }
    /**
     * DES加密
     * @param string $data 待加密数据
     * @param string $key 密钥(8字节)
     * @param string $iv 偏移量(8字节)
     * @return string base64编码的密文
     */
    public static function desEncrypt($data, $key, $iv = '') {
        if (strlen($key) != 8) {
            throw new Exception('DES密钥长度必须为8字节');
        }
        if (empty($iv)) {
            $iv = $key;
        }
        $encrypted = openssl_encrypt($data, 'DES-CBC', $key, OPENSSL_RAW_DATA, $iv);
        return base64_encode($encrypted);
    }
    /**
     * DES解密
     */
    public static function desDecrypt($encrypted, $key, $iv = '') {
        if (strlen($key) != 8) {
            throw new Exception('DES密钥长度必须为8字节');
        }
        if (empty($iv)) {
            $iv = $key;
        }
        $decrypted = openssl_decrypt(base64_decode($encrypted), 'DES-CBC', $key, OPENSSL_RAW_DATA, $iv);
        return $decrypted;
    }
    /**
     * RSA加密
     * @param string $data 待加密数据
     * @param string $publicKey 公钥(PEM格式)
     * @return string base64编码的密文
     */
    public static function rsaEncrypt($data, $publicKey) {
        $publicKey = self::formatPublicKey($publicKey);
        $result = openssl_public_encrypt($data, $encrypted, $publicKey);
        if (!$result) {
            throw new Exception('RSA加密失败');
        }
        return base64_encode($encrypted);
    }
    /**
     * RSA解密
     * @param string $encrypted base64编码的密文
     * @param string $privateKey 私钥(PEM格式)
     * @return string 解密后的明文
     */
    public static function rsaDecrypt($encrypted, $privateKey) {
        $privateKey = self::formatPrivateKey($privateKey);
        $result = openssl_private_decrypt(base64_decode($encrypted), $decrypted, $privateKey);
        if (!$result) {
            throw new Exception('RSA解密失败');
        }
        return $decrypted;
    }
    /**
     * 生成RSA密钥对
     * @param int $bits 密钥位数(1024/2048/4096)
     * @return array 包含公钥和私钥的数组
     */
    public static function generateRSAKeyPair($bits = 2048) {
        $config = [
            "private_key_bits" => $bits,
            "private_key_type" => OPENSSL_KEYTYPE_RSA,
        ];
        $res = openssl_pkey_new($config);
        openssl_pkey_export($res, $privateKey);
        $publicKey = openssl_pkey_get_details($res);
        $publicKey = $publicKey['key'];
        return [
            'public_key' => $publicKey,
            'private_key' => $privateKey
        ];
    }
    /**
     * 格式化公钥(添加BEGIN/END标记)
     */
    private static function formatPublicKey($key) {
        $key = trim($key);
        if (strpos($key, '-----BEGIN PUBLIC KEY-----') === false) {
            $key = chunk_split($key, 64, "\n");
            $key = "-----BEGIN PUBLIC KEY-----\n" . $key . "-----END PUBLIC KEY-----";
        }
        return $key;
    }
    /**
     * 格式化私钥(添加BEGIN/END标记)
     */
    private static function formatPrivateKey($key) {
        $key = trim($key);
        if (strpos($key, '-----BEGIN PRIVATE KEY-----') === false) {
            $key = chunk_split($key, 64, "\n");
            $key = "-----BEGIN PRIVATE KEY-----\n" . $key . "-----END PRIVATE KEY-----";
        }
        return $key;
    }
    /**
     * MD5加密
     * @param string $data 待加密数据
     * @param bool $rawOutput 是否返回原始格式
     * @return string 32位哈希值
     */
    public static function md5($data, $rawOutput = false) {
        return md5($data, $rawOutput);
    }
    /**
     * SHA1加密
     */
    public static function sha1($data) {
        return sha1($data);
    }
    /**
     * SHA256加密
     */
    public static function sha256($data) {
        return hash('sha256', $data);
    }
    /**
     * HMAC-SHA256加密
     * @param string $data 待加密数据
     * @param string $key 密钥
     * @return string HMAC值
     */
    public static function hmacSha256($data, $key) {
        return hash_hmac('sha256', $data, $key);
    }
    /**
     * Base64加密(URL安全)
     * @param string $data 待加密数据
     * @return string URL安全的Base64编码
     */
    public static function base64UrlEncode($data) {
        return rtrim(strtr(base64_encode($data), '+/', '-_'), '=');
    }
    /**
     * Base64解密(URL安全)
     */
    public static function base64UrlDecode($data) {
        return base64_decode(strtr($data, '-_', '+/'));
    }
    /**
     * 密码哈希(推荐用于密码存储)
     * @param string $password 明文密码
     * @return string 包含哈希和盐值的字符串
     */
    public static function passwordHash($password) {
        return password_hash($password, PASSWORD_BCRYPT);
    }
    /**
     * 密码验证
     * @param string $password 明文密码
     * @param string $hash 哈希值
     * @return bool 验证结果
     */
    public static function passwordVerify($password, $hash) {
        return password_verify($password, $hash);
    }
    /**
     * 简单对称加密(自定义算法)
     * @param string $data 待加密数据
     * @param string $key 密钥
     * @return string 加密后的字符串
     */
    public static function simpleEncrypt($data, $key) {
        $char = '';
        $str = '';
        $keyLen = strlen($key);
        $dataLen = strlen($data);
        for ($i = 0; $i < $dataLen; $i++) {
            $char = $data[$i];
            for ($j = 0; $j < $keyLen; $j++) {
                $char = chr(ord($char) ^ ord($key[$j]));
            }
            $str .= $char;
        }
        return base64_encode($str);
    }
    /**
     * 简单对称解密
     */
    public static function simpleDecrypt($data, $key) {
        $data = base64_decode($data);
        $char = '';
        $str = '';
        $keyLen = strlen($key);
        $dataLen = strlen($data);
        for ($i = 0; $i < $dataLen; $i++) {
            $char = $data[$i];
            for ($j = 0; $j < $keyLen; $j++) {
                $char = chr(ord($char) ^ ord($key[$j]));
            }
            $str .= $char;
        }
        return $str;
    }
    /**
     * 生成随机字符串
     * @param int $length 长度
     * @param string $type 类型(all/alnum/alpha/numeric)
     * @return string 随机字符串
     */
    public static function randomString($length = 16, $type = 'all') {
        switch ($type) {
            case 'alnum':
                $chars = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';
                break;
            case 'alpha':
                $chars = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
                break;
            case 'numeric':
                $chars = '0123456789';
                break;
            default:
                $chars = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789!@#$%^&*()-_=+';
        }
        return substr(str_shuffle($chars), 0, $length);
    }
    /**
     * 文件加密
     * @param string $filePath 文件路径
     * @param string $key 密钥
     * @param string $method 加密方法
     * @return string 加密后的文件路径
     */
    public static function encryptFile($filePath, $key, $method = 'AES-128-CBC') {
        $content = file_get_contents($filePath);
        $iv = openssl_random_pseudo_bytes(16);
        $encrypted = openssl_encrypt($content, $method, $key, OPENSSL_RAW_DATA, $iv);
        $encryptedFile = $filePath . '.enc';
        file_put_contents($encryptedFile, $iv . $encrypted);
        return $encryptedFile;
    }
    /**
     * 文件解密
     */
    public static function decryptFile($encryptedFile, $key, $method = 'AES-128-CBC') {
        $content = file_get_contents($encryptedFile);
        $iv = substr($content, 0, 16);
        $encrypted = substr($content, 16);
        $decrypted = openssl_decrypt($encrypted, $method, $key, OPENSSL_RAW_DATA, $iv);
        $decryptedFile = str_replace('.enc', '', $encryptedFile);
        file_put_contents($decryptedFile, $decrypted);
        return $decryptedFile;
    }
}

使用方法示例:

<?php
// 引入工具类
require_once 'Encryption.php';
// 1. AES加解密
$key = '0123456789abcdef'; // 16位密钥
$data = '你好,世界!';
$encrypted = Encryption::aesEncrypt($data, $key);
echo "AES加密:" . $encrypted . "\n";
echo "AES解密:" . Encryption::aesDecrypt($encrypted, $key) . "\n";
// 2. RSA加解密
$keyPair = Encryption::generateRSAKeyPair(2048);
$publicKey = $keyPair['public_key'];
$privateKey = $keyPair['private_key'];
$data = 'RSA加密测试数据';
$rsaEncrypted = Encryption::rsaEncrypt($data, $publicKey);
echo "RSA加密:" . $rsaEncrypted . "\n";
echo "RSA解密:" . Encryption::rsaDecrypt($rsaEncrypted, $privateKey) . "\n";
// 3. 密码哈希
$password = 'my_secure_password';
$hash = Encryption::passwordHash($password);
echo "密码哈希:" . $hash . "\n";
echo "密码验证:" . (Encryption::passwordVerify($password, $hash) ? '通过' : '失败') . "\n";
// 4. HMAC签名
$signature = Encryption::hmacSha256('要签名的数据', '密钥');
echo "HMAC签名:" . $signature . "\n";
// 5. 生成随机字符串
$randomToken = Encryption::randomString(32);
echo "随机令牌:" . $randomToken . "\n";

主要特性:

  1. AES加解密:支持多种模式(CBC、ECB等),自动判断密钥长度
  2. RSA加解密:支持生成密钥对,非对称加密
  3. 密码哈希:使用bcrypt算法,安全存储密码
  4. HMAC签名:数据完整性验证
  5. URL安全Base64:适用于URL传输
  6. 文件加解密:支持文件内容的加密保护
  7. 简单自定义加密:基于XOR运算的简单加密

安全建议:

  1. 生产环境推荐使用AES-256-CBC加密
  2. 密码存储使用passwordHash()方法
  3. 密钥、IV等敏感信息妥善保管
  4. 使用HTTPS传输加密数据
  5. 定期更换加密密钥

这个工具类涵盖了日常开发中大部分的加解密需求,并且代码清晰,易于理解和使用。

抱歉,评论功能暂时关闭!