所有资讯
微信公众号
微信小程序
手机App

PHP实现字符串加密解密

浏览量:47    日期:2025-06-09 14:30

使用 OpenSSL 扩展进行 AES 加密和解密

PHP的OpenSSL扩展提供了对AES加密的支持。以下是一个使用AES-256-CBC模式进行加密和解密的示例。

示例代码

<?php

function encrypt($plaintext, $key, $iv) {

    // 确保密钥长度为32字节(256位)以用于AES-256

    $key = substr(hash('sha256', $key, true), 0, 32);

    // 使用OpenSSL进行加密

    $ciphertext = openssl_encrypt($plaintext, 'aes-256-cbc', $key, OPENSSL_RAW_DATA, $iv);

    // 返回base64编码的密文

    return base64_encode($ciphertext);

}

function decrypt($ciphertext, $key, $iv) {

    // 确保密钥长度为32字节(256位)以用于AES-256

    $key = substr(hash('sha256', $key, true), 0, 32);

    // 解码base64编码的密文

    $ciphertext = base64_decode($ciphertext);

    // 使用OpenSSL进行解密

    return openssl_decrypt($ciphertext, 'aes-256-cbc', $key, OPENSSL_RAW_DATA, $iv);

}

// 示例用法

$key = "thisisaverysecurekey12345"; // 密钥(建议至少32字节)

$iv = openssl_random_pseudo_bytes(openssl_cipher_iv_length('aes-256-cbc')); // 生成一个随机的IV

$plaintext = "Hello, World!";

echo "原文: $plaintext\n";

$ciphertext = encrypt($plaintext, $key, $iv);

echo "加密后: $ciphertext\n";

// 解密时需要使用相同的IV

$decryptedtext = decrypt($ciphertext, $key, $iv);

echo "解密后: $decryptedtext\n";

?>


本文标签:
 
成为您更加专业的技术合伙人
服务热线:15165022080
加微信号:15165022080
客服QQ:1828087588、1421667633
电子邮箱:1828087588@qq.com
 
软件开发咨询:15165022080