Developer Snippet Diary

Securely encode / encrypt and decode / decrypt a string using PHP.

First, you'll need to set up two functions—one for encryption and another for decryption. We'll use AES-256-CBC for encryption, which is a strong cipher, and you'll need to specify a secret key and an initialization vector.

<?php


function encrypt_data($data, $key='rizi_farhan_web404', $iv='1234567890123456') { 
/* $key = ;  // Ensure this key is kept secret $iv =   // 16 bytes initialization vector */
    $encrypted = openssl_encrypt($data, 'aes-256-cbc', $key, 0, $iv);
    return str_replace(array('+', '/'), array('-', '_'), base64_encode($encrypted));  // URL-safe encoding
}

function decrypt_data($data, $key='rizi_farhan_web404', $iv='1234567890123456') {
    $data = base64_decode(str_replace(array('-', '_'), array('+', '/'), $data));  // URL-safe decoding
    return openssl_decrypt($data, 'aes-256-cbc', $key, 0, $iv);
}

// Testing the functions
$originalID = 'Solmate';
$encryptedID = encrypt_data($originalID);
$decryptedID = decrypt_data($encryptedID);

echo "Original ID: $originalID\n";
echo "Encrypted ID: $encryptedID\n";
echo "Decrypted ID: $decryptedID\n";
?>

Output:

Original ID: Solmate Encrypted ID: ajVFV09UMmRoV2tvc0xXQnk5dVQ0dz09 Decrypted ID: Solmate

Key and IV: The key should be a 256-bit key for AES-256 encryption, and the initialization vector (IV) should be 16 bytes. Make sure to keep the key secure and consistent across your application to be able to decrypt the data.

Posted by: R GONDAL
Email: rizikmw@gmail.com