Why does my variable change length in this example?

84 views Asked by At

I am trying to encrypt and decrypt a value. My example sometimes work but most of the time I am getting:

openssl_decrypt(): IV passed is 20 bytes long which is longer than the 16 expected by selected cipher, truncating

These are my 2 methods:

Encrypt

public function encrypt(string $value)
{
    $iv = random_bytes(16);

    $encrypted = openssl_encrypt($value, $this->cipher, $this->key, 0, $iv);

    return base64_encode($encrypted . '/' . $iv);
}

Decrypt

public function decrypt(string $payload)
{
    $payload = base64_decode($payload);

    list($payload, $iv) = explode('/', $payload);

    $decrypted = openssl_decrypt($payload, $this->cipher, $this->key, 0, $iv);

    return $decrypted;
}

The length of my $iv variable has changed after I decrypt it. Could anybody tell me why this happens? Whenever I var dump the random bytes output I sometimes get weird characters as well that can not be rendered.

Could anybody point my in the right direction so I can fix this?

Cheers.

0

There are 0 answers