Manoj Damor

Unlock the World of Coding with Coding Funda

How to encryption data in PHP using base64 with key

1 min read
How to encryption data in PHP using base64 with key

How to encryption data in PHP using base64 with key

Encrypting data in PHP using base64 encoding is not a secure method, as base64 is not an encryption algorithm but rather a method for encoding binary data. For secure encryption, you should use established encryption algorithms like AES (Advanced Encryption Standard) along with a proper key management strategy. Here’s a basic example of encrypting and decrypting data using AES in PHP:

<?php
// Encryption function
function encryptData($data, $key) {
    $cipher = "aes-256-cbc";
    $ivlen = openssl_cipher_iv_length($cipher);
    $iv = openssl_random_pseudo_bytes($ivlen);
    $ciphertext_raw = openssl_encrypt($data, $cipher, $key, $options = OPENSSL_RAW_DATA, $iv);
    $hmac = hash_hmac('sha256', $ciphertext_raw, $key, $as_binary = true);
    $ciphertext = base64_encode($iv . $hmac . $ciphertext_raw);
    return $ciphertext;
}

// Decryption function
function decryptData($ciphertext, $key) {
    $cipher = "aes-256-cbc";
    $c = base64_decode($ciphertext);
    $ivlen = openssl_cipher_iv_length($cipher);
    $iv = substr($c, 0, $ivlen);
    $hmac = substr($c, $ivlen, $sha2len = 32);
    $ciphertext_raw = substr($c, $ivlen + $sha2len);
    $original_plaintext = openssl_decrypt($ciphertext_raw, $cipher, $key, $options = OPENSSL_RAW_DATA, $iv);
    $calcmac = hash_hmac('sha256', $ciphertext_raw, $key, $as_binary = true);
    if (hash_equals($hmac, $calcmac)) {
        return $original_plaintext;
    }
    return false;
}

// Example usage
$key = "YourSecretKey";
$data = "Sensitive information";

// Encrypt data
$encryptedData = encryptData($data, $key);
echo "Encrypted Data: $encryptedData\n";

// Decrypt data
$decryptedData = decryptData($encryptedData, $key);
echo "Decrypted Data: $decryptedData\n";
?>

In this example, AES is used in CBC (Cipher Block Chaining) mode with a randomly generated IV (Initialization Vector) for each encryption. The HMAC (Hash-based Message Authentication Code) is used for integrity verification.

Remember to replace "YourSecretKey" with a strong, secret key and ensure that you handle key management securely. Also, note that this is a simplified example, and in a production environment, you should consider additional security measures and error handling.

Check My Social Profile Links

Instagram

Youtube

Website

Linkedin

Android Application

About The Author

Leave a Reply

Your email address will not be published. Required fields are marked *

Follow by Email
fb-share-icon
Share