0
votes

I have generated a unique custom key and need to encrypt a value using this key.Its return error

The only supported ciphers are AES-128-CBC and AES-256-CBC with the correct key lengths.

public function test(){

        $key = $this->generateRandomKey();
        $newEncrypter = new \Illuminate\Encryption\Encrypter( $key, Config::get('app.cipher') );
        echo $encrypted = $newEncrypter->encrypt( 'hello' );
    }

    protected function generateRandomKey()
    {
       return 'base64:'.base64_encode(
           Encrypter::generateKey(Config::get('app.cipher'))
       );
    }
2
can u try php artisan config:clear command - Yavuz Koca

2 Answers

1
votes

You should not base 64 encode the key (such as you are doing in generateRandomKey), if I'm reading the API correctly - and I presume I am because the errors match.

1
votes

Late to the party, but posting it here as that might help someone some day. The Key should be of 32 character long if AES-256-CBC is used and 16 character if AES-128-CBC is being used. From vendor\laravel\framework\src\Illuminate\Encryption\Encrypter.php you can see:

 public static function supported($key, $cipher)
    {
        $length = mb_strlen($key, '8bit');

        return ($cipher === 'AES-128-CBC' && $length === 16) ||
               ($cipher === 'AES-256-CBC' && $length === 32);
    }

For Encrypting/Decrypting using custom Key, you can use the following snippet.

$theOtherKey    = "22222222222222222222222222222222"; //32 character long
$text           = 'Hello World'; //or the text that you want to encrypt.
$newEncrypter   = new \Illuminate\Encryption\Encrypter ($theOtherKey,'AES-256-CBC');
$encrypted      = $newEncrypter->encrypt($text);
echo $encrypted;

If you prefer using AES-128-CBC, ensure your $theOtherKey is 16 character long.