Search code examples
phpsecurityencryptionaes

I can encrypt data but cannot decrypt


I can successfully encrypt passed data but sadly cannot decrypt it. What is wrong with my decrypt() function? Maybe it is something with my Initialization Vector(iv). Here is my code:

function pad($data, $size) {
    $length = $size - strlen($data) % $size;
    return $data . str_repeat(chr($length), $length);
}

function unpad($data) {
    return substr($data, 0, -ord($data[strlen($data) - 1]));
}

//CORRECT ENCRYPTION METHOD
function encrypt($data) {
    $key = "SiadajerSiadajer";
    $iv_size = 16; 
    $iv = openssl_random_pseudo_bytes($iv_size, $strong);
    $encryptedData = openssl_encrypt(pad($data, 16), 'AES-256-CBC', $key,   OPENSSL_RAW_DATA, $iv);
    $joinedData = hex2bin(bin2hex($iv).bin2hex($encryptedData));
    $encodedJoinedData = base64_encode($joinedData);
    return $encodedJoinedData; 
}

//WRONG DECRYPTION FUNCTION
function decrypt($encodedJoinedData){
    $key = "SiadajerSiadajer";
    $DecodedData = base64_decode($encodedJoinedData);
    $size = strlen($DecodedData);
    $cipheredsize = $size - 16;
    $iv = substr($DecodedData, 0, 16);
    $halfDecryptedData = substr($DecodedData, 16, $size);
    $decryptedData = openssl_decrypt(unpad($halfDecryptedData, 16), 'AES-256-CBC', $key, OPENSSL_RAW_DATA, $iv);
    return $decryptedData;
}

$test = encrypt("sssss");
print $test;
$test2 = decrypt($test);
print $test2;

Solution

  • In the encrypt-method replace the line

    $joinedData = hex2bin(bin2hex($iv).bin2hex($encryptedData));
    

    with

    $joinedData = $iv.$encryptedData;
    

    because the conversions in the previous expression are unnecessary. This replacement doesn't change the result.

    A possible solution for the decryption-part could be:

    function decrypt($encodedJoinedData) {
        $joinedData = base64_decode($encodedJoinedData);                        
        $iv = substr($joinedData, 0, 16);
        $encryptedData = substr($joinedData, 16);
        $key = "SiadajerSiadajer";
        $decryptedData = openssl_decrypt($encryptedData, 'AES-256-CBC', $key, OPENSSL_RAW_DATA, $iv);   
        $unpaddedData = unpad($decryptedData);                              
        return $unpaddedData;
    }