Home:ALL Converter>AES Encryption with PHP

AES Encryption with PHP

Ask Time:2021-11-30T13:06:10         Author:Kelly Flenley

Json Formatter

I am very new to PHP and have now come across encryption with PHP. I have created the PHP file to generate a key using AES and got it working but now very stuck on creating a PHP file that will do the following:

  • Store a generated key
  • Encrypt the following plaintext data: *Fido!hcteF^
  • Decrypt the encrypted data
  • Output all the following to the webpage: the key the plaintext data the encrypted data the decrypted data

I Know I need to add the follow code

The encryption function

function encryptData($data, $key) {
// remove the base64 encoding from our key so we again have the 256 bit key
$encryption_key = base64_decode($key);

// generate an IV
$iv = openssl_random_pseudo_bytes(openssl_cipher_iv_length('aes-256-cbc'));

// encrypt the data using CBC mode AES 256 encryption, also using the encryption key and IV.
$encrypted = openssl_encrypt($data, 'aes-256-cbc', $encryption_key, 0, $iv);

// The $iv is need along with the key for decrypting, so keep it with our encrypted data using a unique separator (::)
return base64_encode($encrypted . '::' . $iv);
}

and

The decryption function

function decryptData($data, $key) {
    
// remove the base64 encoding from our key so we again have the 256 bit key
$encryption_key = base64_decode($key);

// split the encrypted data from our IV - our unique separator used was "::"
list($encrypted_data, $iv) = explode('::', base64_decode($data), 2);

// use the encrypted data, the key and the IV to return the plaintext data
return openssl_decrypt($encrypted_data, 'aes-256-cbc', $encryption_key, 0, $iv);
}

Thank you for any help it is very much appreciated

Author:Kelly Flenley,eproduced under the CC 4.0 BY-SA copyright license with a link to the original source and this disclaimer.
Link to original article:https://stackoverflow.com/questions/70164576/aes-encryption-with-php
yy