You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

PHP7中基于特定盐值的最简安全加解密方案咨询

Secure PHP 7 Encryption/Decryption with a Specific Salt

Hey there! Since mcrypt_encrypt got deprecated back in PHP 7.1, the go-to secure replacement is the built-in OpenSSL extension—it’s well-maintained, widely supported, and ticks all your boxes for reversible encryption with a specific salt. We’ll use AES-256-GCM here because it provides authenticated encryption (meaning it verifies your data hasn’t been tampered with), which is way more secure than older modes like CBC or ECB.

Implementation Code

Below are two straightforward functions for encryption and decryption. They use your specific salt to derive a secure key, generate a random IV (initialization vector) for each encryption, and bundle all necessary data (IV, ciphertext, and authentication tag) into a single base64-encoded string for easy storage/transmission.

Encryption Function

function encrypt(string $plaintext, string $salt): string {
    $cipher = 'aes-256-gcm';
    $ivLength = openssl_cipher_iv_length($cipher);
    
    // Generate a unique random IV for each encryption (critical for security)
    $iv = openssl_random_pseudo_bytes($ivLength);
    
    // Derive a 256-bit secure key from your salt using PBKDF2 (slow hashing to resist brute force)
    $key = hash_pbkdf2('sha256', $salt, $iv, 10000, 32, true);
    
    // Encrypt the plaintext and generate an authentication tag
    $ciphertext = openssl_encrypt(
        $plaintext,
        $cipher,
        $key,
        OPENSSL_RAW_DATA,
        $iv,
        $tag
    );
    
    // Bundle IV, tag, and ciphertext, then base64 encode for safe storage
    return base64_encode($iv . $tag . $ciphertext);
}

Decryption Function

function decrypt(string $encryptedData, string $salt): string|false {
    $cipher = 'aes-256-gcm';
    $ivLength = openssl_cipher_iv_length($cipher);
    $tagLength = 16; // Standard tag length for GCM mode
    
    // Decode the base64-encoded encrypted data
    $decodedData = base64_decode($encryptedData);
    if (!$decodedData) return false;
    
    // Extract IV, authentication tag, and ciphertext from the decoded bundle
    $iv = substr($decodedData, 0, $ivLength);
    $tag = substr($decodedData, $ivLength, $tagLength);
    $ciphertext = substr($decodedData, $ivLength + $tagLength);
    
    // Derive the same key using the salt and IV
    $key = hash_pbkdf2('sha256', $salt, $iv, 10000, 32, true);
    
    // Decrypt and verify the data (fails if tampered with or wrong salt)
    $plaintext = openssl_decrypt(
        $ciphertext,
        $cipher,
        $key,
        OPENSSL_RAW_DATA,
        $iv,
        $tag
    );
    
    return $plaintext;
}

How to Use

// Your specific secret salt (keep this safe—treat it like a password!)
$specificSalt = 'my-super-secret-salt-that-is-at-least-32-characters-long';

// Encrypt a string
$originalString = 'This is my confidential message!';
$encrypted = encrypt($originalString, $specificSalt);
echo "Encrypted Output: $encrypted\n";

// Decrypt the data back to the original string
$decrypted = decrypt($encrypted, $specificSalt);
echo "Decrypted Result: $decrypted\n"; // Should match the original string

Critical Security Notes

  • Guard your salt like a password: Never hardcode it in public code repositories. Store it in environment variables or secure, non-public config files.
  • Use a long salt: Aim for at least 32 characters (256 bits) to make brute-force attacks impractical.
  • IVs are random and unique: The code generates a new IV every time you encrypt, so identical plaintexts will produce different ciphertexts—this prevents pattern detection attacks.
  • AES-256-GCM ensures integrity: If the encrypted data is tampered with or you use the wrong salt, decrypt() will return false, so always add error handling for this case.
  • PBKDF2 slows down key derivation: The 10,000 iterations make it harder for attackers to guess your salt via brute-force. You can adjust this number (higher = more secure, but slightly slower).

内容的提问来源于stack exchange,提问作者Attila Naghi

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.15 04:22:59