Search code examples
phpmysqlencryptionaesmcrypt

PHP AES 256 encrypt weird characters


I have the following encrypt code:

function encryptData($value){ 
   $key = "7685647tfyr65413285746352413sgfh"; 
   $text = $value; 
   $iv_size = mcrypt_get_iv_size(MCRYPT_RIJNDAEL_256, MCRYPT_MODE_ECB); 
   $iv = mcrypt_create_iv($iv_size, MCRYPT_RAND); 
   $crypttext = mcrypt_encrypt(MCRYPT_RIJNDAEL_256, $key, $text, MCRYPT_MODE_ECB, $iv); 
   return $crypttext; 
}

echo 'Encrpt: ' . encryptData('This is just a test');

The output is: Encrpt: yUB�F3�*ľ�G-�ۅd�8�f�_�X/O

I'm going to place this into a mySQL database but was unsure if it would accept those types of weird characters?

Am i doing this correctly?


Solution

  • Yes, you are doing it correctly, however the output is a binary value. To be save, it's good practice to encode it to a 'regular' string via

    $encrypted_base64 = base64_encode($crypttext);
    

    Just remember to do the opposite before decoding;

    $crypttext = base64_decode($encrypted_base64);