How to encrypt and decrypt data using PHP?

In PHP, you can use encryption algorithms and related extension libraries to encrypt and decrypt data. Here is a basic example of data encryption and decryption using PHP:

Use OpenSSL extensions for encryption and decryption:

  1. encryption:

    <?php
    $data = "Hello, World!";
    $key = openssl_random_pseudo_bytes(32); // 生成随机密钥
    
    $iv = openssl_random_pseudo_bytes(16); // 生成随机初始化向量
    
    $encrypted = openssl_encrypt($data, 'aes-256-cbc', $key, 0, $iv);
    
    // 存储 $key 和 $iv 以便后续解密
    
    echo "Encrypted Data: $encrypted\n";
    ?>
    
  2. Decryption:

    <?php
    $encrypted = "encrypted-data"; // 用加密后的数据替换
    
    // 从存储的地方获取 $key 和 $iv
    
    $decrypted = openssl_decrypt($encrypted, 'aes-256-cbc', $key, 0, $iv);
    
    echo "Decrypted Data: $decrypted\n";
    ?>
    

Encryption and decryption using Sodium extension (PHP 7.2+):

  1. encryption:

    <?php
    $data = "Hello, World!";
    $key = sodium_crypto_secretbox_keygen(); // 生成随机密钥
    
    $nonce = random_bytes(SODIUM_CRYPTO_SECRETBOX_NONCEBYTES); // 生成随机 nonce
    
    $encrypted = sodium_crypto_secretbox($data, $nonce, $key);
    
    // 存储 $key 和 $nonce 以便后续解密
    
    echo "Encrypted Data: " . base64_encode($encrypted) . "\n";
    ?>
    
  2. Decryption:

    <?php
    $encrypted = base64_decode("encrypted-data"); // 用加密后的数据替换
    
    // 从存储的地方获取 $key 和 $nonce
    
    $decrypted = sodium_crypto_secretbox_open($encrypted, $nonce, $key);
    
    echo "Decrypted Data: $decrypted\n";
    ?>
    

Ensure that in actual applications, sensitive information such as keys and initialization vectors (iv/nonce) need to be stored securely and should not be directly hard-coded in the code. Key management and secure storage are key to ensuring the security of cryptographic systems.

Supongo que te gusta

Origin blog.csdn.net/u013718071/article/details/135026250
Recomendado
Clasificación